Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0d372c1fd6 | ||
|
|
9f4eef81a3 | ||
|
|
1d9ab255eb | ||
|
|
eff12f2483 | ||
|
|
e0886c152d | ||
|
|
9ef21a64f1 | ||
|
|
1e7c6888b6 | ||
|
|
815d1c0cad |
@@ -5,6 +5,7 @@
|
||||
- **Minimal try/except**: let errors propagate — silent failures hide bugs. Only catch exceptions for intentional fault tolerance (retries, robustness).
|
||||
- **Don't touch `optimization_dtype` / `reduce_dtype`**: never change these model config fields (or their defaults in `trainer.py`) unless the user explicitly asks. They're load-bearing numerical knobs — flipping bfloat16/float32 silently changes training dynamics.
|
||||
- **Targeted comments**: don't explain your work process or reference old code. Use targeted comments sparingly to clarify ambiguous logic.
|
||||
- **Context parallelism**: a module that needs CP state holds a `CPContext` (`models/base.py`) as `self.cp_context`, defaulting to `CPContext()`, which is the non-CP case; `PreTrainedModelPrimeRL` supplies that default. `setup_context_parallel` in `utils/cp.py` builds one `CPContext` and assigns it to every module that has the field, so each module holds the same frozen object.
|
||||
- **Zen of Python**: remember the Zen of Python when writing code.
|
||||
```
|
||||
Beautiful is better than ugly.
|
||||
|
||||
+2
-2
@@ -96,7 +96,7 @@ ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
|
||||
# mount here: .git would bust the cache every commit.
|
||||
COPY --from=manifests /manifests /app
|
||||
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
|
||||
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
|
||||
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
|
||||
--no-install-workspace \
|
||||
--no-install-package prime-rl-configs \
|
||||
--no-install-package verifiers \
|
||||
@@ -132,7 +132,7 @@ RUN --mount=type=cache,target=/usr/local/share/uv/cache \
|
||||
&& \
|
||||
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" /app/deps/renderers/pyproject.toml \
|
||||
&& \
|
||||
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
|
||||
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
|
||||
&& \
|
||||
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]'
|
||||
|
||||
|
||||
@@ -204,10 +204,7 @@ These guides are designed to be run from a Slurm cluster but can also be adapted
|
||||
|
||||
1. [**Qwen3-30B-A3B**](examples/advanced/qwen3-30b-a3b/): Train `Qwen3-30B-A3B` on math, SWE, and agentic tool use.
|
||||
2. [**GLM-4.5-Air**](examples/advanced/glm-4.5-air/): Train `GLM-4.5-Air` on search, SWE, and terminal tasks.
|
||||
3. [**Nemotron-3-Super**](examples/advanced/nemotron-3-super/): Train the `Nemotron-3-Super-120B` hybrid-Mamba MoE on SWE at 131k context.
|
||||
4. [**MiniMax-M2.5 SWE**](examples/advanced/minimax-m2.5/): Train `MiniMax-M2.5` on agentic SWE tasks.
|
||||
5. [**INTELLECT-3.1**](examples/advanced/intellect-3.1/): Reproduce our `INTELLECT-3.1` training run.
|
||||
6. [**High-throughput GLM-5**](examples/advanced/glm-5.2/): Large-scale `GLM-5`/`GLM-5.2` inference with P/D disaggregation, the `llm-d` router, and FP8.
|
||||
3. [**GLM-5**](examples/advanced/glm-5.2/): Large-scale `GLM-5`/`GLM-5.2` training with P/D disaggregation, the `llm-d` router, and FP8.
|
||||
|
||||
## Docs
|
||||
|
||||
|
||||
@@ -6,6 +6,11 @@ Configurations for running prime-rl.
|
||||
environments, sized to run on a single dev machine. Each mirrors the matching
|
||||
[`examples/basic/`](../examples/basic) tutorial and is smoke-tested for one step.
|
||||
Envs: `reverse-text`, `alphabet-sort`, `wiki-search`, `wordle`, `hendrycks-sanity`.
|
||||
- **[`advanced/`](advanced)** — frontier-model training configs without launch walkthroughs:
|
||||
`minimax-m2.5` (swe), `nemotron-3-super` (swe), `deepseek-v4-flash` (sft + a standalone
|
||||
vLLM serving pre-flight). For the tutorialized equivalents, see
|
||||
[`examples/advanced/`](../examples/advanced).
|
||||
- **`evals/`** — standalone eval configs, run with `uv run evals @ configs/evals/swe.toml`.
|
||||
- **`ci/`** — integration and nightly configs used by CI.
|
||||
- **`debug/`** — throwaway configs for developing the framework itself: `algo/`
|
||||
(per-algorithm smokes), `fake/` (fake-data trainer/SFT smokes), and `multi-env/`
|
||||
|
||||
-2
@@ -22,8 +22,6 @@ num_infer_replicas = 4
|
||||
project = "nemotron-3-super"
|
||||
name = "nemotron-3-super-swe"
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
@@ -2,7 +2,7 @@
|
||||
# against DeepSeek V4 Flash on Prime Inference.
|
||||
#
|
||||
# export PRIME_API_KEY=<your Prime Inference key>
|
||||
# uv run evals @ examples/evals/swe.toml
|
||||
# uv run evals @ configs/evals/swe.toml
|
||||
#
|
||||
# The tasksets run in prime sandboxes (the default runtime), so the key also
|
||||
# authenticates sandbox creation. External API endpoints expose no vLLM
|
||||
+31
-1
@@ -184,7 +184,7 @@ $$
|
||||
\mathcal{L} = \frac{\sum \mathcal{L}_{rl}}{N_{rl}} + \frac{\sum \mathcal{L}_{ce}}{N_{ce}} + \frac{\sum \mathcal{L}_{ref\_kl}}{N_{ref\_kl}}
|
||||
$$
|
||||
|
||||
- `rl` — the configured RL loss (`[trainer.loss]`): IPO by default, or a [custom loss](#custom-loss). Fed by the advantage-assigning algorithms (`grpo`, `max_rl`, `rae`, `hierarchical_grpo`, and `echo`'s action tokens).
|
||||
- `rl` — the configured RL loss (`[trainer.loss]`): IPO by default, or optionally [IcePop](#icepop-loss) or a [custom loss](#custom-loss). Fed by the advantage-assigning algorithms (`grpo`, `max_rl`, `rae`, `hierarchical_grpo`, and `echo`'s action tokens).
|
||||
- `ce` — masked NLL. Used for frozen-model tokens (`sft`) and env-observation tokens (`echo`).
|
||||
- `ref_kl` — the per-token reverse KL to a reference model ($\log \pi_{\text{ref}} - \log \pi$) as the policy-gradient signal, importance-ratio corrected with a one-sided trust region (`opd`, `opsd`). Requires `ref_logprobs` from a [reference scoring](#reference-scoring); the scoring model must be a vLLM server (it's the only one that exposes `prompt_logprobs`).
|
||||
|
||||
@@ -215,6 +215,36 @@ The knobs under `[trainer.loss]` are:
|
||||
|
||||
Omit `[trainer.loss]` to use these defaults. Set `type = "ipo"` when you specify the section. The `ce` and `ref_kl` components are fixed and unaffected by `[trainer.loss]`.
|
||||
|
||||
### IcePop Loss
|
||||
|
||||
IcePop is an opt-in RL loss that drops tokens whose trainer-to-inference
|
||||
importance ratio falls outside a fixed acceptance band, introduced to stabilize
|
||||
MoE RL in [Every Step Evolves: Scaling Reinforcement Learning for Trillion-Scale
|
||||
Mixture-of-Experts Reasoning Models](https://arxiv.org/abs/2510.18855). Accepted
|
||||
tokens retain the importance-weighted policy-gradient term, and there is no
|
||||
separate KL penalty:
|
||||
|
||||
$$
|
||||
\mathcal{L}(\theta) = -\frac{1}{N}\sum_t
|
||||
\mathbb{1}\!\left(\alpha \le \frac{\pi(y_t)}{\mu(y_t)} \le \beta\right)
|
||||
\tau_A \hat{A}_t \frac{\pi(y_t)}{\mu(y_t)}.
|
||||
$$
|
||||
|
||||
Enable it explicitly:
|
||||
|
||||
```toml
|
||||
[trainer.loss]
|
||||
type = "icepop"
|
||||
ratio_low = 0.2
|
||||
ratio_high = 5.0
|
||||
```
|
||||
|
||||
| Knob | Default | What it does |
|
||||
|---|---|---|
|
||||
| `ratio_low` | 0.2 | Lower accepted trainer-to-inference probability ratio. |
|
||||
| `ratio_high` | 5.0 | Upper accepted trainer-to-inference probability ratio. |
|
||||
| `adv_tau` | 1.0 | Temperature on the advantage term. |
|
||||
|
||||
### Custom Loss
|
||||
|
||||
`[trainer.loss] type = "custom"` replaces the `rl` component. The loss is computed **per sequence**: you write a function that takes one sequence's tensors and returns a scalar loss. The trainer iterates and aggregates. `inputs.loss_mask` selects exactly the rl member tokens (for a plain GRPO run, all trainable tokens).
|
||||
|
||||
@@ -226,8 +226,8 @@ The shipped end-to-end examples in [`examples/`](https://github.com/PrimeIntelle
|
||||
|
||||
- [**Qwen3-30B-A3B**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/qwen3-30b-a3b) — `Qwen3-30B-A3B` on math, SWE, and tool use.
|
||||
- [**GLM-4.5-Air**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-4.5-air) — `GLM-4.5-Air` on search, SWE, and terminal.
|
||||
- [**Nemotron-3-Super**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/nemotron-3-super) — `Nemotron-3-Super-120B` hybrid-Mamba MoE on SWE at 131k context.
|
||||
- [**MiniMax-M2.5 SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/minimax-m2.5) — `MiniMax-M2.5` on agentic SWE.
|
||||
- [**Nemotron-3-Super**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/configs/advanced/nemotron-3-super) — `Nemotron-3-Super-120B` hybrid-Mamba MoE on SWE at 131k context.
|
||||
- [**MiniMax-M2.5 SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/configs/advanced/minimax-m2.5) — `MiniMax-M2.5` on agentic SWE.
|
||||
- [**INTELLECT-3.1**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/intellect-3.1) — reproduces our INTELLECT-3.1 training run.
|
||||
- [**High-throughput GLM-5**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2) — large-scale `GLM-5`/`GLM-5.2` inference with P/D disaggregation and FP8.
|
||||
|
||||
|
||||
+1
-1
@@ -148,5 +148,5 @@ VLM training (any run with `[model.vlm]` set, SFT or RL) is custom-implementatio
|
||||
3. **Always run the vision encoder.** Text-only micro-batches must feed the encoder dummy pixels and graft the result into the graph with zero contribution (`inputs_embeds + image_embeds.sum() * 0.0`) so FSDP/EP collectives stay symmetric across ranks when the encoder is trainable.
|
||||
4. **Packed-boundary consumption.** Samples pack into shared rows with per-document boundaries in `seq_lens`; every custom model's `forward()` declares the typed `seq_lens`/`seq_lens_are_pre_shard` parameters (the trainer passes them unconditionally) and must honor the boundaries — varlen flash `cu_seqlens`, linear-attention state resets per document, and a loud rejection on attention paths that can't (see the packed-batch guard in any modeling file). Set `supports_packed_multimodal_training` on the VLM model once packed rows are handled — RL fails loudly at startup for VLM models without it.
|
||||
5. **Registration.** Register the composite `model_type` in `_CUSTOM_VLM_MAPPING` (`models/__init__.py`) so `get_model` dispatches to the custom class, and describe the family in `VLM_REGISTRY` (`utils/vlm.py`).
|
||||
6. **Context parallelism (optional).** CP-capable VLMs implement `set_context_parallel_attributes` and shard embeds/positions inside the model after the vision merge; the trainers defer sharding to the model for MRoPE batches under ulysses.
|
||||
6. **Context parallelism (optional).** CP-capable VLMs hold a `CPContext` on all modules which need to be CP-aware and shard embeds/positions inside the model after the vision merge; the trainers defer sharding to the model for MRoPE batches under ulysses.
|
||||
7. **Validation.** Same bar as text models: the KL-mismatch table for the text path, plus an SFT run and an RL run on a real multimodal dataset (the `color-codeword` environment is the reference task).
|
||||
|
||||
+1
-1
@@ -232,7 +232,7 @@ gpus_per_node = 8
|
||||
|
||||
Full multi-node configs ship under [`examples/advanced/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced):
|
||||
|
||||
- [`nemotron-3-super/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/nemotron-3-super/swe.toml) — 4 trainer + 1 inference node RL on a 120B hybrid-Mamba MoE with NCCL weight broadcast.
|
||||
- [`nemotron-3-super/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/configs/advanced/nemotron-3-super/swe.toml) — 4 trainer + 1 inference node RL on a 120B hybrid-Mamba MoE with NCCL weight broadcast.
|
||||
- [`glm-5.2/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2) — large-scale and P/D-disaggregated inference across the GLM-5 family.
|
||||
|
||||
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), fronted by a single global router on node 0. Point clients at the router URL the launcher prints.
|
||||
|
||||
+34
-13
@@ -2,17 +2,38 @@
|
||||
|
||||
End-to-end usage examples for prime-rl, referenced from the top-level [README](../README.md).
|
||||
|
||||
- **[`basic/`](basic)** — walk-throughs for the core environments on 1–8 GPUs (baseline eval →
|
||||
optional SFT warmup → RL → eval), each with its own README:
|
||||
- `reverse-text` — smallest end-to-end loop (single-turn, 0.6B)
|
||||
- `alphabet-sort` — multi-turn, user simulator, LoRA
|
||||
- `wiki-search` — multi-turn tool calling, LoRA
|
||||
- `wordle` — multi-turn (~6-turn games)
|
||||
- `hendrycks-sanity` — single-turn math, long-running
|
||||
- `dynamo` — five-step Qwen3 math training with external Dynamo inference and NCCL weight updates
|
||||
- **[`advanced/`](advanced)** — larger, mostly multi-node runs on frontier models, one folder
|
||||
per model: `qwen3-30b-a3b` (math/swe/tool), `glm-4.5-air` (search/swe/terminal), `glm-5.2`
|
||||
(large-scale + PD-disaggregated inference), `minimax-m2.5` (swe), `nemotron-3-super` (swe),
|
||||
`intellect-3.1` (swe), `deepseek-v4-flash` (sft + a standalone vLLM serving pre-flight).
|
||||
New here? Follow [`basic/reverse-text/`](basic/reverse-text/README.md) first — it trains a small model end-to-end on 2 GPUs and introduces the launch → dashboard → checkpoint flow the advanced examples reuse.
|
||||
|
||||
Dev-sized (2-GPU) counterparts of `basic/` live in [`configs/basic/`](../configs/basic).
|
||||
## advanced/ — frontier models, multi-node
|
||||
|
||||
Larger runs on frontier models, one folder per model, each with a launch README covering requirements, credentials, launch, monitoring, and resume:
|
||||
|
||||
- [`qwen3-30b-a3b/`](advanced/qwen3-30b-a3b/README.md) — `Qwen3-30B-A3B` RL on math (`i3_math`), SWE (`r2e-gym`), and agentic tool use (general-agent on Modal). 2 train + 2 infer nodes; the SWE config runs at 131k context with `ep = 8` + `cp = 2`.
|
||||
- [`glm-4.5-air/`](advanced/glm-4.5-air/README.md) — `GLM-4.5-Air` (100B MoE) RL across search, SWE, and terminal domains at 131k context, with agents in sandboxes. 2 train + 4 infer nodes (SWE: 1 + 3).
|
||||
- [`glm-5.2/`](advanced/glm-5.2/README.md) — the GLM-5 family at scale: 16 trainer nodes, P/D-disaggregated FP8 inference, and an llm-d router + Mooncake KV-offload variant. Also ships standalone `infer/` pre-flights.
|
||||
- `intellect-3.1/` — reproduce the `INTELLECT-3.1` run: 4 train + 12 infer nodes on SWE.
|
||||
|
||||
All advanced configs submit through SLURM (the `rl` entrypoint writes the sbatch job when the config has a `[slurm]` table) and are monitored with `uv run dashboard`. See the per-model README for the full walkthrough.
|
||||
|
||||
## basic/ — 1 to 8 GPUs
|
||||
|
||||
Walk-throughs for the core environments (baseline eval → optional SFT warmup → RL → eval), each with its own README:
|
||||
|
||||
- [`reverse-text/`](basic/reverse-text/README.md) — smallest end-to-end loop (single-turn, 0.6B)
|
||||
- [`alphabet-sort/`](basic/alphabet-sort/README.md) — multi-turn, user simulator, LoRA
|
||||
- [`wiki-search/`](basic/wiki-search/README.md) — multi-turn tool calling, LoRA
|
||||
- [`wordle/`](basic/wordle/README.md) — multi-turn (~6-turn games)
|
||||
- [`hendrycks-sanity/`](basic/hendrycks-sanity/README.md) — single-turn math, long-running
|
||||
|
||||
## extra/ — beyond the core loop
|
||||
|
||||
Examples that don't follow the basic eval → SFT → RL walk-through pattern:
|
||||
|
||||
- [`dynamo/`](extra/dynamo/README.md) — five-step Qwen3 math training with external Dynamo inference and NCCL weight updates
|
||||
- [`vlm/`](extra/vlm/README.md) — multimodal (VLM) SFT, dense + MoE LoRA configs
|
||||
|
||||
## Related config folders
|
||||
|
||||
- Frontier-model configs without launch walkthroughs (`minimax-m2.5`, `nemotron-3-super`, `deepseek-v4-flash`) live in [`configs/advanced/`](../configs/advanced).
|
||||
- Standalone eval configs live in [`configs/evals/`](../configs/evals).
|
||||
- Dev-sized (2-GPU) counterparts of `basic/` live in [`configs/basic/`](../configs/basic).
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
# GLM-4.5-Air
|
||||
|
||||
RL on [`zai-org/GLM-4.5-Air`](https://huggingface.co/zai-org/GLM-4.5-Air) — a 100B MoE — at 131k context, across three agentic domains: web search, SWE, and terminal. Rollouts run in sandboxes ([Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default — see [Requirements](#requirements) for using your own), driven either by the `rlm` agent harness (with its `search` skill, or ipython-only) or a plain `bash` harness. All three configs share the same recipe: GRPO with a linear length penalty on input tokens (and turns, for SWE/terminal), the custom MoE trainer implementation with `cp = 4` (ulysses) context parallelism, router replay, NCCL weight broadcast, checkpoints every 50 steps (`keep_last = 1`), and evals every 20 steps (including step 0).
|
||||
|
||||
| Config | Trains on | Evals on | Topology |
|
||||
|---|---|---|---|
|
||||
| [`search.toml`](search.toml) | `openseeker` + `redsearcher` (search QA, `rlm` harness + `search` skill) | `browsecomp` (500 examples) | 2 train + 4 infer nodes |
|
||||
| [`swe.toml`](swe.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 1 train + 3 infer nodes |
|
||||
| [`terminal.toml`](terminal.toml) | `tmax` (per-task Docker image, `rlm` ipython harness) | `swebench-verified` + `terminal-bench-2` (avg@4) | 2 train + 4 infer nodes |
|
||||
|
||||
Inference serves the bf16 checkpoint as-is (no quantization), with `tensor_parallel_size = 8`. `search.toml` and `terminal.toml` train with Muon on 2 nodes; `swe.toml` fits the trainer on a single node with full optimizer offload and the stateless sign-SGD optimizer. Search answers are scored by a reference judge (`Qwen/Qwen3-235B-A22B-Instruct-2507`).
|
||||
|
||||
## Requirements
|
||||
|
||||
- A Slurm cluster with 8-GPU nodes and a shared filesystem. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path.
|
||||
- **Sandboxes.** Rollout and eval agents run in sandboxes. These configs are wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default — if you use those, log the `prime` CLI in (it ships with prime-rl's dependencies), and each config's `slurm.pre_run_command` will clean up the run's orphaned sandboxes by label before launching:
|
||||
|
||||
```bash
|
||||
uv run prime login # or: uv run prime config set-api-key <your-key>
|
||||
```
|
||||
|
||||
To run on your own infrastructure instead, swap `env.agent.runtime` on each source for a runtime your environments support (e.g. a local Docker backend) and drop the `slurm.pre_run_command` cleanup line.
|
||||
|
||||
- Environment variables, exported in the shell you launch from — the launcher passes its environment to every component:
|
||||
|
||||
- `HF_TOKEN` — `zai-org/GLM-4.5-Air` is a gated model.
|
||||
- `WANDB_API_KEY` — every config logs to W&B (`[monitors.wandb]`).
|
||||
- `SERPER_API_KEY` — search envs only; forwarded into the agent sandbox for the `search` skill (`harness.forward_env`).
|
||||
|
||||
## Setup
|
||||
|
||||
Clone prime-rl onto the shared filesystem and install everything, including the environments — they are opt-in uv workspace members, so `--all-packages` is required:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
|
||||
uv sync --all-extras --all-packages
|
||||
```
|
||||
|
||||
## Tweak before launching
|
||||
|
||||
- `[slurm] partition` is set to `all` — override with `--slurm.partition <your-partition>`, or edit the config.
|
||||
- `--output-dir` defaults to `outputs/` next to the checkout; on a cluster, point it at the shared filesystem.
|
||||
- Validate the full config without submitting a job by appending `--dry-run`: it writes `<run_dir>/launcher/rl.sbatch` plus the resolved per-process configs, and exits.
|
||||
|
||||
## Start the run
|
||||
|
||||
The `rl` entrypoint submits an sbatch job whenever the config has a `[slurm]` table — there is no separate launcher. From the shared checkout:
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/advanced/glm-4.5-air/swe.toml \
|
||||
--output-dir /shared/outputs/glm45air \
|
||||
--run.name glm45air-swe
|
||||
```
|
||||
|
||||
Swap `swe.toml` for `search.toml` or `terminal.toml` to run the other domains. Pass `--run.name`: the run directory is `<output_dir>/<run_name>` and you need a stable name to resume later (unset, it auto-generates as `<envs>--<model>--<short-id>`).
|
||||
|
||||
## Monitor with the dashboard
|
||||
|
||||
Start the local run dashboard on the head node — it only reads the run directories, so it is safe to point at a live run while the job is training:
|
||||
|
||||
```bash
|
||||
uv run dashboard /shared/outputs/glm45air # serves http://localhost:7788
|
||||
```
|
||||
|
||||
If the head node is remote, forward the port from your laptop and open `http://localhost:7788` in a browser:
|
||||
|
||||
```bash
|
||||
ssh -L 7788:localhost:7788 <head-node>
|
||||
```
|
||||
|
||||
Pick the run (`<run_name>` from the launch) and you get five views:
|
||||
|
||||
- **Metrics** — the W&B-style overview, read from the run's `metrics.jsonl`. Watch `reward/{all,env}/mean` trend upward over steps, and `seq_len/*` + `is_truncated/*` for rollout health.
|
||||
- **Configs** — the launch TOML next to the merged, resolved per-process configs the run actually started with.
|
||||
- **Trace** — a per-episode rollout viewer with per-token overlays (advantage, entropy, sampling mismatch, loss/content masks), showing the transcript, a wall-clock timeline of the rollout, a terminal replay of model and tool activity, and a semantic graph of the model-call chain.
|
||||
- **Logs** — the merged component logs (trainer, orchestrator, inference), also on disk under `<run_dir>/logs/`.
|
||||
- **Reports** — markdown reports written to `<run_dir>/reports/`, if any tooling produces them.
|
||||
|
||||
Pass several output directories to track parallel experiments side by side (`uv run dashboard /shared/outputs/a /shared/outputs/b`); a taken port automatically bumps to the next free one. SLURM stdout/stderr and the generated sbatch script land in `<run_dir>/launcher/`.
|
||||
|
||||
## Checkpoint, resume, export
|
||||
|
||||
Checkpoints land in `<run_dir>/checkpoints/step_<N>` every 50 steps (`keep_last = 1`). To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, the same `--run.name` / `--output-dir`, and a `--max-steps` at least the target final step:
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/advanced/glm-4.5-air/swe.toml \
|
||||
--output-dir /shared/outputs/glm45air \
|
||||
--run.name glm45air-swe \
|
||||
--resume --max-steps 1000
|
||||
```
|
||||
|
||||
Trainer checkpoints are DCP-sharded; export HF-format weights with:
|
||||
|
||||
```bash
|
||||
uv run python tools/convert_dcp_to_bf16.py /shared/outputs/glm45air/glm45air-swe/checkpoints/step_100
|
||||
```
|
||||
|
||||
See [Training](../../../docs/training.md) for the full knobs and metrics reference, and [Scaling](../../../docs/scaling.md) for SLURM and multi-node details.
|
||||
@@ -25,8 +25,6 @@ num_infer_replicas = 4
|
||||
project = "search-ablations"
|
||||
name = "glm45air-search"
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe` SWE taskset, bash harness on a prime sandbox
|
||||
# runtime; eval on SWE-Bench Verified. Router replay is enabled (trainer.enable_router_replay replays
|
||||
# the routed-expert decisions returned by inference via enable_return_routed_experts) — GLM-4.5-Air is
|
||||
# a glm4_moe model, which supports routed_experts.
|
||||
# runtime; eval on SWE-Bench Verified. Follows the research-prod air ablation base config
|
||||
# (research-prod PR #198): 2 trainer nodes with the Muon optimizer (instead of the single-node
|
||||
# sign-SGD setup), 4 one-node inference replicas serving the bf16 checkpoint with TP=8 + expert
|
||||
# parallelism, batch size 256 / group size 16, and the linear length penalty with the input-token
|
||||
# and turns coefficients set to 0.1. Router replay stays enabled (trainer.enable_router_replay replays the routed-expert
|
||||
# decisions returned by inference via enable_return_routed_experts) — GLM-4.5-Air is a glm4_moe
|
||||
# model, which supports routed_experts. Optimizer state is checkpointed so runs can resume.
|
||||
#
|
||||
# GRPO uses the linear length penalty with the input-token and turns coefficients set to 0.1. Each
|
||||
# term is pass_rate-scaled and normalized by the group's own max before the GRPO baseline
|
||||
# subtraction.
|
||||
# GRPO uses the linear length penalty. Each term is pass_rate-scaled and normalized by the
|
||||
# group's own max before the GRPO baseline subtraction.
|
||||
#
|
||||
# 1 train + 3 infer nodes. Inference serves the bf16 checkpoint as-is (no quantization). The trainer
|
||||
# fits on one node via cp=4 (ulysses), full CPU optimizer offload with the stateless sign-SGD optimizer, plus
|
||||
# the memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
|
||||
# chunking, activation checkpointing (freq=1) + activation offloading (max_inflight=1), and
|
||||
# skip-gather / skip-optimizer checkpointing.
|
||||
# Two trainer nodes fit GLM-4.5-Air with Muon plus the memory improvements from the GLM-5.1 prod
|
||||
# run (research-prod rlm5/prod.toml): activation checkpointing (freq=1) + activation offloading
|
||||
# (max_inflight=1). LM-head token chunking (8192) and optimizer CPU offload run at their defaults.
|
||||
# Concurrency is fully default: the controller derives its start from the measured KV budget and
|
||||
# adapts from there.
|
||||
|
||||
@@ -31,16 +32,14 @@ pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-swe" -y ||
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 1
|
||||
num_train_nodes = 2
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 3
|
||||
num_infer_replicas = 4
|
||||
|
||||
[monitors.wandb]
|
||||
project = "swe-ablations"
|
||||
name = "glm45air-scaleswe"
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
@@ -65,9 +64,6 @@ impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
cp = 4
|
||||
cp_style = "ulysses"
|
||||
optim_cpu_offload = false
|
||||
full_offload = true
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
|
||||
[trainer.model.ac]
|
||||
|
||||
@@ -76,11 +72,8 @@ max_inflight_activations = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
type = "sign_sgd"
|
||||
type = "muon"
|
||||
|
||||
# --- Orchestrator ---
|
||||
|
||||
@@ -130,6 +123,8 @@ VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.vllm]
|
||||
gpu_memory_utilization = 0.85
|
||||
max_model_len = 131072
|
||||
tensor_parallel_size = 8
|
||||
enable_expert_parallel = true
|
||||
enable_return_routed_experts = true
|
||||
|
||||
@@ -26,8 +26,6 @@ num_infer_replicas = 4
|
||||
project = "terminal-ablations"
|
||||
name = "glm45air-terminal"
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
# GLM-5 family at scale
|
||||
|
||||
Large-scale RL and serving for the GLM-5 family — `zai-org/GLM-5`, `GLM-5.1`, and `GLM-5.2-FP8` — at 131k context: 16 trainer nodes on the custom MoE implementation (expert parallelism; the llm-d variant adds context parallelism) and P/D-disaggregated FP8 inference. The `-llmd` variants front the inference plane with the [**llm-d**](https://llm-d.ai) router (Endpoint Picker + Envoy): its `active-request-scorer` load-balances in flight — instead of reacting to delayed metrics like the default `vllm-router` — which, combined with prefix-cache affinity for grouped rollouts, keeps prefill and decode ranks evenly loaded under RL's bursty request pattern. They also offload KV to a Mooncake distributed CPU pool (1TB per node by default).
|
||||
|
||||
| Config | What it runs | Topology |
|
||||
|---|---|---|
|
||||
| [`swe.toml`](swe.toml) | GLM-5 RL plane: 16 train nodes, eval on `swebench-verified` every 20 steps, default vLLM router over 2 P/D replicas (4 prefill + 4 decode nodes each). Declares **no train source** — compose yours on top with an `[[orchestrator.train.source]]` overlay. | 16 train + 16 infer nodes |
|
||||
| [`swe-llmd.toml`](swe-llmd.toml) | Full-stack GLM-5.1 RL: trains on `r2e-gym` (`rlm` harness), FP8-quantized trainer (`deepgemm_fp8` MoE compute), llm-d router + Mooncake KV offload. | 16 train + 16 infer nodes |
|
||||
| [`infer/pd.toml`](infer/pd.toml) | Inference-only pre-flight: P/D-disaggregated `GLM-5-FP8`. | 6 infer nodes |
|
||||
| [`infer/pd-llmd.toml`](infer/pd-llmd.toml) | Inference-only pre-flight: `GLM-5.2-FP8` with llm-d + Mooncake. | 16 infer nodes |
|
||||
|
||||
## Requirements
|
||||
|
||||
- A Slurm cluster with 8-GPU nodes, a shared filesystem, and at least **32 nodes** (16 trainer + 16 inference) for the RL configs. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path. If you have fewer nodes, drop `seq_len`, lower `num_train_nodes`, and reduce `cp` (llm-d variant) accordingly.
|
||||
- InfiniBand/RDMA NICs for the Mooncake KV pool (llm-d variants).
|
||||
- **Sandboxes.** Rollout and eval agents run in sandboxes, wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. If you use those, log the `prime` CLI in — it ships with prime-rl's dependencies:
|
||||
|
||||
```bash
|
||||
uv run prime login # or: uv run prime config set-api-key <your-key>
|
||||
```
|
||||
|
||||
To run on your own infrastructure instead, swap `env.agent.runtime` on each source for a runtime your environments support (e.g. a local Docker backend).
|
||||
|
||||
- Environment variables, exported in the shell you launch from — the launcher passes its environment to every component:
|
||||
|
||||
- `HF_TOKEN` — the GLM-5 family checkpoints are gated models.
|
||||
- `WANDB_API_KEY` — both RL configs log to W&B (`[monitors.wandb]`).
|
||||
|
||||
### Install llm-d (llmd variants only)
|
||||
|
||||
The llm-d router ships as vendored binaries (`epp`, `envoy`, `pd-sidecar`). Build them once into `third_party/llmd/bin`:
|
||||
|
||||
```bash
|
||||
bash scripts/install_llmd.sh
|
||||
```
|
||||
|
||||
## Setup
|
||||
|
||||
Clone prime-rl onto the shared filesystem and install everything, including the environments — they are opt-in uv workspace members, so `--all-packages` is required:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
|
||||
uv sync --all-extras --all-packages
|
||||
```
|
||||
|
||||
## Tweak before launching
|
||||
|
||||
- `swe-llmd.toml` marks two `# FILL IN` values: `output_dir` (point it at your shared filesystem) and `[slurm] partition`. `swe.toml` needs `--slurm.partition <your-partition>` or `--output-dir` overrides on the command line.
|
||||
- `[inference.kv_cache_offload] device_name` — the RDMA NIC list for Mooncake. Auto-detection is unreliable; set it by hand from `nvidia-smi topo -m` on your nodes.
|
||||
- `[inference.kv_cache_offload.cpu] num_bytes` — 1TB per node by default; lower it if your nodes have less RAM.
|
||||
- `swe-llmd.toml` ships without `[ckpt]` — add a checkpoint overlay if you want resume support.
|
||||
|
||||
## Start the run
|
||||
|
||||
The `rl` entrypoint submits an sbatch job whenever the config has a `[slurm]` table — there is no separate launcher. From the shared checkout:
|
||||
|
||||
```bash
|
||||
# GLM-5.1 RL with llm-d + Mooncake (recommended)
|
||||
uv run rl @ examples/advanced/glm-5.2/swe-llmd.toml
|
||||
|
||||
# GLM-5 base plane — compose your train source onto it
|
||||
uv run rl @ examples/advanced/glm-5.2/swe.toml @ my-train-source.toml
|
||||
```
|
||||
|
||||
The inference configs are standalone pre-flights: they serve the FP8 checkpoint through the same entrypoint the trainer uses (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster` included — never call `vllm serve` directly), and are a fast way to check that this cluster can serve the model at all before committing it to a run:
|
||||
|
||||
```bash
|
||||
uv run inference @ examples/advanced/glm-5.2/infer/pd.toml
|
||||
uv run inference @ examples/advanced/glm-5.2/infer/pd-llmd.toml
|
||||
```
|
||||
|
||||
## Monitor with the dashboard
|
||||
|
||||
Start the local run dashboard on the head node — it only reads the run directories, so it is safe to point at a live run while the job is training:
|
||||
|
||||
```bash
|
||||
uv run dashboard /shared/outputs # serves http://localhost:7788
|
||||
```
|
||||
|
||||
If the head node is remote, forward the port from your laptop and open `http://localhost:7788` in a browser:
|
||||
|
||||
```bash
|
||||
ssh -L 7788:localhost:7788 <head-node>
|
||||
```
|
||||
|
||||
Pick the run and you get five views:
|
||||
|
||||
- **Metrics** — the W&B-style overview, read from the run's `metrics.jsonl`. Watch `reward/{all,env}/mean` trend upward over steps, and `seq_len/*` + `is_truncated/*` for rollout health.
|
||||
- **Configs** — the launch TOML next to the merged, resolved per-process configs the run actually started with.
|
||||
- **Trace** — a per-episode rollout viewer with per-token overlays (advantage, entropy, sampling mismatch, loss/content masks), showing the transcript, a wall-clock timeline, a terminal replay of model and tool activity, and a semantic graph of the model-call chain.
|
||||
- **Logs** — the merged component logs (trainer, orchestrator, inference), also on disk under `<run_dir>/logs/`.
|
||||
- **Reports** — markdown reports written to `<run_dir>/reports/`, if any tooling produces them.
|
||||
|
||||
Pass several output directories to track parallel experiments side by side (`uv run dashboard /shared/outputs/a /shared/outputs/b`); a taken port automatically bumps to the next free one. SLURM stdout/stderr and the generated sbatch script land in `<run_dir>/launcher/`.
|
||||
|
||||
## Checkpoint and resume
|
||||
|
||||
`swe.toml` checkpoints every 100 steps (`[ckpt] interval = 100`). To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, a stable `--run.name`, and a `--max-steps` at least the target final step. Trainer checkpoints are DCP-sharded; export HF-format weights with `tools/convert_dcp_to_bf16.py`. See [Training](../../../docs/training.md) for the full resume and export reference.
|
||||
|
||||
See [Scaling](../../../docs/scaling.md) for SLURM details and [Inference](../../../docs/inference.md) for the disaggregated-inference and router reference.
|
||||
@@ -0,0 +1,106 @@
|
||||
# Qwen3-30B-A3B
|
||||
|
||||
RL on the 30B-A3B MoE across three domains: math, SWE, and agentic tool use. The Thinking checkpoint trains math and SWE; the tool config trains the Instruct checkpoint with colocated tools on [Modal](https://modal.com). All configs use the custom MoE trainer implementation with expert parallelism (`ep = 8`), the AdamW optimizer, NCCL weight broadcast, and W&B logging. `swe.toml` adds `cp = 2` context parallelism for its 131k context; the other two run at 32k.
|
||||
|
||||
| Config | Trains on | Evals on | Runtime | Topology |
|
||||
|---|---|---|---|---|
|
||||
| [`math.toml`](math.toml) | `i3_math` | `aime2025` (every 25 steps) | `subprocess` — runs locally, no sandbox | 2 train + 2 infer nodes |
|
||||
| [`swe.toml`](swe.toml) | `r2e-gym` (`bash` harness) | `swebench-verified` (every 25 steps) | sandbox (Prime Intellect by default) | 2 train + 2 infer nodes |
|
||||
| [`tool.toml`](tool.toml) | `general-agent` (colocated tools) | — | `modal` | 1 train + 1 infer node |
|
||||
|
||||
`tool.toml` is the odd one out: 400 steps, `group_size = 16`, checkpoints every 50 steps with `keep_last = 1`, and inference at `dp = 2` / `tp = 4`. `math.toml` and `swe.toml` run 512-task batches with checkpoints every 100 steps.
|
||||
|
||||
## Requirements
|
||||
|
||||
- A Slurm cluster with 8-GPU nodes and a shared filesystem. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path.
|
||||
- **Sandboxes** (`swe.toml` only) — the SWE agents run in sandboxes, wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. If you use those, log the `prime` CLI in (it ships with prime-rl's dependencies):
|
||||
|
||||
```bash
|
||||
uv run prime login # or: uv run prime config set-api-key <your-key>
|
||||
```
|
||||
|
||||
To run on your own infrastructure instead, swap `env.agent.runtime` on the source for a runtime your environments support (e.g. a local Docker backend).
|
||||
- **Modal** (`tool.toml` only) — the tool agents run on Modal (`env.agent.runtime.type = "modal"`). Authenticate once:
|
||||
|
||||
```bash
|
||||
uv run modal setup # or export MODAL_TOKEN_ID / MODAL_TOKEN_SECRET
|
||||
```
|
||||
|
||||
- Environment variables, exported in the shell you launch from — the launcher passes its environment to every component:
|
||||
|
||||
- `WANDB_API_KEY` — every config logs to W&B (`[monitors.wandb]`).
|
||||
- `HF_TOKEN` — optional; the Qwen checkpoints are public, but a token avoids rate limits.
|
||||
|
||||
`math.toml` needs none of the above beyond W&B: its agents run as local subprocesses on the env server.
|
||||
|
||||
## Setup
|
||||
|
||||
Clone prime-rl onto the shared filesystem and install everything, including the environments — they are opt-in uv workspace members, so `--all-packages` is required:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
|
||||
uv sync --all-extras --all-packages
|
||||
```
|
||||
|
||||
## Tweak before launching
|
||||
|
||||
- None of the configs set a `[slurm] partition` — sbatch picks your cluster default. Override with `--slurm.partition <your-partition>`.
|
||||
- `--output-dir` defaults to `outputs/` next to the checkout; on a cluster, point it at the shared filesystem.
|
||||
- Validate the full config without submitting a job by appending `--dry-run`: it writes `<run_dir>/launcher/rl.sbatch` plus the resolved per-process configs, and exits.
|
||||
|
||||
## Start the run
|
||||
|
||||
The `rl` entrypoint submits an sbatch job whenever the config has a `[slurm]` table — there is no separate launcher. From the shared checkout:
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/advanced/qwen3-30b-a3b/math.toml \
|
||||
--output-dir /shared/outputs/qwen30b \
|
||||
--run.name qwen30b-math
|
||||
```
|
||||
|
||||
Swap `math.toml` for `swe.toml` or `tool.toml` to run the other domains. Pass `--run.name`: the run directory is `<output_dir>/<run_name>` and you need a stable name to resume later (unset, it auto-generates as `<envs>--<model>--<short-id>`).
|
||||
|
||||
## Monitor with the dashboard
|
||||
|
||||
Start the local run dashboard on the head node — it only reads the run directories, so it is safe to point at a live run while the job is training:
|
||||
|
||||
```bash
|
||||
uv run dashboard /shared/outputs/qwen30b # serves http://localhost:7788
|
||||
```
|
||||
|
||||
If the head node is remote, forward the port from your laptop and open `http://localhost:7788` in a browser:
|
||||
|
||||
```bash
|
||||
ssh -L 7788:localhost:7788 <head-node>
|
||||
```
|
||||
|
||||
Pick the run and you get five views:
|
||||
|
||||
- **Metrics** — the W&B-style overview, read from the run's `metrics.jsonl`. Watch `reward/{all,env}/mean` trend upward over steps, and `seq_len/*` + `is_truncated/*` for rollout health.
|
||||
- **Configs** — the launch TOML next to the merged, resolved per-process configs the run actually started with.
|
||||
- **Trace** — a per-episode rollout viewer with per-token overlays (advantage, entropy, sampling mismatch, loss/content masks), showing the transcript, a wall-clock timeline of the rollout, a terminal replay of model and tool activity, and a semantic graph of the model-call chain.
|
||||
- **Logs** — the merged component logs (trainer, orchestrator, inference), also on disk under `<run_dir>/logs/`.
|
||||
- **Reports** — markdown reports written to `<run_dir>/reports/`, if any tooling produces them.
|
||||
|
||||
Pass several output directories to track parallel experiments side by side (`uv run dashboard /shared/outputs/a /shared/outputs/b`); a taken port automatically bumps to the next free one. SLURM stdout/stderr and the generated sbatch script land in `<run_dir>/launcher/`.
|
||||
|
||||
## Checkpoint, resume, export
|
||||
|
||||
Checkpoints land in `<run_dir>/checkpoints/step_<N>` — every 100 steps for `math.toml`/`swe.toml`, every 50 steps (`keep_last = 1`) for `tool.toml`. To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, the same `--run.name` / `--output-dir`, and a `--max-steps` at least the target final step:
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/advanced/qwen3-30b-a3b/math.toml \
|
||||
--output-dir /shared/outputs/qwen30b \
|
||||
--run.name qwen30b-math \
|
||||
--resume --max-steps 1000
|
||||
```
|
||||
|
||||
Trainer checkpoints are DCP-sharded; export HF-format weights with:
|
||||
|
||||
```bash
|
||||
uv run python tools/convert_dcp_to_bf16.py /shared/outputs/qwen30b/qwen30b-math/checkpoints/step_100
|
||||
```
|
||||
|
||||
See [Training](../../../docs/training.md) for the full knobs and metrics reference, and [Scaling](../../../docs/scaling.md) for SLURM and multi-node details.
|
||||
@@ -67,7 +67,7 @@ discovery_url = "http://dynamo.example:9000"
|
||||
After both endpoint checks pass, run Prime-RL from the repository in a third terminal. With no managed `[inference]` section, Prime-RL assigns GPU 0 to its single trainer process and leaves the external Dynamo worker on GPU 1:
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/basic/dynamo/rl.toml
|
||||
uv run rl @ examples/extra/dynamo/rl.toml
|
||||
```
|
||||
|
||||
The example stops after five optimizer steps. Outputs are written under `outputs/` unless `output_dir` is overridden.
|
||||
@@ -0,0 +1,22 @@
|
||||
# VLM SFT
|
||||
|
||||
Multimodal (VLM) supervised fine-tuning configs, dense and MoE. VLM training requires a custom PrimeRL implementation (`impl = "custom"`, `[model.vlm]` set — see [Advanced § Multimodal Training](../../../docs/advanced.md#multimodal-training)); these configs use the Qwen3.5 dense and Qwen3.6 MoE VLM implementations. Both LoRA-finetune with a frozen vision encoder and assistant-only loss masking.
|
||||
|
||||
| Config | Model | Hardware |
|
||||
|---|---|---|
|
||||
| [`sft.toml`](sft.toml) | `Qwen/Qwen3.5-0.8B` (dense, LoRA rank 16) | tiny — sanity-scale (20 steps) |
|
||||
| [`sft-moe.toml`](sft-moe.toml) | `Qwen/Qwen3.6-35B-A3B` (MoE, LoRA rank 32, `ep = 8`) | one 8-GPU node (`num_train_gpus = 8`) |
|
||||
|
||||
## Run it
|
||||
|
||||
Point `data.name` at your multimodal chat dataset (HF dataset with a `messages` column — see [Training § Dataset Format](../../../docs/training.md#dataset-format)), then:
|
||||
|
||||
```bash
|
||||
uv run sft @ examples/extra/vlm/sft.toml
|
||||
```
|
||||
|
||||
Notes:
|
||||
|
||||
- The MoE config declares `[deployment]` with `num_train_gpus = 8`; keep its `ep` in sync with the GPU count.
|
||||
- `micro_batch_size = 1` is required for VLM SFT — do not raise it.
|
||||
- Checkpoints land in `<run_dir>/checkpoints/step_<N>`; export HF-format weights with `tools/convert_dcp_to_bf16.py` (see [Training](../../../docs/training.md)).
|
||||
@@ -34,10 +34,7 @@ micro_batch_size = 1 # required for VLM SFT
|
||||
seq_len = 16384
|
||||
|
||||
[data.loss_mask]
|
||||
system = false
|
||||
user = false
|
||||
assistant = true
|
||||
tool = false
|
||||
assistant = true # only assistant turns contribute to the loss; system/user/tool default to false
|
||||
|
||||
[optim]
|
||||
lr = 1e-5
|
||||
@@ -29,5 +29,8 @@ batch_size = 1
|
||||
micro_batch_size = 1
|
||||
seq_len = 16384
|
||||
|
||||
[data.loss_mask]
|
||||
assistant = true # only assistant turns contribute to the loss; system/user/tool default to false
|
||||
|
||||
[optim]
|
||||
lr = 1e-5
|
||||
@@ -220,7 +220,7 @@ class CPUOffloadTier(BaseConfig):
|
||||
|
||||
class DiskOffloadTier(BaseConfig):
|
||||
path: Path
|
||||
"""Filesystem root for the disk tier. For ``native`` this is the ``fs_python`` secondary tier's ``root_dir``; for ``mooncake`` it is the store client's ``MOONCAKE_OFFLOAD_FILE_STORAGE_PATH``. Capacity is bounded by the filesystem at ``path`` (neither backend enforces a byte quota)."""
|
||||
"""Filesystem root for the disk tier. For ``native`` this is the ``fs`` secondary tier's ``root_dir``; for ``mooncake`` it is the store client's ``MOONCAKE_OFFLOAD_FILE_STORAGE_PATH``. Capacity is bounded by the filesystem at ``path`` (neither backend enforces a byte quota)."""
|
||||
|
||||
|
||||
class BaseKVCacheOffloadConfig(BaseConfig):
|
||||
@@ -242,14 +242,14 @@ class BaseKVCacheOffloadConfig(BaseConfig):
|
||||
|
||||
class NativeKVCacheOffloadConfig(BaseKVCacheOffloadConfig):
|
||||
type: Literal["native"] = "native"
|
||||
"""vLLM-native offloading. cpu-only uses ``OffloadingConnector`` + ``CPUOffloadingSpec``; cpu+disk uses ``TieringOffloadingSpec`` (CPU primary tier + ``fs_python`` disk secondary). Fully self-contained — no external processes."""
|
||||
"""vLLM-native offloading. cpu-only uses ``OffloadingConnector`` + ``CPUOffloadingSpec``; cpu+disk uses ``TieringOffloadingSpec`` (CPU primary tier + ``fs`` disk secondary). Fully self-contained — no external processes."""
|
||||
|
||||
def to_connector_dict(self) -> dict[str, Any]:
|
||||
assert self.cpu is not None
|
||||
extra: dict[str, Any] = {"cpu_bytes_to_use": int(self.cpu.num_bytes)}
|
||||
if self.disk is not None:
|
||||
extra["spec_name"] = "TieringOffloadingSpec"
|
||||
extra["secondary_tiers"] = [{"type": "fs_python", "root_dir": str(self.disk.path)}]
|
||||
extra["secondary_tiers"] = [{"type": "fs", "root_dir": str(self.disk.path)}]
|
||||
return {
|
||||
"kv_connector": "OffloadingConnector",
|
||||
"kv_role": "kv_both",
|
||||
|
||||
@@ -578,6 +578,25 @@ class IPOLossConfig(BaseConfig):
|
||||
"""Temperature for the KL term."""
|
||||
|
||||
|
||||
class IcePopLossConfig(BaseConfig):
|
||||
type: Literal["icepop"] = "icepop"
|
||||
|
||||
ratio_low: float = Field(0.2, gt=0)
|
||||
"""Lower accepted trainer-to-inference probability ratio."""
|
||||
|
||||
ratio_high: float = Field(5.0, gt=0)
|
||||
"""Upper accepted trainer-to-inference probability ratio."""
|
||||
|
||||
adv_tau: float = Field(1.0, ge=0)
|
||||
"""Temperature for the advantage term."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_ratio_bounds(self):
|
||||
if self.ratio_low > self.ratio_high:
|
||||
raise ValueError("ratio_low must not exceed ratio_high")
|
||||
return self
|
||||
|
||||
|
||||
class CustomLossConfig(BaseConfig):
|
||||
type: Literal["custom"] = "custom"
|
||||
|
||||
@@ -588,7 +607,7 @@ class CustomLossConfig(BaseConfig):
|
||||
"""Kwargs forwarded to the loss function."""
|
||||
|
||||
|
||||
LossConfig: TypeAlias = Annotated[IPOLossConfig | CustomLossConfig, Field(discriminator="type")]
|
||||
LossConfig: TypeAlias = Annotated[IPOLossConfig | IcePopLossConfig | CustomLossConfig, Field(discriminator="type")]
|
||||
|
||||
|
||||
class FakeDataLoaderConfig(BaseConfig):
|
||||
|
||||
@@ -73,7 +73,7 @@ The `sft` entrypoint takes the same eval shape at the top level for online evals
|
||||
|
||||
**Discriminated unions** — set the `type` field to pick the variant (`[orchestrator.algo] type = "max_rl"`). Omit `type` to keep the default variant.
|
||||
|
||||
**RL loss** — `[trainer.loss]` defaults to IPO with `eps = 0.1`, `adv_tau = 1.0`, and `kl_tau = 1e-3`. Omit the section to use these defaults. Set `type = "custom"` with `import_path` and optional `kwargs` to load a custom RL loss. The `ce` and `ref_kl` components are fixed.
|
||||
**RL loss** — `[trainer.loss]` defaults to IPO with `eps = 0.1`, `adv_tau = 1.0`, and `kl_tau = 1e-3`. Omit the section to use these defaults. Set `type = "icepop"` for ratio masking with `ratio_low = 0.2`, `ratio_high = 5.0`, and `adv_tau = 1.0`; IcePop has no separate KL term. Set `type = "custom"` with `import_path` and optional `kwargs` to load a custom RL loss. The `ce` and `ref_kl` components are fixed.
|
||||
|
||||
**Algorithms** — `[orchestrator.algo] type = "grpo" | "max_rl" | "rae" | "hierarchical_grpo" | "opd" | "opsd" | "sft" | "echo"` — the type names the algorithm (credit assignment + loss routing, fused), and each type's class defaults are its vetted setting; any other key you set is your own assembly (e.g. `[orchestrator.algo.roles.user] alpha = 0.1` for echo — setting any echo role replaces the whole role table). `hierarchical_grpo` is only valid with a proposer-solver env: it compares solvers with attempts on the same proposed problem and proposers with other proposals in the group. There is no preset layer, and no config hook that points at user code — a new algorithm is a named class in the repo (subclass `Algorithm`, register it). Per-source override: `[orchestrator.train.source.algo] type = "opd"` (the source assembles its own algorithm). prime-rl only hosts the trainable policy; frozen models are inline external endpoints on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for opd (the frozen model scored against), `[orchestrator.algo.sampling.source]` for sft (the model it samples from), each with `name` + `base_url`. There is no shared `teacher` slot. opsd declares no model — it self-distills against the live policy. See `docs/algorithms.md`.
|
||||
|
||||
|
||||
@@ -128,7 +128,7 @@ interval = 10 # completed task groups between cursor saves
|
||||
```
|
||||
|
||||
- Env servers: spawned by the evals process, one per source without an explicit `serve.address`, at `tcp://127.0.0.1:<eval.env_server_base_port + index>`; logs at `{output_dir}/logs/latest/envs/eval/{name}.log`.
|
||||
- External inference APIs (no vLLM `/metrics`, e.g. Prime Inference) have no load signal for adaptive concurrency: the startup `/metrics` probe fails fast unless the band is pinned (`min_inflight = max_inflight`). Full example: `examples/evals/swe.toml` (SWE-bench Verified + Terminal-Bench 2 on Prime Inference, `agent.timeout.rollout = 3600`).
|
||||
- External inference APIs (no vLLM `/metrics`, e.g. Prime Inference) have no load signal for adaptive concurrency: the startup `/metrics` probe fails fast unless the band is pinned (`min_inflight = max_inflight`). Full example: `configs/evals/swe.toml` (SWE-bench Verified + Terminal-Bench 2 on Prime Inference, `agent.timeout.rollout = 3600`).
|
||||
- Config: `EvalsConfig` (`packages/prime-rl-configs/src/prime_rl/configs/evals.py`)
|
||||
- Entrypoint: `src/prime_rl/entrypoints/evals.py` (implementation: `src/prime_rl/evals/evals.py`)
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ from typing import Literal
|
||||
from torch import Tensor
|
||||
from transformers.modeling_utils import PreTrainedModel
|
||||
|
||||
from prime_rl.utils.cp import CPContext
|
||||
|
||||
CPStyle = Literal["ring", "ulysses"]
|
||||
ALL_CP_STYLES: frozenset[CPStyle] = frozenset({"ring", "ulysses"})
|
||||
|
||||
@@ -25,6 +27,8 @@ class PreTrainedModelPrimeRL(PreTrainedModel):
|
||||
after loading with meta device.
|
||||
"""
|
||||
|
||||
cp_context: CPContext = CPContext()
|
||||
|
||||
@classmethod
|
||||
def cp_support(cls, config) -> CPSupport:
|
||||
"""CP styles this architecture supports, given its config.
|
||||
|
||||
@@ -136,7 +136,7 @@ from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding
|
||||
from prime_rl.trainer.models.kernels.deepseek_v4 import IGNORE_SLOT
|
||||
from prime_rl.trainer.models.kernels.fp8_indexer import fp8_indexer
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.utils.cp import gather_for_cp
|
||||
from prime_rl.utils.cp import CPContext, gather_for_cp
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
|
||||
|
||||
# Guarded because tilelang ships in the linux-gated `gpu` extra, so some installs lack it.
|
||||
@@ -690,18 +690,7 @@ class DeepseekV4Attention(nn.Module):
|
||||
compressor_class = COMPRESSOR_CLASSES[self.layer_type]
|
||||
self.compressor = compressor_class(config) if compressor_class is not None else None
|
||||
|
||||
self._cp_group: dist.ProcessGroup | None = None
|
||||
self._cp_rank: int = 0
|
||||
self._cp_world_size: int = 1
|
||||
|
||||
def set_context_parallel_attributes(self, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
|
||||
self._cp_group = cp_group
|
||||
self._cp_rank = cp_rank
|
||||
self._cp_world_size = cp_world_size
|
||||
|
||||
@property
|
||||
def cp_enabled(self) -> bool:
|
||||
return self._cp_world_size > 1
|
||||
self.cp_context = CPContext()
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor, packed: PackedContext) -> tuple[torch.Tensor, None]:
|
||||
"""`packed` carries the document boundaries every pathway below is clipped at."""
|
||||
@@ -730,13 +719,17 @@ class DeepseekV4Attention(nn.Module):
|
||||
kv = self.kv_norm(self.kv_proj(hidden_states)) # (b, t, d)
|
||||
kv = kv.view(*kv.shape[:2], 1, self.head_dim) # (b, t, 1, d)
|
||||
kv = apply_rotary_pos_emb_interleaved(kv, cos, sin, unsqueeze_dim=2)
|
||||
if self.cp_enabled:
|
||||
kv = gather_for_cp(kv, self._cp_group) # (b, T, 1, d)
|
||||
if self.cp_context.cp_enabled:
|
||||
kv = gather_for_cp(kv, self.cp_context.cp_group) # (b, T, 1, d)
|
||||
kv = kv.transpose(1, 2) # (b, 1, T, d)
|
||||
|
||||
compressed = (
|
||||
self.compressor(
|
||||
hidden_states, q_residual, packed, cp_group=self._cp_group, cp_world_size=self._cp_world_size
|
||||
hidden_states,
|
||||
q_residual,
|
||||
packed,
|
||||
cp_group=self.cp_context.cp_group,
|
||||
cp_world_size=self.cp_context.cp_world_size,
|
||||
)
|
||||
if self.compressor is not None
|
||||
else None
|
||||
|
||||
@@ -120,13 +120,17 @@ def eager_attention_forward(
|
||||
kv = module.kv_norm(module.kv_proj(hidden_states))
|
||||
kv = kv.view(*kv.shape[:2], 1, module.head_dim)
|
||||
kv = apply_rotary_pos_emb_interleaved(kv, cos, sin, unsqueeze_dim=2)
|
||||
if module.cp_enabled:
|
||||
kv = dsv4_attention.gather_for_cp(kv, module._cp_group)
|
||||
if module.cp_context.cp_enabled:
|
||||
kv = dsv4_attention.gather_for_cp(kv, module.cp_context.cp_group)
|
||||
kv = kv.transpose(1, 2)
|
||||
|
||||
compressed = (
|
||||
module.compressor(
|
||||
hidden_states, q_residual, packed, cp_group=module._cp_group, cp_world_size=module._cp_world_size
|
||||
hidden_states,
|
||||
q_residual,
|
||||
packed,
|
||||
cp_group=module.cp_context.cp_group,
|
||||
cp_world_size=module.cp_context.cp_world_size,
|
||||
)
|
||||
if module.compressor is not None
|
||||
else None
|
||||
|
||||
@@ -9,7 +9,6 @@ embedding all the way to `hc_head`, which collapses them back before the final n
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from torch import Tensor, nn
|
||||
from transformers.generation import GenerationMixin
|
||||
from transformers.modeling_layers import GradientCheckpointingLayer
|
||||
@@ -51,12 +50,6 @@ class DeepseekV4DecoderLayer(GradientCheckpointingLayer):
|
||||
self.attn_hc = DeepseekV4HyperConnection(config)
|
||||
self.ffn_hc = DeepseekV4HyperConnection(config)
|
||||
|
||||
def set_context_parallel_attributes(self, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
|
||||
self._cp_group = cp_group
|
||||
self._cp_rank = cp_rank
|
||||
self._cp_world_size = cp_world_size
|
||||
self.self_attn.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
@@ -201,13 +194,6 @@ class DeepseekV4Model(DeepseekV4PreTrainedModel):
|
||||
|
||||
self.post_init()
|
||||
|
||||
def get_cp_rank_and_world_size(self) -> tuple[int, int]:
|
||||
if len(self.layers) == 0:
|
||||
return 0, 1
|
||||
|
||||
layer = self.layers[0]
|
||||
return getattr(layer, "_cp_rank", 0), getattr(layer, "_cp_world_size", 1)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.LongTensor | None = None,
|
||||
@@ -249,7 +235,7 @@ class DeepseekV4Model(DeepseekV4PreTrainedModel):
|
||||
"""
|
||||
assert (input_ids is None) != (inputs_embeds is None), "pass exactly one of input_ids or inputs_embeds"
|
||||
|
||||
cp_rank, cp_world_size = self.get_cp_rank_and_world_size()
|
||||
cp_rank, cp_world_size = self.cp_context.cp_rank, self.cp_context.cp_world_size
|
||||
assert seq_lens_are_pre_shard == (cp_world_size > 1), (
|
||||
f"seq_lens_are_pre_shard={seq_lens_are_pre_shard} disagrees with cp_world_size={cp_world_size}"
|
||||
)
|
||||
|
||||
@@ -90,12 +90,6 @@ class GlmMoeDsaDecoderLayer(GradientCheckpointingLayer):
|
||||
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 set_context_parallel_attributes(self, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
|
||||
self._cp_group = cp_group
|
||||
self._cp_rank = cp_rank
|
||||
self._cp_world_size = cp_world_size
|
||||
self.self_attn.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
|
||||
|
||||
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
||||
def forward(
|
||||
self,
|
||||
@@ -192,13 +186,6 @@ class GlmMoeDsaModel(GlmMoeDsaPreTrainedModel):
|
||||
|
||||
self.post_init()
|
||||
|
||||
def _context_parallel_state(self) -> tuple[dist.ProcessGroup | None, int, int]:
|
||||
if len(self.layers) == 0:
|
||||
return None, 0, 1
|
||||
|
||||
layer = self.layers[0]
|
||||
return getattr(layer, "_cp_group", None), getattr(layer, "_cp_rank", 0), getattr(layer, "_cp_world_size", 1)
|
||||
|
||||
def _gather_position_ids_for_cp(
|
||||
self,
|
||||
position_ids: torch.LongTensor,
|
||||
@@ -234,9 +221,9 @@ class GlmMoeDsaModel(GlmMoeDsaPreTrainedModel):
|
||||
if inputs_embeds is None:
|
||||
inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
|
||||
|
||||
cp_group, cp_rank, cp_world_size = self._context_parallel_state()
|
||||
if cp_group is not None and cp_world_size > 1:
|
||||
position_ids_full = self._gather_position_ids_for_cp(position_ids, cp_group, cp_world_size)
|
||||
cp_rank, cp_world_size = self.cp_context.cp_rank, self.cp_context.cp_world_size
|
||||
if self.cp_context.cp_enabled:
|
||||
position_ids_full = self._gather_position_ids_for_cp(position_ids, self.cp_context.cp_group, cp_world_size)
|
||||
else:
|
||||
position_ids_full = position_ids
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ from torch import nn
|
||||
from prime_rl.trainer.models.kernels.fp8_indexer import fp8_indexer
|
||||
from prime_rl.trainer.models.layers.norms import LayerNorm, RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import rotate_half
|
||||
from prime_rl.utils.cp import gather_for_cp
|
||||
from prime_rl.utils.cp import CPContext, gather_for_cp
|
||||
|
||||
try:
|
||||
from prime_rl.trainer.models.kernels.sparse_mla_fwd import sparse_mla
|
||||
@@ -145,18 +145,7 @@ class GlmMoeDsaAttention(nn.Module):
|
||||
self.skip_topk = args.skip_topk
|
||||
self.scaling = self.qk_head_dim ** (-0.5)
|
||||
|
||||
self._cp_group: dist.ProcessGroup | None = None
|
||||
self._cp_rank: int = 0
|
||||
self._cp_world_size: int = 1
|
||||
|
||||
def set_context_parallel_attributes(self, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
|
||||
self._cp_group = cp_group
|
||||
self._cp_rank = cp_rank
|
||||
self._cp_world_size = cp_world_size
|
||||
|
||||
@property
|
||||
def cp_enabled(self) -> bool:
|
||||
return self._cp_world_size > 1
|
||||
self.cp_context = CPContext()
|
||||
|
||||
def mla_latents(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
q_latent = self.q_a_layernorm(self.q_a_proj(hidden_states))
|
||||
@@ -178,9 +167,10 @@ class GlmMoeDsaAttention(nn.Module):
|
||||
q_nope, q_rope = q_full.split([self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
|
||||
|
||||
cos_full, sin_full = position_embeddings_full
|
||||
if self.cp_enabled:
|
||||
cos_local = cos_full[:, self._cp_rank * s_local : (self._cp_rank + 1) * s_local, :]
|
||||
sin_local = sin_full[:, self._cp_rank * s_local : (self._cp_rank + 1) * s_local, :]
|
||||
if self.cp_context.cp_enabled:
|
||||
cp_rank = self.cp_context.cp_rank
|
||||
cos_local = cos_full[:, cp_rank * s_local : (cp_rank + 1) * s_local, :]
|
||||
sin_local = sin_full[:, cp_rank * s_local : (cp_rank + 1) * s_local, :]
|
||||
else:
|
||||
cos_local, sin_local = cos_full, sin_full
|
||||
|
||||
@@ -215,9 +205,9 @@ class GlmMoeDsaAttention(nn.Module):
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
q_latent, k_compressed_normed, k_rope = self.mla_latents(hidden_states)
|
||||
|
||||
if self.cp_enabled:
|
||||
k_compressed_normed = gather_for_cp(k_compressed_normed, self._cp_group)
|
||||
k_rope = gather_for_cp(k_rope, self._cp_group)
|
||||
if self.cp_context.cp_enabled:
|
||||
k_compressed_normed = gather_for_cp(k_compressed_normed, self.cp_context.cp_group)
|
||||
k_rope = gather_for_cp(k_rope, self.cp_context.cp_group)
|
||||
|
||||
indices = cached_indices
|
||||
if not self.skip_topk:
|
||||
@@ -228,9 +218,9 @@ class GlmMoeDsaAttention(nn.Module):
|
||||
ke=ke,
|
||||
index_topk=self.args.index_topk,
|
||||
position_embeddings_full=position_embeddings,
|
||||
cp_group=self._cp_group,
|
||||
cp_world_size=self._cp_world_size,
|
||||
cp_rank=self._cp_rank,
|
||||
cp_group=self.cp_context.cp_group,
|
||||
cp_world_size=self.cp_context.cp_world_size,
|
||||
cp_rank=self.cp_context.cp_rank,
|
||||
)
|
||||
|
||||
sparse_q, sparse_kv, w_v = self.mla_up_proj(
|
||||
|
||||
@@ -2,7 +2,7 @@ import torch
|
||||
from torch import Tensor, nn
|
||||
from transformers.modeling_outputs import BaseModelOutput
|
||||
|
||||
from prime_rl.trainer.models.base import ALL_CP_STYLES, CPSupport, PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.gpt_oss.attention import GptOssAttention
|
||||
from prime_rl.trainer.models.gpt_oss.configuration_gpt_oss import GptOssConfig
|
||||
from prime_rl.trainer.models.gpt_oss.converting_gpt_oss import (
|
||||
@@ -93,10 +93,6 @@ class GptOssPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
_supports_attention_backend = True
|
||||
_keep_in_fp32_modules = ["post_attention_layernorm", "input_layernorm", "norm"]
|
||||
|
||||
@classmethod
|
||||
def cp_support(cls, config) -> CPSupport:
|
||||
return CPSupport(ALL_CP_STYLES)
|
||||
|
||||
@classmethod
|
||||
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return is_hf_state_dict(state_dict)
|
||||
|
||||
@@ -14,6 +14,7 @@ from torch import nn
|
||||
|
||||
from prime_rl.trainer.distributed.collectives import all_to_all_single_equal
|
||||
from prime_rl.trainer.models.nemotron_h.configuration_nemotron_h import NemotronHConfig
|
||||
from prime_rl.utils.cp import CPContext
|
||||
|
||||
|
||||
def sequence_to_head_parallel(
|
||||
@@ -124,15 +125,7 @@ class NemotronHMamba2(nn.Module):
|
||||
with torch.no_grad():
|
||||
self.dt_bias.copy_((time_steps + torch.log(-torch.expm1(-time_steps))).to(self.dt_bias.dtype))
|
||||
|
||||
def set_context_parallel_attributes(
|
||||
self,
|
||||
process_group: dist.ProcessGroup,
|
||||
rank: int,
|
||||
world_size: int,
|
||||
) -> None:
|
||||
self.process_group = process_group
|
||||
self.context_parallel_rank = rank
|
||||
self.context_parallel_world_size = world_size
|
||||
self.cp_context = CPContext()
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor) -> torch.Tensor:
|
||||
batch_size, sequence_length, _ = hidden_states.shape
|
||||
@@ -153,11 +146,12 @@ class NemotronHMamba2(nn.Module):
|
||||
dt_bias = self.dt_bias
|
||||
norm_weight = self.norm.weight
|
||||
|
||||
if hasattr(self, "process_group"):
|
||||
world_size = self.context_parallel_world_size
|
||||
rank = self.context_parallel_rank
|
||||
gate = sequence_to_head_parallel(gate, self.process_group, world_size)
|
||||
time_step = sequence_to_head_parallel(time_step, self.process_group, world_size)
|
||||
if self.cp_context.cp_enabled:
|
||||
cp_group = self.cp_context.cp_group
|
||||
world_size = self.cp_context.cp_world_size
|
||||
rank = self.cp_context.cp_rank
|
||||
gate = sequence_to_head_parallel(gate, cp_group, world_size)
|
||||
time_step = sequence_to_head_parallel(time_step, cp_group, world_size)
|
||||
|
||||
recurrent_input, state_input, state_output = torch.split(
|
||||
convolution_input,
|
||||
@@ -166,9 +160,9 @@ class NemotronHMamba2(nn.Module):
|
||||
)
|
||||
convolution_input = torch.cat(
|
||||
[
|
||||
sequence_to_head_parallel(recurrent_input, self.process_group, world_size),
|
||||
sequence_to_head_parallel(state_input, self.process_group, world_size),
|
||||
sequence_to_head_parallel(state_output, self.process_group, world_size),
|
||||
sequence_to_head_parallel(recurrent_input, cp_group, world_size),
|
||||
sequence_to_head_parallel(state_input, cp_group, world_size),
|
||||
sequence_to_head_parallel(state_output, cp_group, world_size),
|
||||
],
|
||||
dim=-1,
|
||||
)
|
||||
@@ -238,11 +232,11 @@ class NemotronHMamba2(nn.Module):
|
||||
).reshape(batch_size, sequence_length, intermediate_size)
|
||||
hidden_states = self.norm(hidden_states, gate, weight=norm_weight)
|
||||
|
||||
if hasattr(self, "process_group"):
|
||||
if self.cp_context.cp_enabled:
|
||||
hidden_states = head_to_sequence_parallel(
|
||||
hidden_states,
|
||||
self.process_group,
|
||||
self.context_parallel_world_size,
|
||||
self.cp_context.cp_group,
|
||||
self.cp_context.cp_world_size,
|
||||
)
|
||||
return self.out_proj(hidden_states)
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from torch import Tensor, nn
|
||||
from transformers.modeling_outputs import BaseModelOutput
|
||||
|
||||
@@ -175,16 +174,6 @@ class NemotronHModel(NemotronHPreTrainedModel):
|
||||
)
|
||||
self.norm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.layer_norm_epsilon))
|
||||
|
||||
def set_context_parallel_attributes(
|
||||
self,
|
||||
process_group: dist.ProcessGroup,
|
||||
rank: int,
|
||||
world_size: int,
|
||||
) -> None:
|
||||
for module in self.layers.modules():
|
||||
if isinstance(module, NemotronHMamba2):
|
||||
module.set_context_parallel_attributes(process_group, rank, world_size)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.LongTensor,
|
||||
@@ -219,14 +208,6 @@ class NemotronHForCausalLM(NemotronHPreTrainedModel):
|
||||
self.model = NemotronHModel(config)
|
||||
self.lm_head = VanillaOutputLinear(config.hidden_size, config.vocab_size)
|
||||
|
||||
def set_context_parallel_attributes(
|
||||
self,
|
||||
process_group: dist.ProcessGroup,
|
||||
rank: int,
|
||||
world_size: int,
|
||||
) -> None:
|
||||
self.model.set_context_parallel_attributes(process_group, rank, world_size)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.LongTensor,
|
||||
|
||||
@@ -7,6 +7,7 @@ from fla.ops.gated_delta_rule import chunk_gated_delta_rule
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.trainer.models.qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfig
|
||||
from prime_rl.utils.cp import CPContext
|
||||
|
||||
# Dynamo lowers all-gather to concatenation, then fails to copy the result into
|
||||
# FLA's stacked output buffer. Keep CP convolution eager until this is fixed:
|
||||
@@ -47,12 +48,7 @@ class Qwen3_5GatedDeltaNet(nn.Module):
|
||||
self.in_proj_z = nn.Linear(config.hidden_size, self.value_dim, bias=False)
|
||||
self.in_proj_b = nn.Linear(config.hidden_size, self.num_value_heads, bias=False)
|
||||
self.in_proj_a = nn.Linear(config.hidden_size, self.num_value_heads, bias=False)
|
||||
self.context_parallel_group = None
|
||||
self.context_parallel_world_size = 1
|
||||
|
||||
def set_context_parallel_attributes(self, process_group, world_size: int) -> None:
|
||||
self.context_parallel_group = process_group
|
||||
self.context_parallel_world_size = world_size
|
||||
self.cp_context = CPContext()
|
||||
|
||||
def forward(
|
||||
self,
|
||||
@@ -68,10 +64,10 @@ class Qwen3_5GatedDeltaNet(nn.Module):
|
||||
decay = -self.A_log.float().exp() * F.softplus(self.in_proj_a(hidden_states).float() + self.dt_bias)
|
||||
|
||||
context = None
|
||||
if self.context_parallel_group is not None:
|
||||
if self.cp_context.cp_enabled:
|
||||
context = build_cp_context(
|
||||
cu_seqlens=cu_seqlens.to(device=hidden_states.device, dtype=torch.int32),
|
||||
group=self.context_parallel_group,
|
||||
group=self.cp_context.cp_group,
|
||||
conv1d_kernel_size=self.conv_kernel_size,
|
||||
)
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ from prime_rl.trainer.models.qwen3_5.rotary_embedding import (
|
||||
build_qwen3_5_mrope_position_ids,
|
||||
)
|
||||
from prime_rl.trainer.models.qwen3_5.vision import Qwen3_5VisionModel
|
||||
from prime_rl.utils.cp import setup_cp_attention_params, shard_for_cp, shard_position_ids_for_cp
|
||||
from prime_rl.utils.cp import CPContext, setup_cp_attention_params, shard_for_cp, shard_position_ids_for_cp
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
|
||||
|
||||
|
||||
@@ -163,14 +163,6 @@ class Qwen3_5Model(Qwen3_5PreTrainedModel):
|
||||
def set_input_embeddings(self, embeddings: nn.Embedding) -> None:
|
||||
self.embed_tokens = embeddings
|
||||
|
||||
def set_context_parallel_attributes(self, process_group, rank: int, world_size: int) -> None:
|
||||
self.context_parallel_group = process_group
|
||||
self.context_parallel_rank = rank
|
||||
self.context_parallel_world_size = world_size
|
||||
for module in self.modules():
|
||||
if isinstance(module, Qwen3_5GatedDeltaNet):
|
||||
module.set_context_parallel_attributes(process_group, world_size)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.LongTensor | None = None,
|
||||
@@ -212,6 +204,7 @@ class Qwen3_5VLMModel(nn.Module):
|
||||
self.config = config
|
||||
self.visual = Qwen3_5VisionModel(config.vision_config)
|
||||
self.language_model = Qwen3_5Model(config.text_config)
|
||||
self.cp_context = CPContext()
|
||||
|
||||
def get_input_embeddings(self) -> nn.Embedding:
|
||||
return self.language_model.get_input_embeddings()
|
||||
@@ -219,9 +212,6 @@ class Qwen3_5VLMModel(nn.Module):
|
||||
def set_input_embeddings(self, embeddings: nn.Embedding) -> None:
|
||||
self.language_model.set_input_embeddings(embeddings)
|
||||
|
||||
def set_context_parallel_attributes(self, process_group, rank: int, world_size: int) -> None:
|
||||
self.language_model.set_context_parallel_attributes(process_group, rank, world_size)
|
||||
|
||||
def prepare_inputs(
|
||||
self,
|
||||
input_ids: torch.LongTensor,
|
||||
@@ -295,11 +285,14 @@ class Qwen3_5VLMModel(nn.Module):
|
||||
mm_token_type_ids,
|
||||
seq_lens,
|
||||
)
|
||||
process_group = getattr(self.language_model, "context_parallel_group", None)
|
||||
if image_grid_thw is not None and process_group is not None:
|
||||
rank = self.language_model.context_parallel_rank
|
||||
world_size = self.language_model.context_parallel_world_size
|
||||
setup_cp_attention_params(position_ids, cp_group=process_group, cp_style="ulysses", seq_lens=seq_lens)
|
||||
if image_grid_thw is not None and self.cp_context.cp_enabled:
|
||||
rank, world_size = self.cp_context.cp_rank, self.cp_context.cp_world_size
|
||||
setup_cp_attention_params(
|
||||
position_ids,
|
||||
cp_group=self.cp_context.cp_group,
|
||||
cp_style=self.cp_context.cp_style,
|
||||
seq_lens=seq_lens,
|
||||
)
|
||||
inputs_embeds = shard_for_cp(inputs_embeds, cp_rank=rank, cp_world_size=world_size)
|
||||
position_ids = shard_position_ids_for_cp(position_ids, cp_rank=rank, cp_world_size=world_size)
|
||||
if routed_experts is not None:
|
||||
@@ -335,9 +328,6 @@ class Qwen3_5ForCausalLM(Qwen3_5PreTrainedModel):
|
||||
def set_input_embeddings(self, embeddings: nn.Embedding) -> None:
|
||||
self.model.set_input_embeddings(embeddings)
|
||||
|
||||
def set_context_parallel_attributes(self, process_group, rank: int, world_size: int) -> None:
|
||||
self.model.set_context_parallel_attributes(process_group, rank, world_size)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.LongTensor | None = None,
|
||||
|
||||
@@ -19,6 +19,18 @@ class CPUOffloadOptimizer(OffloadOptimizer):
|
||||
self.optimizer = optimizer
|
||||
self.pin_memory = pin_memory
|
||||
self._initialized = False
|
||||
self._cpu_buffers: dict[tuple[torch.Tensor, str], torch.Tensor] = {}
|
||||
|
||||
def _offload_to_cpu(self, param: torch.Tensor, key: str, src: torch.Tensor) -> torch.Tensor:
|
||||
if not self.pin_memory:
|
||||
return src.to("cpu", non_blocking=True)
|
||||
buffer = self._cpu_buffers.get((param, key))
|
||||
if buffer is None or buffer.shape != src.shape or buffer.dtype != src.dtype:
|
||||
buffer = torch.empty(src.shape, dtype=src.dtype, device="cpu", pin_memory=True)
|
||||
self._cpu_buffers[(param, key)] = buffer
|
||||
if buffer is not src:
|
||||
buffer.copy_(src, non_blocking=True)
|
||||
return buffer
|
||||
|
||||
def _move_states(self, device: str):
|
||||
"""Move optimizer states to CPU or back to GPU (matching each parameter's device)."""
|
||||
@@ -28,10 +40,7 @@ class CPUOffloadOptimizer(OffloadOptimizer):
|
||||
if isinstance(value, DTensor):
|
||||
local_tensor = value._local_tensor
|
||||
if device == "cpu":
|
||||
non_blocking = not self.pin_memory
|
||||
new_local = local_tensor.to("cpu", non_blocking=non_blocking)
|
||||
if self.pin_memory and not new_local.is_pinned():
|
||||
new_local = new_local.pin_memory()
|
||||
new_local = self._offload_to_cpu(param, key, local_tensor)
|
||||
else:
|
||||
new_local = local_tensor.to(device, non_blocking=True)
|
||||
new_dtensor = copy.copy(value)
|
||||
@@ -39,13 +48,11 @@ class CPUOffloadOptimizer(OffloadOptimizer):
|
||||
state[key] = new_dtensor
|
||||
elif isinstance(value, torch.Tensor):
|
||||
if device == "cpu":
|
||||
non_blocking = not self.pin_memory
|
||||
cpu_tensor = value.to("cpu", non_blocking=non_blocking)
|
||||
if self.pin_memory and not cpu_tensor.is_pinned():
|
||||
cpu_tensor = cpu_tensor.pin_memory()
|
||||
state[key] = cpu_tensor
|
||||
state[key] = self._offload_to_cpu(param, key, value)
|
||||
else:
|
||||
state[key] = value.to(device, non_blocking=True)
|
||||
if device == "cpu" and torch.cuda.is_initialized():
|
||||
torch.cuda.synchronize()
|
||||
|
||||
def step(self, closure=None):
|
||||
# First step initializes states on GPU - offload after
|
||||
|
||||
+105
-49
@@ -1,12 +1,12 @@
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Callable
|
||||
from typing import Any, Callable, Protocol
|
||||
|
||||
import torch
|
||||
from beartype import beartype as typechecker
|
||||
from jaxtyping import Bool, Float, Int, jaxtyped
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.configs.trainer import CustomLossConfig, IPOLossConfig, LossConfig
|
||||
from prime_rl.configs.trainer import CustomLossConfig, IcePopLossConfig, IPOLossConfig, LossConfig
|
||||
from prime_rl.trainer.models.layers.lm_head import sampling_replay_mask
|
||||
from prime_rl.utils.utils import import_object
|
||||
|
||||
@@ -37,10 +37,18 @@ class LossOutputs:
|
||||
metrics: dict[str, Tensor]
|
||||
|
||||
|
||||
LossFn = Callable[..., LossOutputs]
|
||||
"""Type for a per-sample loss function.
|
||||
class Loss(Protocol):
|
||||
"""Interface for the config-initialized rl loss objects built by
|
||||
``setup_rl_loss_fn``: ``IPOLoss``, ``IcePopLoss`` and ``CustomLoss``."""
|
||||
|
||||
Expected signature:
|
||||
def loss(self, inputs: LossInputs) -> LossOutputs: ...
|
||||
|
||||
|
||||
LossFn = Callable[..., LossOutputs]
|
||||
"""Type for a per-sample loss function, as opposed to a ``Loss`` object: the
|
||||
fixed ce / ref_kl losses and the function imported from ``CustomLossConfig``.
|
||||
|
||||
Expected signature for a custom loss:
|
||||
def my_loss(inputs: LossInputs, **kwargs) -> LossOutputs:
|
||||
...
|
||||
"""
|
||||
@@ -129,39 +137,80 @@ def compute_importance_ratio_and_mismatch_kl(
|
||||
return log_importance_ratio, importance_ratio, mismatch_kl
|
||||
|
||||
|
||||
def ipo_loss_fn(inputs: LossInputs, loss_config: IPOLossConfig) -> LossOutputs:
|
||||
class IPOLoss:
|
||||
"""IPO loss type: a symmetric trust region (mask tokens whose probability
|
||||
moved more than ``eps`` in absolute terms), policy gradient via
|
||||
the importance ratio, and a squared-log-ratio KL regularizer."""
|
||||
trainer_logprobs = inputs.trainer_logprobs
|
||||
inference_logprobs = inputs.inference_logprobs
|
||||
advantages = inputs.advantages
|
||||
loss_mask = inputs.loss_mask
|
||||
|
||||
log_importance_ratio, importance_ratio, mismatch_kl = compute_importance_ratio_and_mismatch_kl(
|
||||
trainer_logprobs, inference_logprobs
|
||||
)
|
||||
def __init__(self, config: IPOLossConfig):
|
||||
self.config = config
|
||||
|
||||
abs_probs_diff = torch.abs(torch.exp(trainer_logprobs) - torch.exp(inference_logprobs))
|
||||
def loss(self, inputs: LossInputs) -> LossOutputs:
|
||||
loss_config = self.config
|
||||
trainer_logprobs = inputs.trainer_logprobs
|
||||
inference_logprobs = inputs.inference_logprobs
|
||||
advantages = inputs.advantages
|
||||
loss_mask = inputs.loss_mask
|
||||
|
||||
is_masked = abs_probs_diff > loss_config.eps
|
||||
keep_mask = loss_mask & ~is_masked
|
||||
log_importance_ratio, importance_ratio, mismatch_kl = compute_importance_ratio_and_mismatch_kl(
|
||||
trainer_logprobs, inference_logprobs
|
||||
)
|
||||
|
||||
advantages = loss_config.adv_tau * advantages
|
||||
pg_loss = keep_mask * advantages * importance_ratio
|
||||
kl_loss = loss_mask * log_importance_ratio**2
|
||||
per_token_loss = -pg_loss + loss_config.kl_tau * kl_loss
|
||||
if inputs.loss_weights is not None:
|
||||
per_token_loss = per_token_loss * inputs.loss_weights
|
||||
loss = per_token_loss.sum()
|
||||
abs_probs_diff = torch.abs(torch.exp(trainer_logprobs) - torch.exp(inference_logprobs))
|
||||
|
||||
metrics = {
|
||||
"masked_mismatch_kl": _safe_mean(mismatch_kl, loss_mask & is_masked), # all trainable, masked tokens
|
||||
"unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask), # all trainable, unmasked tokens
|
||||
"is_masked": _safe_mean(is_masked, loss_mask),
|
||||
}
|
||||
is_masked = abs_probs_diff > loss_config.eps
|
||||
keep_mask = loss_mask & ~is_masked
|
||||
|
||||
return LossOutputs(loss=loss, metrics=metrics)
|
||||
advantages = loss_config.adv_tau * advantages
|
||||
pg_loss = keep_mask * advantages * importance_ratio
|
||||
kl_loss = loss_mask * log_importance_ratio**2
|
||||
per_token_loss = -pg_loss + loss_config.kl_tau * kl_loss
|
||||
if inputs.loss_weights is not None:
|
||||
per_token_loss = per_token_loss * inputs.loss_weights
|
||||
loss = per_token_loss.sum()
|
||||
|
||||
metrics = {
|
||||
"masked_mismatch_kl": _safe_mean(mismatch_kl, loss_mask & is_masked), # all trainable, masked tokens
|
||||
"unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask), # all trainable, unmasked tokens
|
||||
"is_masked": _safe_mean(is_masked, loss_mask),
|
||||
}
|
||||
|
||||
return LossOutputs(loss=loss, metrics=metrics)
|
||||
|
||||
|
||||
class IcePopLoss:
|
||||
"""IcePop loss type: policy gradient with a fixed importance-ratio
|
||||
acceptance band."""
|
||||
|
||||
def __init__(self, config: IcePopLossConfig):
|
||||
self.config = config
|
||||
|
||||
def loss(self, inputs: LossInputs) -> LossOutputs:
|
||||
loss_config = self.config
|
||||
log_importance_ratio, _, mismatch_kl = compute_importance_ratio_and_mismatch_kl(
|
||||
inputs.trainer_logprobs, inputs.inference_logprobs
|
||||
)
|
||||
|
||||
log_ratio_low = log_importance_ratio.new_tensor(loss_config.ratio_low).log()
|
||||
log_ratio_high = log_importance_ratio.new_tensor(loss_config.ratio_high).log()
|
||||
detached_log_ratio = log_importance_ratio.detach()
|
||||
is_masked = (detached_log_ratio < log_ratio_low) | (detached_log_ratio > log_ratio_high)
|
||||
keep_mask = inputs.loss_mask & ~is_masked
|
||||
|
||||
# Mask before exponentiation so rejected extreme ratios cannot produce
|
||||
# 0 * inf = NaN in the loss or its gradient.
|
||||
safe_log_ratio = torch.where(keep_mask, log_importance_ratio, torch.zeros_like(log_importance_ratio))
|
||||
importance_ratio = torch.exp(safe_log_ratio)
|
||||
per_token_loss = -(keep_mask * loss_config.adv_tau * inputs.advantages * importance_ratio)
|
||||
if inputs.loss_weights is not None:
|
||||
per_token_loss = per_token_loss * inputs.loss_weights
|
||||
|
||||
metrics = {
|
||||
"masked_mismatch_kl": _safe_mean(mismatch_kl, inputs.loss_mask & is_masked),
|
||||
"unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask),
|
||||
"is_masked": _safe_mean(is_masked, inputs.loss_mask),
|
||||
}
|
||||
return LossOutputs(loss=per_token_loss.sum(), metrics=metrics)
|
||||
|
||||
|
||||
def ref_kl_loss_fn(inputs: LossInputs) -> LossOutputs:
|
||||
@@ -227,23 +276,30 @@ def ce_loss_fn(inputs: LossInputs) -> LossOutputs:
|
||||
return LossOutputs(loss=loss, metrics=metrics)
|
||||
|
||||
|
||||
def setup_rl_loss_fn(loss_config: LossConfig) -> LossFn:
|
||||
"""Build the loss fn for the rl component from ``trainer.loss``:
|
||||
``ipo_loss_fn`` (``IPOLossConfig``) or the imported function
|
||||
(``CustomLossConfig``).
|
||||
class CustomLoss:
|
||||
"""Custom loss type: the loss function imported from ``import_path``,
|
||||
called with ``kwargs``."""
|
||||
|
||||
def __init__(self, config: CustomLossConfig):
|
||||
self.config = config
|
||||
self.fn: LossFn = import_object(config.import_path)
|
||||
|
||||
def loss(self, inputs: LossInputs) -> LossOutputs:
|
||||
return self.fn(inputs, **self.config.kwargs)
|
||||
|
||||
|
||||
def setup_rl_loss_fn(loss_config: LossConfig) -> Loss:
|
||||
"""Build the loss object for the rl component from ``trainer.loss``.
|
||||
The ce / ref_kl loss types are fixed and unaffected by ``trainer.loss``."""
|
||||
if isinstance(loss_config, CustomLossConfig):
|
||||
custom_fn = import_object(loss_config.import_path)
|
||||
kwargs = loss_config.kwargs
|
||||
|
||||
def rl_fn(inputs: LossInputs) -> LossOutputs:
|
||||
return custom_fn(inputs, **kwargs)
|
||||
else:
|
||||
|
||||
def rl_fn(inputs: LossInputs) -> LossOutputs:
|
||||
return ipo_loss_fn(inputs, loss_config)
|
||||
|
||||
return rl_fn
|
||||
match loss_config:
|
||||
case CustomLossConfig():
|
||||
return CustomLoss(loss_config)
|
||||
case IPOLossConfig():
|
||||
return IPOLoss(loss_config)
|
||||
case IcePopLossConfig():
|
||||
return IcePopLoss(loss_config)
|
||||
case _:
|
||||
raise TypeError(f"Unsupported RL loss config: {type(loss_config).__name__}")
|
||||
|
||||
|
||||
def compute_loss(
|
||||
@@ -255,7 +311,7 @@ def compute_loss(
|
||||
rl_weights: list[Float[Tensor, " seq_i"]] | None,
|
||||
ce_weights: list[Float[Tensor, " seq_i"]] | None,
|
||||
ref_kl_weights: list[Float[Tensor, " seq_i"]] | None,
|
||||
rl_loss_fn: LossFn,
|
||||
rl_loss_fn: Loss,
|
||||
rl_scale: int,
|
||||
ce_scale: int,
|
||||
ref_kl_scale: int,
|
||||
@@ -286,7 +342,7 @@ def compute_loss(
|
||||
rl_weights: Per-token rl weights for each sequence, or None (1.0 on the loss mask)
|
||||
ce_weights: Per-token ce weights for each sequence, or None (no ce component)
|
||||
ref_kl_weights: Per-token ref_kl weights for each sequence, or None (no ref_kl component)
|
||||
rl_loss_fn: Loss fn for the rl component from setup_rl_loss_fn()
|
||||
rl_loss_fn: RL loss object built by setup_rl_loss_fn()
|
||||
rl_scale: Global rl-token count normalizing the rl component
|
||||
ce_scale: Global ce-token count normalizing the ce component
|
||||
ref_kl_scale: Global ref_kl-token count normalizing the ref_kl component
|
||||
@@ -341,11 +397,11 @@ def compute_loss(
|
||||
)
|
||||
|
||||
if rl_w is None:
|
||||
rl_loss = rl_loss + run_loss_fn(rl_loss_fn, make_inputs(mask, None))
|
||||
rl_loss = rl_loss + run_loss_fn(rl_loss_fn.loss, make_inputs(mask, None))
|
||||
else:
|
||||
rl_mask = mask & (rl_w != 0)
|
||||
if bool(rl_mask.any()):
|
||||
rl_loss = rl_loss + run_loss_fn(rl_loss_fn, make_inputs(rl_mask, rl_w))
|
||||
rl_loss = rl_loss + run_loss_fn(rl_loss_fn.loss, make_inputs(rl_mask, rl_w))
|
||||
if ce_w is not None:
|
||||
ce_mask = ce_w != 0
|
||||
if bool(ce_mask.any()):
|
||||
|
||||
@@ -8,7 +8,6 @@ from datetime import timedelta
|
||||
# Import environment before any other imports
|
||||
# ruff: noqa: I001
|
||||
|
||||
from prime_rl.trainer.models.layers.attn import substitute_ring_attn
|
||||
from prime_rl.transports.weights import prune_broadcasts_beyond, setup_weight_sender
|
||||
from prime_rl.utils.act_offloading import maybe_activation_offloading
|
||||
import torch
|
||||
@@ -22,6 +21,7 @@ from prime_rl.trainer.rl.data import DataLoader, FakeDataLoader
|
||||
from prime_rl.utils.cp import (
|
||||
gather_for_cp,
|
||||
gather_for_cp_wo_grad,
|
||||
setup_context_parallel,
|
||||
setup_cp_params,
|
||||
shard_for_cp,
|
||||
)
|
||||
@@ -69,7 +69,6 @@ from prime_rl import monitors
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
from prime_rl.utils.utils import clean_exit, resolve_latest_ckpt_step
|
||||
from ring_flash_attn import substitute_hf_flash_attn
|
||||
|
||||
|
||||
@clean_exit
|
||||
@@ -192,27 +191,7 @@ def train(config: TrainerConfig):
|
||||
logger.debug(f"Initialized weight broadcast in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
if parallel_dims.cp_enabled:
|
||||
cp_group = parallel_dims.world_mesh["cp"].get_group()
|
||||
cp_rank = parallel_dims.world_mesh["cp"].get_local_rank()
|
||||
if config.model.cp_style == "ring":
|
||||
substitute_hf_flash_attn(cp_group, heads_k_stride=1)
|
||||
substitute_ring_attn(cp_group, heads_k_stride=1, attn_impl=config.model.attn)
|
||||
else:
|
||||
from prime_rl.trainer.models.layers.ulysses_attn import (
|
||||
substitute_hf_ulysses_attn,
|
||||
substitute_ulysses_attn,
|
||||
)
|
||||
|
||||
substitute_hf_ulysses_attn(cp_group)
|
||||
substitute_ulysses_attn(cp_group, attn_impl=config.model.attn)
|
||||
from prime_rl.utils.cp import setup_model_cp, setup_sparse_mla_cp
|
||||
|
||||
# sparse MLA is softmax (works with both ring and ulysses).
|
||||
setup_sparse_mla_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
# Linear-attn / Mamba layers are only configured under ulysses; models that have them
|
||||
# declare ulysses-only in `cp_support`, so `get_model` already rejected ring.
|
||||
if config.model.cp_style == "ulysses":
|
||||
setup_model_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
setup_context_parallel(model, config.model, parallel_dims)
|
||||
|
||||
# Fresh adapter init after FSDP materialization (the pretrained checkpoint
|
||||
# carries no adapter weights); a checkpoint resume below overwrites it.
|
||||
|
||||
@@ -7,13 +7,11 @@ from contextlib import nullcontext
|
||||
from datetime import timedelta
|
||||
|
||||
from renderers.base import create_renderer
|
||||
from ring_flash_attn import substitute_hf_flash_attn
|
||||
from torch.nn import CrossEntropyLoss
|
||||
|
||||
# Import environment before any other imports
|
||||
# ruff: noqa: I001
|
||||
|
||||
from prime_rl.trainer.models.layers.attn import substitute_ring_attn
|
||||
from prime_rl.utils.act_offloading import maybe_activation_offloading
|
||||
import torch
|
||||
from torch.profiler import profile, ProfilerActivity, record_function
|
||||
@@ -22,7 +20,7 @@ from prime_rl.utils.pathing import resolve_latest_ckpt_step
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
from prime_rl.configs.trainer import CheckpointConfig
|
||||
from prime_rl.transports.weights import prune_broadcasts_beyond, setup_weight_sender
|
||||
from prime_rl.utils.cp import setup_cp_params, shard_for_cp
|
||||
from prime_rl.utils.cp import setup_context_parallel, setup_cp_params, shard_for_cp
|
||||
from prime_rl.trainer.lora import get_lora_state
|
||||
from prime_rl.trainer.models.layers.lora import set_lora_num_tokens
|
||||
from prime_rl.utils.logger import format_time, setup_logger
|
||||
@@ -35,7 +33,6 @@ from prime_rl.trainer.model import (
|
||||
is_tt_moe_model,
|
||||
setup_processor,
|
||||
setup_tokenizer,
|
||||
resolve_auto_attn,
|
||||
setup_model,
|
||||
)
|
||||
from prime_rl.trainer.parallel_dims import get_parallel_dims, resolve_ep
|
||||
@@ -124,25 +121,8 @@ def train(config: SFTConfig):
|
||||
)
|
||||
grad_accum_steps = total_micro_batches // micro_batches_per_step
|
||||
|
||||
# Resolve attn='auto' before CP setup so ring/ulysses patches use the correct kernel
|
||||
resolve_auto_attn(config.model)
|
||||
|
||||
if parallel_dims.cp_enabled:
|
||||
assert config.data.seq_len % parallel_dims.cp == 0, "Sequence length must be divisible by CP degree"
|
||||
cp_group = parallel_dims.world_mesh["cp"].get_group()
|
||||
cp_rank = parallel_dims.world_mesh["cp"].get_local_rank()
|
||||
if config.model.cp_style == "ring":
|
||||
substitute_hf_flash_attn(cp_group, heads_k_stride=1)
|
||||
substitute_ring_attn(cp_group, heads_k_stride=1, attn_impl=config.model.attn)
|
||||
else:
|
||||
from prime_rl.trainer.models.layers.ulysses_attn import (
|
||||
substitute_hf_ulysses_attn,
|
||||
substitute_ulysses_attn,
|
||||
)
|
||||
|
||||
substitute_hf_ulysses_attn(cp_group)
|
||||
substitute_ulysses_attn(cp_group, attn_impl=config.model.attn)
|
||||
from prime_rl.utils.cp import setup_model_cp, setup_sparse_mla_cp
|
||||
|
||||
# Set up checkpoint manager
|
||||
logger.info(f"Initializing checkpoint manager ({config.ckpt})")
|
||||
@@ -163,12 +143,7 @@ def train(config: SFTConfig):
|
||||
model = setup_model(config.model, parallel_dims, loading_from_ckpt_later)
|
||||
|
||||
if parallel_dims.cp_enabled:
|
||||
# sparse MLA is softmax (works with both ring and ulysses).
|
||||
setup_sparse_mla_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
# Linear-attn / Mamba layers are only configured under ulysses; models that have them
|
||||
# declare ulysses-only in `cp_support`, so `get_model` already rejected ring.
|
||||
if config.model.cp_style == "ulysses":
|
||||
setup_model_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
setup_context_parallel(model, config.model, parallel_dims)
|
||||
|
||||
if config.model.lora is not None:
|
||||
get_lora_state().reset_adapter_parameters()
|
||||
|
||||
+42
-51
@@ -3,80 +3,71 @@ from __future__ import annotations
|
||||
# ruff: noqa: I001 — `prime_rl._compat` must run before `ring_flash_attn` imports below.
|
||||
import prime_rl._compat # noqa: F401
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch.nn as nn
|
||||
from ring_flash_attn import update_ring_flash_attn_params
|
||||
from ring_flash_attn import substitute_hf_flash_attn, update_ring_flash_attn_params
|
||||
|
||||
from prime_rl.trainer.distributed.collectives import all_gather
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
|
||||
|
||||
if TYPE_CHECKING:
|
||||
# `prime_rl.trainer.models` imports this module, so importing the model base eagerly would
|
||||
# cycle. `from __future__ import annotations` keeps CPStyle out of the runtime path.
|
||||
from prime_rl.configs.trainer import ModelConfig
|
||||
from prime_rl.trainer.models.base import CPStyle
|
||||
from prime_rl.trainer.parallel_dims import ParallelDims
|
||||
|
||||
|
||||
def _has_linear_attn_layer(model: nn.Module) -> bool:
|
||||
"""True if the model contains any non-softmax (linear/SSM) attention layer."""
|
||||
inner = getattr(model, "model", model)
|
||||
if hasattr(inner, "language_model"):
|
||||
inner = inner.language_model
|
||||
layers = getattr(inner, "layers", None)
|
||||
if layers is None:
|
||||
return False
|
||||
layer_modules = layers.modules() if isinstance(layers, nn.Module) else layers
|
||||
for layer in layer_modules:
|
||||
# Qwen3.5 hybrid DeltaNet
|
||||
if getattr(layer, "layer_type", None) == "linear_attention":
|
||||
return True
|
||||
# NemotronH Mamba
|
||||
if hasattr(layer, "mamba"):
|
||||
return True
|
||||
return False
|
||||
@dataclass(frozen=True)
|
||||
class CPContext:
|
||||
"""Context-parallel topology, shared by every module that consumes it."""
|
||||
|
||||
cp_group: dist.ProcessGroup | None = None
|
||||
cp_rank: int = 0
|
||||
cp_world_size: int = 1
|
||||
cp_style: CPStyle | None = None
|
||||
|
||||
@property
|
||||
def cp_enabled(self) -> bool:
|
||||
return self.cp_world_size > 1
|
||||
|
||||
|
||||
def setup_model_cp(model: nn.Module, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
|
||||
"""Hand the CP topology to models whose layers need it (DeltaNet, Mamba).
|
||||
def setup_context_parallel(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDims) -> None:
|
||||
cp_group = parallel_dims.world_mesh["cp"].get_group()
|
||||
cp_rank = parallel_dims.world_mesh["cp"].get_local_rank()
|
||||
|
||||
Such models expose ``set_context_parallel_attributes`` at the top level and
|
||||
own their layer wiring; softmax-only models don't and need nothing.
|
||||
"""
|
||||
if hasattr(model, "set_context_parallel_attributes"):
|
||||
model.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
|
||||
from prime_rl.utils.logger import get_logger
|
||||
if config.cp_style == "ring":
|
||||
# Delayed imports: both modules live under trainer.models, which imports back into
|
||||
# prime_rl.utils — a top-level import would deadlock at startup.
|
||||
from prime_rl.trainer.models.layers.attn import substitute_ring_attn
|
||||
|
||||
get_logger().info("Configured model CP attributes")
|
||||
elif _has_linear_attn_layer(model):
|
||||
raise ValueError(
|
||||
"Model has linear-attention/Mamba layers but does not implement "
|
||||
"set_context_parallel_attributes; CP would silently misconfigure them"
|
||||
)
|
||||
substitute_hf_flash_attn(cp_group, heads_k_stride=1)
|
||||
substitute_ring_attn(cp_group, heads_k_stride=1, attn_impl=config.attn)
|
||||
elif config.cp_style == "ulysses":
|
||||
from prime_rl.trainer.models.layers.ulysses_attn import substitute_hf_ulysses_attn, substitute_ulysses_attn
|
||||
|
||||
substitute_hf_ulysses_attn(cp_group)
|
||||
substitute_ulysses_attn(cp_group, attn_impl=config.attn)
|
||||
else:
|
||||
raise ValueError(f"Unknown cp_style: {config.cp_style}")
|
||||
|
||||
def setup_sparse_mla_cp(model: nn.Module, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
|
||||
"""Configure GLM-5 sparse MLA modules for context-parallel gather/scatter."""
|
||||
|
||||
count = 0
|
||||
if not hasattr(model, "model"):
|
||||
return
|
||||
|
||||
if not hasattr(model.model, "layers"):
|
||||
return
|
||||
|
||||
for layer in model.model.layers:
|
||||
if not hasattr(layer, "set_context_parallel_attributes"):
|
||||
cp_context = CPContext(cp_group, cp_rank, parallel_dims.cp, config.cp_style)
|
||||
for module in model.modules():
|
||||
if not hasattr(module, "cp_context"):
|
||||
continue
|
||||
if not isinstance(module.cp_context, CPContext):
|
||||
raise TypeError(
|
||||
f"{type(module).__name__}.cp_context is {type(module.cp_context).__name__}, not a CPContext; "
|
||||
"context-parallel setup claims that attribute name, so rename it"
|
||||
)
|
||||
module.cp_context = cp_context
|
||||
|
||||
layer.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
|
||||
count += 1
|
||||
|
||||
if count > 0:
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
get_logger().info(f"Configured sparse MLA CP on {count} DSA layers")
|
||||
get_logger().info(f"Configured {config.cp_style} context parallelism (cp={parallel_dims.cp})")
|
||||
|
||||
|
||||
def shard_for_cp(t: torch.Tensor, cp_rank: int, cp_world_size: int, seq_dim: int = 1) -> torch.Tensor:
|
||||
|
||||
@@ -164,6 +164,19 @@ def test_removed_fused_lm_head_chunk_size_field_is_rejected():
|
||||
TrainerModelConfig.model_validate({"fused_lm_head_chunk_size": "auto"})
|
||||
|
||||
|
||||
def test_icepop_is_an_optional_loss_with_validated_ratio_bounds():
|
||||
default_config = TrainerConfig()
|
||||
assert default_config.loss.type == "ipo"
|
||||
|
||||
config = TrainerConfig.model_validate({"loss": {"type": "icepop", "ratio_low": 0.2, "ratio_high": 5.0}})
|
||||
assert config.loss.type == "icepop"
|
||||
assert config.loss.ratio_low == 0.2
|
||||
assert config.loss.ratio_high == 5.0
|
||||
|
||||
with pytest.raises(ValidationError, match="ratio_low must not exceed ratio_high"):
|
||||
TrainerConfig.model_validate({"loss": {"type": "icepop", "ratio_low": 5.0, "ratio_high": 0.2}})
|
||||
|
||||
|
||||
def test_moe_runtime_defaults_are_independent_from_dense_quantization():
|
||||
config = TrainerModelConfig.model_validate({"quantization": {"type": "mxfp8"}})
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ from prime_rl.trainer.models.qwen3_5 import (
|
||||
Qwen3_5VisionConfig,
|
||||
)
|
||||
from prime_rl.trainer.models.qwen3_5.attention import Qwen3_5Attention
|
||||
from prime_rl.utils.cp import setup_model_cp
|
||||
from prime_rl.utils.cp import CPContext
|
||||
|
||||
|
||||
def get_text_config(config_cls=Qwen3_5TextConfig) -> Qwen3_5TextConfig:
|
||||
@@ -90,36 +90,29 @@ def test_context_parallel_setup_chain_text_and_vlm(text_config):
|
||||
text_model = get_model(text_config, device="meta")
|
||||
linear_layer = text_model.model.layers[0]
|
||||
text_model.model.layers[0] = torch.nn.Sequential(linear_layer)
|
||||
setup_model_cp(text_model, cp_group, cp_rank=1, cp_world_size=2)
|
||||
assert text_model.model.context_parallel_group is cp_group
|
||||
assert text_model.model.context_parallel_rank == 1
|
||||
assert text_model.model.context_parallel_world_size == 2
|
||||
assert linear_layer.linear_attn.context_parallel_group is cp_group
|
||||
assert linear_layer.linear_attn.context_parallel_world_size == 2
|
||||
|
||||
text_cp_context = CPContext(cp_group, 1, 2, "ulysses")
|
||||
for module in text_model.modules():
|
||||
if hasattr(module, "cp_context"):
|
||||
module.cp_context = text_cp_context
|
||||
|
||||
assert text_model.model.cp_context is text_cp_context
|
||||
assert text_model.model.cp_context.cp_rank == 1
|
||||
assert text_model.model.cp_context.cp_world_size == 2
|
||||
assert text_model.model.cp_context.cp_style == "ulysses"
|
||||
assert linear_layer.linear_attn.cp_context is text_cp_context
|
||||
|
||||
vlm_model = get_model(get_vlm_config(text_config), device="meta")
|
||||
setup_model_cp(vlm_model, cp_group, cp_rank=0, cp_world_size=2)
|
||||
assert vlm_model.model.language_model.context_parallel_group is cp_group
|
||||
assert vlm_model.model.language_model.layers[0].linear_attn.context_parallel_world_size == 2
|
||||
|
||||
vlm_cp_context = CPContext(cp_group, 0, 2, "ulysses")
|
||||
for module in vlm_model.modules():
|
||||
if hasattr(module, "cp_context"):
|
||||
module.cp_context = vlm_cp_context
|
||||
|
||||
def test_setup_model_cp_requires_hook_only_for_hybrid_models():
|
||||
class HybridLayer(torch.nn.Module):
|
||||
layer_type = "linear_attention"
|
||||
|
||||
class Inner:
|
||||
layers = torch.nn.Sequential(torch.nn.Sequential(HybridLayer()))
|
||||
|
||||
class HybridNoHookModel:
|
||||
model = Inner()
|
||||
|
||||
with pytest.raises(ValueError, match="set_context_parallel_attributes"):
|
||||
setup_model_cp(HybridNoHookModel(), MagicMock(), cp_rank=0, cp_world_size=2)
|
||||
|
||||
class SoftmaxOnlyModel:
|
||||
pass
|
||||
|
||||
setup_model_cp(SoftmaxOnlyModel(), MagicMock(), cp_rank=0, cp_world_size=2)
|
||||
assert vlm_model.model.cp_context is vlm_cp_context
|
||||
assert vlm_model.model.language_model.cp_context is vlm_cp_context
|
||||
assert vlm_model.model.language_model.cp_context.cp_style == "ulysses"
|
||||
assert vlm_model.model.language_model.layers[0].linear_attn.cp_context is vlm_cp_context
|
||||
|
||||
|
||||
def test_ring_patches_flash_attention():
|
||||
|
||||
@@ -14,6 +14,7 @@ from prime_rl.trainer.models.deepseek_v4.attention import DeepseekV4Attention, P
|
||||
from prime_rl.trainer.models.deepseek_v4.eager_reference import dense_mask_from_indices, eager_attention_with_sinks
|
||||
from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding, apply_rotary_pos_emb_interleaved
|
||||
from prime_rl.trainer.models.kernels.deepseek_v4 import IGNORE_SLOT
|
||||
from prime_rl.utils.cp import CPContext
|
||||
from prime_rl.utils.utils import default_dtype
|
||||
|
||||
try:
|
||||
@@ -1244,7 +1245,7 @@ def test_context_parallel_shards_reproduce_the_whole_row(layer_idx, cp_world_siz
|
||||
for cp_rank, chunk in enumerate(chunks):
|
||||
gather, pending = _fake_gather_for_cp(projections, chunks, cp_rank)
|
||||
monkeypatch.setattr(dsv4_attention, "gather_for_cp", gather)
|
||||
module.set_context_parallel_attributes(MagicMock(), cp_rank, cp_world_size)
|
||||
module.cp_context = CPContext(MagicMock(), cp_rank, cp_world_size, "ring")
|
||||
|
||||
packed = _packed_context(doc_lens, torch.float32, V4FLASH_CONFIG, cp_rank=cp_rank, cp_world_size=cp_world_size)
|
||||
out_rank, _ = module(chunk, packed=packed)
|
||||
|
||||
@@ -6,7 +6,7 @@ import torch
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
from prime_rl.trainer.models.nemotron_h import NemotronHConfig, NemotronHForCausalLM
|
||||
from prime_rl.trainer.models.nemotron_h.mamba import NemotronHMamba2
|
||||
from prime_rl.utils.cp import setup_model_cp
|
||||
from prime_rl.utils.cp import CPContext
|
||||
from prime_rl.utils.utils import default_dtype
|
||||
|
||||
pytestmark = [pytest.mark.gpu]
|
||||
@@ -114,11 +114,15 @@ def test_nemotron_h_context_parallel_setup_finds_wrapped_mamba_layer():
|
||||
model.model.layers[0] = torch.nn.Sequential(mamba_layer)
|
||||
|
||||
cp_group = MagicMock()
|
||||
setup_model_cp(model, cp_group, cp_rank=1, cp_world_size=2)
|
||||
|
||||
assert mamba_layer.mamba.process_group is cp_group
|
||||
assert mamba_layer.mamba.context_parallel_rank == 1
|
||||
assert mamba_layer.mamba.context_parallel_world_size == 2
|
||||
cp_context = CPContext(cp_group, 1, 2, "ulysses")
|
||||
for module in model.modules():
|
||||
if hasattr(module, "cp_context"):
|
||||
module.cp_context = cp_context
|
||||
|
||||
assert mamba_layer.mamba.cp_context is cp_context
|
||||
assert mamba_layer.mamba.cp_context.cp_rank == 1
|
||||
assert mamba_layer.mamba.cp_context.cp_world_size == 2
|
||||
|
||||
|
||||
def test_nemotron_h_no_latent_projection():
|
||||
|
||||
@@ -12,8 +12,8 @@ from prime_rl.configs.trainer import IPOLossConfig
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
from prime_rl.trainer.models.nemotron_h import NemotronHConfig, NemotronHForCausalLM
|
||||
from prime_rl.trainer.rl.loss import (
|
||||
IPOLoss,
|
||||
LossInputs,
|
||||
ipo_loss_fn,
|
||||
selective_log_softmax,
|
||||
shift_tensor_right,
|
||||
)
|
||||
@@ -101,7 +101,7 @@ def test_kl_zero_when_identical():
|
||||
advantages=advantages,
|
||||
loss_mask=loss_mask,
|
||||
)
|
||||
result = ipo_loss_fn(inputs, IPOLossConfig(eps=10.0))
|
||||
result = IPOLoss(IPOLossConfig(eps=10.0)).loss(inputs)
|
||||
|
||||
assert result.metrics["unmasked_mismatch_kl"].item() == pytest.approx(0.0, abs=1e-6), (
|
||||
f"Expected zero KL for identical models, got {result.metrics['unmasked_mismatch_kl'].item()}"
|
||||
@@ -135,7 +135,7 @@ def test_kl_positive_after_perturbation():
|
||||
advantages=advantages,
|
||||
loss_mask=loss_mask,
|
||||
)
|
||||
result = ipo_loss_fn(inputs, IPOLossConfig(eps=10.0))
|
||||
result = IPOLoss(IPOLossConfig(eps=10.0)).loss(inputs)
|
||||
kl = result.metrics["unmasked_mismatch_kl"].item()
|
||||
|
||||
assert kl > 0, f"Expected positive KL after perturbation, got {kl}"
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from prime_rl.configs.trainer import CustomLossConfig, IPOLossConfig
|
||||
from prime_rl.trainer.rl.loss import LossInputs, LossOutputs, compute_entropy, compute_loss, setup_rl_loss_fn
|
||||
from prime_rl.configs.trainer import CustomLossConfig, IcePopLossConfig, IPOLossConfig
|
||||
from prime_rl.trainer.rl.loss import (
|
||||
IcePopLoss,
|
||||
LossInputs,
|
||||
LossOutputs,
|
||||
compute_entropy,
|
||||
compute_loss,
|
||||
setup_rl_loss_fn,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.gpu]
|
||||
|
||||
@@ -79,12 +86,48 @@ def test_setup_rl_loss_fn_with_custom_config():
|
||||
loss_mask=torch.ones(50, dtype=torch.bool).cuda(),
|
||||
)
|
||||
|
||||
result = rl_loss_fn(inputs)
|
||||
result = rl_loss_fn.loss(inputs)
|
||||
assert isinstance(result, LossOutputs)
|
||||
assert result.loss.shape == ()
|
||||
assert "custom_metric" in result.metrics
|
||||
|
||||
|
||||
def test_icepop_loss_masks_ratios_outside_inclusive_band():
|
||||
ratios = torch.tensor([0.1, 0.2, 1.0, 5.0, 10.0], device="cuda")
|
||||
trainer_logprobs = ratios.log().requires_grad_()
|
||||
inputs = LossInputs(
|
||||
trainer_logprobs=trainer_logprobs,
|
||||
inference_logprobs=torch.zeros_like(trainer_logprobs),
|
||||
ref_logprobs=None,
|
||||
advantages=torch.ones_like(trainer_logprobs),
|
||||
loss_mask=torch.ones_like(trainer_logprobs, dtype=torch.bool),
|
||||
)
|
||||
|
||||
result = setup_rl_loss_fn(IcePopLossConfig()).loss(inputs)
|
||||
|
||||
assert torch.isclose(result.loss, torch.tensor(-6.2, device="cuda"))
|
||||
assert torch.isclose(result.metrics["is_masked"], torch.tensor(0.4, device="cuda"))
|
||||
result.loss.backward()
|
||||
assert torch.allclose(trainer_logprobs.grad, torch.tensor([0.0, -0.2, -1.0, -5.0, 0.0], device="cuda"))
|
||||
|
||||
|
||||
def test_icepop_loss_masks_extreme_ratio_without_nan():
|
||||
trainer_logprobs = torch.tensor([100.0], device="cuda", requires_grad=True)
|
||||
inputs = LossInputs(
|
||||
trainer_logprobs=trainer_logprobs,
|
||||
inference_logprobs=torch.zeros_like(trainer_logprobs),
|
||||
ref_logprobs=None,
|
||||
advantages=torch.ones_like(trainer_logprobs),
|
||||
loss_mask=torch.ones_like(trainer_logprobs, dtype=torch.bool),
|
||||
)
|
||||
|
||||
result = IcePopLoss(IcePopLossConfig()).loss(inputs)
|
||||
|
||||
assert torch.equal(result.loss, torch.zeros_like(result.loss))
|
||||
result.loss.backward()
|
||||
assert torch.equal(trainer_logprobs.grad, torch.zeros_like(trainer_logprobs.grad))
|
||||
|
||||
|
||||
def test_ce_component_matches_masked_nll():
|
||||
trainer_logprobs = [torch.tensor([-0.1, -0.5, -0.2], dtype=torch.float32).cuda()]
|
||||
inference_logprobs = [torch.zeros(3, dtype=torch.float32).cuda()]
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
from typing import NamedTuple
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from torch.optim import Optimizer
|
||||
|
||||
from prime_rl.trainer.optim.state_offload import CPUOffloadOptimizer
|
||||
|
||||
pytestmark = [pytest.mark.gpu]
|
||||
|
||||
|
||||
class TrainedPair(NamedTuple):
|
||||
reference_model: torch.nn.Module
|
||||
reference_optimizer: Optimizer
|
||||
offloaded_model: torch.nn.Module
|
||||
offloaded_optimizer: CPUOffloadOptimizer
|
||||
|
||||
|
||||
def make_model(seed: int) -> torch.nn.Sequential:
|
||||
torch.manual_seed(seed)
|
||||
model = torch.nn.Sequential(torch.nn.Linear(64, 128), torch.nn.GELU(), torch.nn.Linear(128, 32))
|
||||
return model.cuda()
|
||||
|
||||
|
||||
def run_steps(model: torch.nn.Module, optimizer: Optimizer, num_steps: int, seed: int) -> None:
|
||||
torch.manual_seed(seed)
|
||||
for _ in range(num_steps):
|
||||
batch = torch.randn(16, 64, device="cuda")
|
||||
loss = model(batch).square().mean()
|
||||
loss.backward()
|
||||
optimizer.step()
|
||||
optimizer.zero_grad()
|
||||
|
||||
|
||||
def assert_params_equal(reference_model: torch.nn.Module, model: torch.nn.Module) -> None:
|
||||
for (name, reference_param), (_, param) in zip(reference_model.named_parameters(), model.named_parameters()):
|
||||
assert torch.equal(reference_param, param), f"param mismatch: {name}"
|
||||
|
||||
|
||||
def assert_states_offloaded(optimizer: CPUOffloadOptimizer) -> None:
|
||||
for param in optimizer.state:
|
||||
for key, value in optimizer.state[param].items():
|
||||
assert value.device.type == "cpu", f"state '{key}' on {value.device}, expected cpu"
|
||||
assert value.is_pinned(), f"state '{key}' not pinned"
|
||||
|
||||
|
||||
def assert_state_dicts_equal(saved: dict, restored: dict) -> None:
|
||||
assert saved["param_groups"] == restored["param_groups"]
|
||||
assert saved["state"].keys() == restored["state"].keys()
|
||||
for index in saved["state"]:
|
||||
assert saved["state"][index].keys() == restored["state"][index].keys()
|
||||
for key, saved_value in saved["state"][index].items():
|
||||
restored_value = restored["state"][index][key]
|
||||
if isinstance(saved_value, torch.Tensor):
|
||||
assert torch.equal(saved_value.cpu(), restored_value.cpu()), f"state[{index}]['{key}'] mismatch"
|
||||
else:
|
||||
assert saved_value == restored_value, f"state[{index}]['{key}'] mismatch"
|
||||
|
||||
|
||||
def state_data_ptrs(optimizer: CPUOffloadOptimizer) -> dict[tuple[int, str], int]:
|
||||
return {
|
||||
(id(param), key): value.data_ptr() for param in optimizer.state for key, value in optimizer.state[param].items()
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def trained_pair() -> TrainedPair:
|
||||
reference_model = make_model(0)
|
||||
reference_optimizer = torch.optim.AdamW(reference_model.parameters(), lr=1e-2)
|
||||
run_steps(reference_model, reference_optimizer, num_steps=3, seed=1)
|
||||
|
||||
offloaded_model = make_model(0)
|
||||
offloaded_optimizer = CPUOffloadOptimizer(torch.optim.AdamW(offloaded_model.parameters(), lr=1e-2))
|
||||
run_steps(offloaded_model, offloaded_optimizer, num_steps=3, seed=1)
|
||||
|
||||
return TrainedPair(reference_model, reference_optimizer, offloaded_model, offloaded_optimizer)
|
||||
|
||||
|
||||
def test_offloaded_steps_match_plain_adamw(trained_pair: TrainedPair) -> None:
|
||||
assert_params_equal(trained_pair.reference_model, trained_pair.offloaded_model)
|
||||
|
||||
|
||||
def test_states_are_on_cpu_and_pinned_between_steps(trained_pair: TrainedPair) -> None:
|
||||
assert_states_offloaded(trained_pair.offloaded_optimizer)
|
||||
|
||||
|
||||
def test_state_dict_round_trip_is_exact_and_training_continues(trained_pair: TrainedPair) -> None:
|
||||
optimizer = trained_pair.offloaded_optimizer
|
||||
|
||||
saved = optimizer.state_dict()
|
||||
optimizer.load_state_dict(saved)
|
||||
restored = optimizer.state_dict()
|
||||
|
||||
assert_state_dicts_equal(saved, restored)
|
||||
assert_states_offloaded(optimizer)
|
||||
|
||||
run_steps(trained_pair.reference_model, trained_pair.reference_optimizer, num_steps=1, seed=2)
|
||||
run_steps(trained_pair.offloaded_model, optimizer, num_steps=1, seed=2)
|
||||
assert_params_equal(trained_pair.reference_model, trained_pair.offloaded_model)
|
||||
|
||||
|
||||
def test_offload_reuses_pinned_buffers_across_steps() -> None:
|
||||
model = make_model(0)
|
||||
optimizer = CPUOffloadOptimizer(torch.optim.AdamW(model.parameters(), lr=1e-2))
|
||||
run_steps(model, optimizer, num_steps=2, seed=1)
|
||||
|
||||
pointers_before = state_data_ptrs(optimizer)
|
||||
|
||||
run_steps(model, optimizer, num_steps=1, seed=2)
|
||||
|
||||
pointers_after = state_data_ptrs(optimizer)
|
||||
assert pointers_before.keys() == pointers_after.keys()
|
||||
for key, pointer in pointers_before.items():
|
||||
assert pointers_after[key] == pointer, f"state buffer reallocated for {key}"
|
||||
Reference in New Issue
Block a user