Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c935497d71 | ||
|
|
cd2f3daeb2 | ||
|
|
897b935cae | ||
|
|
81f9e9512b | ||
|
|
d4385029c8 | ||
|
|
c654dc1d4d | ||
|
|
6ba37c2c21 | ||
|
|
458b16ef47 | ||
|
|
b5f196a9c5 | ||
|
|
6dda4a1466 | ||
|
|
fa55779272 | ||
|
|
b2ba40b5eb | ||
|
|
e4330c2d2c | ||
|
|
4a6b45487f | ||
|
|
024abb2043 | ||
|
|
5b11b8de33 |
@@ -14,7 +14,11 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
submodules: false
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v5
|
||||
with:
|
||||
|
||||
@@ -28,23 +28,20 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
submodules: false
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v5
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --locked
|
||||
- name: Run unit tests
|
||||
env:
|
||||
USERNAME_CI: CI_RUNNER
|
||||
WANDB_API_KEY: ${{ secrets.WANDB_API_KEY }}
|
||||
# Set WANDB_MODE to online only if WANDB_API_KEY is available, otherwise set to offline
|
||||
# This is to allow running tests on forks without WANDB_API_KEY
|
||||
WANDB_MODE: ${{ secrets.WANDB_API_KEY && 'online' || 'offline' }}
|
||||
WANDB_MODE: offline
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
PRIME_API_KEY: ${{ secrets.PRIME_API_KEY }}
|
||||
GITHUB_REF_NAME: ${{ github.ref_name }}
|
||||
GITHUB_HEAD_REF: ${{ github.head_ref }}
|
||||
@@ -63,21 +60,30 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- test: base
|
||||
- test: reverse_text_sft
|
||||
runner: vm
|
||||
pytest_args: "tests/integration -m gpu --ignore=tests/integration/test_rl_lora.py --ignore=tests/integration/test_rl_multi_run_lora.py --ignore=tests/integration/test_benchmark_regression.py --ignore=tests/integration/test_alphabet_sort.py"
|
||||
- test: rl_lora
|
||||
pytest_args: "tests/integration/test_reverse_text_sft.py"
|
||||
- test: reverse_text_sft_lora
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_rl_lora.py -m gpu"
|
||||
pytest_args: "tests/integration/test_reverse_text_sft_lora.py"
|
||||
- test: reverse_text
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_reverse_text.py"
|
||||
- test: alphabet_sort
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_alphabet_sort.py -m gpu"
|
||||
- test: rl_multi_run
|
||||
pytest_args: "tests/integration/test_alphabet_sort.py"
|
||||
- test: reverse_text_lora
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_reverse_text_lora.py"
|
||||
- test: reverse_text_moe
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_reverse_text_moe.py"
|
||||
- test: reverse_text_multi_run
|
||||
runner: 4xa6000
|
||||
pytest_args: "tests/integration/test_rl_multi_run_lora.py -m gpu"
|
||||
pytest_args: "tests/integration/test_reverse_text_multi_run.py"
|
||||
- test: benchmark_regression
|
||||
runner: 4xa6000
|
||||
pytest_args: "tests/integration/test_benchmark_regression.py -m gpu"
|
||||
pytest_args: "tests/integration/test_benchmark_regression.py"
|
||||
steps:
|
||||
- name: Install Git
|
||||
run: |
|
||||
@@ -87,23 +93,20 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
submodules: false
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v5
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --locked
|
||||
- name: Run integration tests
|
||||
env:
|
||||
USERNAME_CI: CI_RUNNER
|
||||
WANDB_API_KEY: ${{ secrets.WANDB_API_KEY }}
|
||||
# Set WANDB_MODE to online only if WANDB_API_KEY is available, otherwise set to offline
|
||||
# This is to allow running tests on forks without WANDB_API_KEY
|
||||
WANDB_MODE: ${{ secrets.WANDB_API_KEY && 'online' || 'offline' }}
|
||||
WANDB_MODE: offline
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
PRIME_API_KEY: ${{ secrets.PRIME_API_KEY }}
|
||||
PRIME_BASE_URL: ${{ secrets.PRIME_BASE_URL }}
|
||||
PRIME_TEAM_ID: ${{ secrets.PRIME_TEAM_ID }}
|
||||
@@ -111,4 +114,4 @@ jobs:
|
||||
GITHUB_HEAD_REF: ${{ github.head_ref }}
|
||||
PYTEST_OUTPUT_DIR: /tmp/outputs
|
||||
VLLM_WORKER_MULTIPROC_METHOD: spawn
|
||||
run: uv run pytest ${{ matrix.pytest_args }}
|
||||
run: uv run pytest -vvs ${{ matrix.pytest_args }}
|
||||
|
||||
@@ -25,7 +25,7 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
submodules: false
|
||||
|
||||
- name: Build matrix from nightly test files
|
||||
id: build-matrix
|
||||
@@ -75,7 +75,11 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
submodules: false
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v5
|
||||
with:
|
||||
|
||||
@@ -24,6 +24,12 @@ jobs:
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
submodules: false
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: crazy-max/ghaction-docker-meta@v2
|
||||
|
||||
@@ -16,8 +16,9 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
# Submodules are excluded from ruff via pyproject.toml; no need to fetch them.
|
||||
with:
|
||||
submodules: true
|
||||
submodules: false
|
||||
- name: Run ruff
|
||||
uses: astral-sh/ruff-action@v3
|
||||
with:
|
||||
|
||||
+2
-1
@@ -1,4 +1,5 @@
|
||||
.vscode/*
|
||||
.claude/scheduled_tasks.lock
|
||||
*.ipynb
|
||||
*.jsonl
|
||||
configs/endpoints.py
|
||||
@@ -200,4 +201,4 @@ debug_I2_zero_band
|
||||
|
||||
outputs/
|
||||
|
||||
third_party/
|
||||
third_party/
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
[submodule "verifiers"]
|
||||
path = deps/verifiers
|
||||
url = git@github.com:PrimeIntellect-ai/verifiers.git
|
||||
[submodule "renderers"]
|
||||
path = deps/renderers
|
||||
url = git@github.com:PrimeIntellect-ai/renderers.git
|
||||
[submodule "research-environments"]
|
||||
path = deps/research-environments
|
||||
url = git@github.com:PrimeIntellect-ai/research-environments.git
|
||||
[submodule "configs/private"]
|
||||
path = configs/private
|
||||
url = git@github.com:PrimeIntellect-ai/research-configs.git
|
||||
@@ -3,6 +3,7 @@
|
||||
## Writing code
|
||||
|
||||
- **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.
|
||||
- **Zen of Python**: remember the Zen of Python when writing code.
|
||||
```
|
||||
|
||||
@@ -43,6 +43,7 @@ COPY uv.lock /app/uv.lock
|
||||
COPY README.md /app/README.md
|
||||
COPY src/ /app/src/
|
||||
COPY packages/ /app/packages/
|
||||
COPY deps/ /app/deps/
|
||||
COPY configs /app/configs
|
||||
COPY examples /app/examples
|
||||
COPY benchmarks/scripts /app/benchmarks/scripts
|
||||
|
||||
@@ -53,6 +53,7 @@ With `[model] impl = "auto"` (the default), the trainer selects that custom stac
|
||||
| Qwen3 MoE (`qwen3_moe`) | `Qwen/Qwen3-30B-A3B`, … | yes | ✅ | ✅ |
|
||||
| Qwen3.5 MoE (`qwen3_5_moe`) | `Qwen/Qwen3.5-35B-A3B`, … | yes | ✅ | ✅ |
|
||||
| Qwen3 / Qwen3.5 VLMs | [multimodal.md](docs/multimodal.md) (`qwen3_vl`, `qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ✅ |
|
||||
| Poolside Laguna (`laguna`) | `poolside/Laguna-XS.2` | yes | ✅ | ✅ |
|
||||
| MiniMax M2 (`minimax_m2`) | `MiniMax/MiniMax-M2` | yes | ✅ | ✅ |
|
||||
| Nemotron H (`nemotron_h`) | `nvidia/Nemotron-3-Nano-30B-A3B`, `nvidia/Nemotron-3-Super-120B-A12B`, … | yes | ✅ | ❌ |
|
||||
| Trinity (`afmoe`) | `arcee-ai/Trinity-Mini`, … | yes | ✅ | ✅ |
|
||||
@@ -90,14 +91,20 @@ git clone https://github.com/PrimeIntellect-ai/prime-rl.git
|
||||
cd prime-rl
|
||||
```
|
||||
|
||||
2. Install [uv](https://docs.astral.sh/uv/)
|
||||
2. Initialize submodules
|
||||
|
||||
```bash
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments
|
||||
```
|
||||
|
||||
3. Install [uv](https://docs.astral.sh/uv/)
|
||||
|
||||
```bash
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
source $HOME/.local/bin/env
|
||||
```
|
||||
|
||||
3. Install dependencies from the lock file
|
||||
4. Install dependencies from the lock file
|
||||
|
||||
```bash
|
||||
uv sync --all-extras
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
max_steps = 10
|
||||
max_steps = 5
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt]
|
||||
@@ -1,29 +0,0 @@
|
||||
max_steps = 10
|
||||
seq_len = 2048
|
||||
|
||||
[deployment]
|
||||
type = "single_node"
|
||||
num_infer_gpus = 1
|
||||
num_train_gpus = 1
|
||||
|
||||
[ckpt]
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-0.6B"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-5
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 8
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "primeintellect/alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, similarity_power = 4, power_per_turn = false }
|
||||
|
||||
[inference]
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
max_steps = 25
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt]
|
||||
resume_step = 20
|
||||
resume_step = 15
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
max_steps = 20
|
||||
max_steps = 15
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt]
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
max_steps = 25
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt]
|
||||
resume_step = 20
|
||||
resume_step = 15
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
max_steps = 20
|
||||
max_steps = 15
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt]
|
||||
+3
@@ -9,6 +9,9 @@ name = "samsja/mini-glm-moe"
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
+1
@@ -1,6 +1,7 @@
|
||||
max_steps = 10
|
||||
|
||||
[ckpt]
|
||||
resume_step = 5
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B"
|
||||
+1
-2
@@ -1,7 +1,6 @@
|
||||
max_steps = 20
|
||||
max_steps = 5
|
||||
|
||||
[ckpt]
|
||||
resume_step = 10
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B"
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
max_steps = 20
|
||||
max_steps = 10
|
||||
|
||||
[ckpt]
|
||||
resume_step = 10
|
||||
resume_step = 5
|
||||
|
||||
[ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
max_steps = 10
|
||||
max_steps = 5
|
||||
|
||||
[ckpt]
|
||||
|
||||
Submodule
+1
Submodule configs/private added at 74c1330008
+1
Submodule deps/renderers added at 17d0584f87
+1
Submodule deps/research-environments added at d141472268
+1
Submodule deps/verifiers added at 711a7c705e
@@ -1082,6 +1082,14 @@ class OrchestratorConfig(BaseConfig):
|
||||
),
|
||||
] = 8
|
||||
|
||||
max_error_reschedule_attempts: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
ge=1,
|
||||
description="The group is dropped from the current step's batch once this many of its dispatch rounds have returned errored or empty rollouts (the trainer proceeds with the rollouts from other groups). Counts rounds, not individual rollouts: a non-group-scoring env that dispatches `rollouts_per_example` rollouts at once still only counts one round per failed batch. `None` means retry indefinitely (legacy behavior). Useful for unblocking single-example hangs in agent envs.",
|
||||
),
|
||||
] = None
|
||||
|
||||
max_async_level: Annotated[
|
||||
int,
|
||||
Field(
|
||||
|
||||
@@ -6,6 +6,7 @@ from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from prime_rl.configs.shared import (
|
||||
HeartbeatConfig,
|
||||
RendererConfig,
|
||||
SlurmConfig,
|
||||
TrainerLogConfig,
|
||||
WandbConfig,
|
||||
@@ -172,6 +173,21 @@ class SFTConfig(BaseConfig):
|
||||
# The tokenizer configuration
|
||||
tokenizer: TokenizerConfig = TokenizerConfig()
|
||||
|
||||
# The renderer configuration (only used when use_renderer=True)
|
||||
renderer: RendererConfig = RendererConfig()
|
||||
|
||||
use_renderer: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description=(
|
||||
"If True, tokenize SFT samples through the `renderers` library "
|
||||
"(single render() + message_indices mask) instead of the default "
|
||||
"`build_incremental_token_mask` path. Required for chat templates "
|
||||
"that render position-dependently (e.g. Qwen3, Qwen3.5)."
|
||||
),
|
||||
),
|
||||
] = False
|
||||
|
||||
# The data configuration
|
||||
data: DataConfig = SFTDataConfig()
|
||||
|
||||
@@ -357,6 +373,55 @@ class SFTConfig(BaseConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_renderer_vs_vlm(self):
|
||||
if self.use_renderer and self.model.vlm is not None:
|
||||
raise ValueError(
|
||||
"use_renderer is not supported for VLMs. The renderer tokenizes "
|
||||
"text-only message dicts client-side and cannot handle image inputs."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_renderer_args(self):
|
||||
# pool_size is orchestrator-only. An in-process renderer pool exists
|
||||
# to amortize tokenization across concurrent rollouts in the
|
||||
# orchestrator (many async requests render at once, HF fast
|
||||
# tokenizers release the GIL during Rust encoding, so a pool of N
|
||||
# tokenizer copies parallelizes well). SFT has no such concurrency:
|
||||
# the StatefulDataLoader is constructed with num_workers=0, so the
|
||||
# main process tokenizes one example at a time, between training
|
||||
# steps. Across DP, each rank already owns its own renderer — an
|
||||
# implicit pool of size world_size. Pooling within a rank gives
|
||||
# nothing on top of that. Reject so callers don't silently set a
|
||||
# knob that does nothing; if SFT tokenization ever becomes a
|
||||
# bottleneck the fix is num_workers on the dataloader, not a pool.
|
||||
if self.renderer.pool_size is not None:
|
||||
raise ValueError(
|
||||
f"renderer.pool_size={self.renderer.pool_size!r} is only used by the orchestrator. "
|
||||
"SFT tokenizes synchronously (num_workers=0) and already gets one renderer per DP "
|
||||
"rank — an in-process pool adds nothing. If tokenization is a bottleneck, raise "
|
||||
"num_workers on the dataloader instead."
|
||||
)
|
||||
|
||||
if self.use_renderer:
|
||||
return self
|
||||
|
||||
renderer_args_set = []
|
||||
if self.renderer.name != "auto":
|
||||
renderer_args_set.append(f"renderer.name={self.renderer.name!r}")
|
||||
if self.renderer.tool_parser is not None:
|
||||
renderer_args_set.append(f"renderer.tool_parser={self.renderer.tool_parser!r}")
|
||||
if self.renderer.reasoning_parser is not None:
|
||||
renderer_args_set.append(f"renderer.reasoning_parser={self.renderer.reasoning_parser!r}")
|
||||
|
||||
if renderer_args_set:
|
||||
raise ValueError(
|
||||
"Renderer-specific args set without use_renderer=True: "
|
||||
f"{', '.join(renderer_args_set)}. Either enable the renderer or remove these knobs."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_lora_adapter_saving(self):
|
||||
if self.ckpt and self.ckpt.weights and self.ckpt.weights.save_adapter_separately:
|
||||
|
||||
+91
-53
@@ -21,7 +21,7 @@ dependencies = [
|
||||
"vllm>=0.20.2",
|
||||
"wandb>=0.26.1",
|
||||
"ring-flash-attn>=0.1.8",
|
||||
"prime>=0.5.73",
|
||||
"prime>=0.6.4",
|
||||
"pyzmq>=27.1.0",
|
||||
"aiolimiter>=1.2.1",
|
||||
"tenacity>=8.2.0",
|
||||
@@ -31,7 +31,7 @@ dependencies = [
|
||||
"uvloop>=0.21.0",
|
||||
"torchtitan",
|
||||
"verifiers",
|
||||
"renderers==0.1.6",
|
||||
"renderers",
|
||||
"dion",
|
||||
"tilelang>=0.1.8",
|
||||
"flash-linear-attention",
|
||||
@@ -59,20 +59,33 @@ flash-attn-cute = [
|
||||
"flash-attn-4",
|
||||
]
|
||||
envs = [
|
||||
"reverse-text",
|
||||
"alphabet-sort",
|
||||
"wiki-search",
|
||||
"math-python",
|
||||
"math-env",
|
||||
"code-env",
|
||||
"science-env",
|
||||
"logic-env",
|
||||
"color-codeword",
|
||||
"math500",
|
||||
"aime2024",
|
||||
"aime2025",
|
||||
"mini_swe_agent_plus",
|
||||
"deepdive"
|
||||
"alphabet-sort",
|
||||
"code-env",
|
||||
"color-codeword",
|
||||
"deepdive",
|
||||
"gpqa",
|
||||
"hle",
|
||||
"ifeval",
|
||||
"livecodebench",
|
||||
"logic-env",
|
||||
"math-env",
|
||||
"math-python",
|
||||
"math500",
|
||||
"mini-swe-agent-plus",
|
||||
"mini-swe-agent-plus-rlm",
|
||||
"mmlu-pro",
|
||||
"opencode-cp",
|
||||
"opencode-deepdive",
|
||||
"opencode-math",
|
||||
"opencode-science",
|
||||
"opencode-swe",
|
||||
"reverse-text",
|
||||
"science-env",
|
||||
"simpleqa-verified",
|
||||
"tau2-bench",
|
||||
"wiki-search",
|
||||
]
|
||||
disagg = [
|
||||
"deep-ep ; platform_machine == 'x86_64'",
|
||||
@@ -109,7 +122,38 @@ dev = [
|
||||
|
||||
|
||||
[tool.uv.workspace]
|
||||
members = ["packages/*"]
|
||||
members = [
|
||||
"packages/prime-rl-configs",
|
||||
"deps/verifiers",
|
||||
"deps/renderers",
|
||||
"deps/verifiers/environments/alphabet_sort",
|
||||
"deps/verifiers/environments/math_python",
|
||||
"deps/verifiers/environments/reverse_text",
|
||||
"deps/verifiers/environments/wiki_search",
|
||||
"deps/research-environments/environments/aime2024",
|
||||
"deps/research-environments/environments/aime2025",
|
||||
"deps/research-environments/environments/code_env",
|
||||
"deps/research-environments/environments/color_codeword",
|
||||
"deps/research-environments/environments/deepdive",
|
||||
"deps/research-environments/environments/gpqa",
|
||||
"deps/research-environments/environments/hle",
|
||||
"deps/research-environments/environments/ifeval",
|
||||
"deps/research-environments/environments/livecodebench",
|
||||
"deps/research-environments/environments/logic_env",
|
||||
"deps/research-environments/environments/math500",
|
||||
"deps/research-environments/environments/math_env",
|
||||
"deps/research-environments/environments/mini_swe_agent_plus",
|
||||
"deps/research-environments/environments/mini_swe_agent_plus_rlm",
|
||||
"deps/research-environments/environments/mmlu_pro",
|
||||
"deps/research-environments/environments/opencode_cp",
|
||||
"deps/research-environments/environments/opencode_deepdive",
|
||||
"deps/research-environments/environments/opencode_math",
|
||||
"deps/research-environments/environments/opencode_science",
|
||||
"deps/research-environments/environments/opencode_swe",
|
||||
"deps/research-environments/environments/science_env",
|
||||
"deps/research-environments/environments/simpleqa_verified",
|
||||
"deps/research-environments/environments/tau2_bench",
|
||||
]
|
||||
|
||||
[tool.uv]
|
||||
exclude-newer = "7 days"
|
||||
@@ -125,35 +169,20 @@ override-dependencies = [
|
||||
"nvidia-cudnn-cu12>=9.15",
|
||||
"nvidia-cutlass-dsl>=4.4.1",
|
||||
"transformers>=5.1.0.dev0",
|
||||
"torch>=2.9.0",
|
||||
"openenv-core",
|
||||
]
|
||||
|
||||
[tool.uv.exclude-newer-package]
|
||||
# we want latest vllm, remove next patch
|
||||
vllm = false
|
||||
flash_attn_3 = false
|
||||
# Self-vendored packages on our primeintellect index
|
||||
reverse-text = false
|
||||
alphabet-sort = false
|
||||
wiki-search = false
|
||||
math-python = false
|
||||
math-env = false
|
||||
code-env = false
|
||||
science-env = false
|
||||
logic-env = false
|
||||
color-codeword = false
|
||||
math500 = false
|
||||
aime2024 = false
|
||||
aime2025 = false
|
||||
deepdive = false
|
||||
mini_swe_agent_plus = false
|
||||
# PrimeIntellect-published on PyPI (trusted publisher)
|
||||
prime = false
|
||||
prime-sandboxes = false
|
||||
prime-tunnel = false
|
||||
prime-evals = false
|
||||
# Trusted git/URL sources pinned by rev or wheel URL (defensive: belt-and-suspenders)
|
||||
verifiers = false
|
||||
renderers = false
|
||||
vllm-router = false
|
||||
dion = false
|
||||
pydantic-config = false
|
||||
@@ -163,10 +192,38 @@ nixl-cu12 = false
|
||||
|
||||
[tool.uv.sources]
|
||||
prime-rl-configs = { workspace = true }
|
||||
verifiers = { workspace = true }
|
||||
renderers = { workspace = true }
|
||||
aime2024 = { workspace = true }
|
||||
aime2025 = { workspace = true }
|
||||
alphabet-sort = { workspace = true }
|
||||
code-env = { workspace = true }
|
||||
color-codeword = { workspace = true }
|
||||
deepdive = { workspace = true }
|
||||
gpqa = { workspace = true }
|
||||
hle = { workspace = true }
|
||||
ifeval = { workspace = true }
|
||||
livecodebench = { workspace = true }
|
||||
logic-env = { workspace = true }
|
||||
math-env = { workspace = true }
|
||||
math-python = { workspace = true }
|
||||
math500 = { workspace = true }
|
||||
mini-swe-agent-plus = { workspace = true }
|
||||
mini-swe-agent-plus-rlm = { workspace = true }
|
||||
mmlu-pro = { workspace = true }
|
||||
opencode-cp = { workspace = true }
|
||||
opencode-deepdive = { workspace = true }
|
||||
opencode-math = { workspace = true }
|
||||
opencode-science = { workspace = true }
|
||||
opencode-swe = { workspace = true }
|
||||
reverse-text = { workspace = true }
|
||||
science-env = { workspace = true }
|
||||
simpleqa-verified = { workspace = true }
|
||||
tau2-bench = { workspace = true }
|
||||
wiki-search = { workspace = true }
|
||||
torch = { index = "pytorch-cu128" }
|
||||
torchvision = { index = "pytorch-cu128" }
|
||||
torchaudio = { index = "pytorch-cu128" }
|
||||
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "aa428f3" }
|
||||
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
|
||||
transformers = { git = "https://github.com/huggingface/transformers.git", rev = "c1c3424" }
|
||||
@@ -177,20 +234,6 @@ vllm = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.20.2/vllm-0.20.2+cu129-cp38-abi3-manylinux_2_31_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.20.2/vllm-0.20.2+cu129-cp38-abi3-manylinux_2_31_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
reverse-text = { index = "primeintellect" }
|
||||
alphabet-sort = { index = "primeintellect" }
|
||||
wiki-search = { index = "primeintellect" }
|
||||
math-python = { index = "primeintellect" }
|
||||
math-env = { index = "primeintellect" }
|
||||
code-env = { index = "primeintellect" }
|
||||
science-env = { index = "primeintellect" }
|
||||
logic-env = { index = "primeintellect" }
|
||||
color-codeword = { index = "primeintellect" }
|
||||
math500 = { index = "primeintellect" }
|
||||
aime2024 = { index = "primeintellect" }
|
||||
aime2025 = { index = "primeintellect" }
|
||||
deepdive = { index = "primeintellect" }
|
||||
mini_swe_agent_plus = { index = "primeintellect" }
|
||||
deep-ep = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl" }
|
||||
deep-gemm = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl" }
|
||||
nixl-cu12 = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }
|
||||
@@ -205,17 +248,11 @@ mamba-ssm = [{ requirement = "torch", match-runtime = true }]
|
||||
[tool.uv.extra-build-variables]
|
||||
flash-attn = { FLASH_ATTENTION_SKIP_CUDA_BUILD = "TRUE" }
|
||||
|
||||
[[tool.uv.index]]
|
||||
name = "primeintellect"
|
||||
url = "https://hub.primeintellect.ai/primeintellect/simple/"
|
||||
explicit = true
|
||||
|
||||
[[tool.uv.index]]
|
||||
name = "pytorch-cu128"
|
||||
url = "https://download.pytorch.org/whl/cu128"
|
||||
explicit = true
|
||||
|
||||
|
||||
[[tool.uv.index]]
|
||||
name = "pytorch-cu128-test"
|
||||
url = "https://download.pytorch.org/whl/test/cu128"
|
||||
@@ -233,6 +270,7 @@ known-first-party = ["prime_rl"]
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 120
|
||||
extend-exclude = ["deps"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
addopts = "--strict-markers"
|
||||
|
||||
@@ -66,6 +66,29 @@ ensure_known_hosts() {
|
||||
fi
|
||||
}
|
||||
|
||||
# Initialize each submodule independently so that a missing private repo
|
||||
# (e.g. configs/private when the user lacks access) does not abort the install.
|
||||
init_submodules() {
|
||||
if [ ! -f .gitmodules ]; then
|
||||
return 0
|
||||
fi
|
||||
local paths failures
|
||||
paths=$(git config -f .gitmodules --get-regexp '^submodule\..*\.path$' | awk '{print $2}')
|
||||
failures=()
|
||||
for path in $paths; do
|
||||
log_info "Initializing submodule: ${path}"
|
||||
if git submodule update --init --recursive -- "$path"; then
|
||||
:
|
||||
else
|
||||
log_warn "Could not initialize submodule '${path}' (likely no access). Continuing without it."
|
||||
failures+=("$path")
|
||||
fi
|
||||
done
|
||||
if [ "${#failures[@]}" -gt 0 ]; then
|
||||
log_warn "Skipped submodules: ${failures[*]}"
|
||||
fi
|
||||
}
|
||||
|
||||
main() {
|
||||
assert_supported_platform
|
||||
|
||||
@@ -98,6 +121,13 @@ main() {
|
||||
cd ${REPO_ID}
|
||||
fi
|
||||
|
||||
if ! has_ssh_access; then
|
||||
git config url."https://github.com/".insteadOf "git@github.com:"
|
||||
fi
|
||||
|
||||
log_info "Initializing submodules..."
|
||||
init_submodules
|
||||
|
||||
log_info "Installing uv..."
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
|
||||
|
||||
@@ -23,6 +23,8 @@ from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import (
|
||||
|
||||
from prime_rl.trainer.models.glm4_moe import Glm4MoeConfig
|
||||
from prime_rl.trainer.models.glm4_moe import Glm4MoeForCausalLM as PrimeRLGlm4MoeForCausalLM
|
||||
from prime_rl.trainer.models.laguna import LagunaConfig
|
||||
from prime_rl.trainer.models.laguna import LagunaForCausalLM as PrimeRLLagunaForCausalLM
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2Config
|
||||
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2ForCausalLM as PrimeRLMiniMaxM2ForCausalLM
|
||||
@@ -130,6 +132,59 @@ ARCH_PRESETS = {
|
||||
"prime_model_class": PrimeRLMiniMaxM2ForCausalLM,
|
||||
"tokenizer_source": "MiniMaxAI/MiniMax-M2.1",
|
||||
},
|
||||
"laguna": {
|
||||
"config_class": LagunaConfig,
|
||||
"config_kwargs": dict(
|
||||
vocab_size=100352,
|
||||
hidden_size=512,
|
||||
intermediate_size=2048,
|
||||
num_hidden_layers=12,
|
||||
num_attention_heads=8,
|
||||
num_attention_heads_per_layer=[8] * 12,
|
||||
num_key_value_heads=4,
|
||||
head_dim=64,
|
||||
hidden_act="silu",
|
||||
max_position_embeddings=4096,
|
||||
rms_norm_eps=1e-6,
|
||||
rope_parameters={
|
||||
"full_attention": {
|
||||
"rope_type": "yarn",
|
||||
"rope_theta": 500000.0,
|
||||
"factor": 4.0,
|
||||
"original_max_position_embeddings": 1024,
|
||||
"beta_slow": 1.0,
|
||||
"beta_fast": 64.0,
|
||||
"attention_factor": 1.0,
|
||||
"partial_rotary_factor": 0.5,
|
||||
},
|
||||
"sliding_attention": {
|
||||
"rope_type": "default",
|
||||
"rope_theta": 10000.0,
|
||||
"partial_rotary_factor": 1.0,
|
||||
},
|
||||
},
|
||||
layer_types=["full_attention", "sliding_attention", "sliding_attention", "sliding_attention"] * 3,
|
||||
sliding_window=512,
|
||||
moe_intermediate_size=128,
|
||||
shared_expert_intermediate_size=128,
|
||||
num_experts=8,
|
||||
num_experts_per_tok=4,
|
||||
mlp_layer_types=["dense"] + ["sparse"] * 11,
|
||||
moe_routed_scaling_factor=2.5,
|
||||
use_grouped_mm=False,
|
||||
pad_token_id=9,
|
||||
bos_token_id=2,
|
||||
eos_token_id=[2, 24],
|
||||
auto_map={
|
||||
"AutoConfig": "poolside/Laguna-XS.2--configuration_laguna.LagunaConfig",
|
||||
"AutoModel": "poolside/Laguna-XS.2--modeling_laguna.LagunaModel",
|
||||
"AutoModelForCausalLM": "poolside/Laguna-XS.2--modeling_laguna.LagunaForCausalLM",
|
||||
},
|
||||
),
|
||||
"hf_model_class": None, # uses Poolside remote modeling code
|
||||
"prime_model_class": PrimeRLLagunaForCausalLM,
|
||||
"tokenizer_source": "poolside/Laguna-XS.2",
|
||||
},
|
||||
"qwen3_5_moe_vlm": {
|
||||
"config_fn": _qwen3_5_moe_vlm_config,
|
||||
"hf_model_class": HFQwen3_5MoeVLM,
|
||||
|
||||
@@ -177,4 +177,5 @@ In TOML, an empty section header does the same:
|
||||
- `src/prime_rl/utils/config.py` — re-exports `BaseConfig` and `cli` from pydantic_config
|
||||
- `src/prime_rl/configs/` — all domain-specific config classes
|
||||
- `configs/debug/` — minimal debug configs for testing
|
||||
- `configs/private/` — private configs via git submodule (internal only)
|
||||
- `examples/` — full example configs for various tasks
|
||||
|
||||
@@ -88,4 +88,5 @@ curl http://localhost:8000/v1/chat/completions \
|
||||
- `src/prime_rl/entrypoints/` — top-level entrypoints (`rl`, `sft`, `inference`)
|
||||
- `src/prime_rl/configs/` — all config classes
|
||||
- `configs/debug/` — minimal configs for quick testing
|
||||
- `configs/private/` — private configs submodule (if access granted)
|
||||
- `examples/` — full example configs for various tasks
|
||||
|
||||
@@ -5,13 +5,37 @@ description: How to install prime-rl and its optional dependencies. Use when set
|
||||
|
||||
# Installation
|
||||
|
||||
## Cloning
|
||||
|
||||
prime-rl is a monorepo with submodules. Clone the repo first, then initialize submodules explicitly:
|
||||
|
||||
```bash
|
||||
git clone git@github.com:PrimeIntellect-ai/prime-rl.git
|
||||
cd prime-rl
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments
|
||||
```
|
||||
|
||||
For an existing clone, initialize the public submodules by passing explicit paths:
|
||||
|
||||
```bash
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments
|
||||
```
|
||||
|
||||
Do **not** use `git submodule update --init --recursive` without explicit paths — it will also attempt to clone `configs/private` (a private submodule) and fail with "Repository not found" for users without access. Git will retry the clone once internally before aborting, which is expected behavior.
|
||||
|
||||
The public submodules live under `deps/`: `deps/verifiers/`, `deps/renderers/`, and `deps/research-environments/`. Each is also a uv workspace member, so source edits inside them apply to the prime-rl venv without re-sync.
|
||||
|
||||
The install script (`scripts/install.sh`) handles the private submodule gracefully — it iterates each submodule individually so a failed `configs/private` init does not abort the rest.
|
||||
|
||||
## Basic
|
||||
```bash
|
||||
uv sync # core dependencies only
|
||||
uv sync --group dev # dev tools: pytest, ruff, pre-commit
|
||||
uv sync --all-extras # recommended: includes flash-attn, flash-attn-cute, etc.
|
||||
uv sync --all-extras # recommended: includes envs, flash-attn, flash-attn-cute, etc.
|
||||
```
|
||||
|
||||
The `envs` extra installs the env packages listed in `pyproject.toml > [tool.uv.workspace] members`. Adding a new env means adding it there, in the `envs` extra, and in `[tool.uv.sources]`.
|
||||
|
||||
## Advanced
|
||||
|
||||
### Mamba-SSM (NemotronH models)
|
||||
|
||||
@@ -145,6 +145,8 @@ These tell you whether training is healthy or diverging.
|
||||
|--------|--------|-------------|
|
||||
| `mismatch_kl/mean` | trainer | KL divergence between trainer and (old) inference policy |
|
||||
| `entropy/mean` | trainer | policy entropy |
|
||||
| `masked_advantage_positive/mean` | trainer | fraction of DPPO-masked trainable tokens with positive advantage (W&B) |
|
||||
| `masked_advantage_negative/mean` | trainer | fraction of DPPO-masked trainable tokens with negative advantage (W&B) |
|
||||
| `optim/grad_norm` | trainer | gradient norm — spikes may precede divergence |
|
||||
|
||||
#### Performance
|
||||
|
||||
@@ -349,10 +349,10 @@ def rl_local(config: RLConfig):
|
||||
monitor_threads.append(monitor_thread)
|
||||
|
||||
# Monitor all processes for failures
|
||||
logger.success("Startup complete. Showing trainer logs...")
|
||||
logger.success("Startup complete. Showing orchestrator logs...")
|
||||
|
||||
tail_process = Popen(
|
||||
f"tail -F '{log_dir / 'trainer.log'}' | sed -u 's/^\\[[a-zA-Z]*[0-9]*\\]://'",
|
||||
f"tail -F '{log_dir / 'orchestrator.log'}'",
|
||||
shell=True,
|
||||
)
|
||||
processes.append(tail_process)
|
||||
|
||||
@@ -18,6 +18,37 @@ def transformers_v5_compat():
|
||||
monkey_patch_deep_gemm_ep_scatter()
|
||||
monkey_patch_deep_gemm_silu_mul_quant_int64()
|
||||
monkey_patch_dp_engine_core_pause_resume_deadlock()
|
||||
monkey_patch_vllm_layerwise_reload_alias_buffers()
|
||||
|
||||
|
||||
def monkey_patch_vllm_layerwise_reload_alias_buffers():
|
||||
# vLLM's layerwise reload materializes each buffer as an independent tensor
|
||||
# and then copies it back into the original kernel storage. When a buffer
|
||||
# aliases a parameter (e.g. NemotronH Mamba's mixer.conv_weights, a view of
|
||||
# mixer.conv1d.weight), the buffer copy stamps garbage into the parameter's
|
||||
# storage *after* the parameter has been correctly reloaded. Skip the copy
|
||||
# for any buffer that shares storage with a parameter; _place_kernel_tensors
|
||||
# re-registers the original view, which trivially reflects the parameter.
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.model_loader.reload import layerwise as reload_layerwise
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
def _copy_and_restore_kernel_tensors(layer: torch.nn.Module, info: reload_layerwise.LayerReloadingInfo):
|
||||
assert info.kernel_tensors is not None
|
||||
parameters, buffers = info.kernel_tensors
|
||||
param_storage_ptrs = {p.untyped_storage().data_ptr() for p in layer.parameters(recurse=True)}
|
||||
for name, param in parameters.items():
|
||||
param.data.copy_(getattr(layer, name))
|
||||
for name, buffer in buffers.items():
|
||||
if buffer.untyped_storage().data_ptr() in param_storage_ptrs:
|
||||
continue
|
||||
buffer.data.copy_(getattr(layer, name))
|
||||
|
||||
reload_layerwise._place_kernel_tensors(layer, info)
|
||||
|
||||
reload_layerwise._copy_and_restore_kernel_tensors = _copy_and_restore_kernel_tensors
|
||||
logger.warning("Enabled vLLM layerwise reload alias-buffer patch.")
|
||||
|
||||
|
||||
@triton.jit
|
||||
|
||||
@@ -222,6 +222,22 @@ class PrimeRlServingTokens(ServingTokens):
|
||||
|
||||
sampling_params: SamplingParams = request.sampling_params
|
||||
|
||||
# Upstream ``ServingTokens.serve_tokens`` parses ``request.kv_transfer_params``
|
||||
# but never threads it into the engine, so PD disagg never fires on
|
||||
# ``/inference/v1/generate`` — decode receives an empty NIXL handshake
|
||||
# and ends up re-prefilling the prompt locally (~100× slower under
|
||||
# concurrency). The chat path bridges this via
|
||||
# ``ChatCompletionRequestWithTokens.to_sampling_params``; we mirror that
|
||||
# bridge here so the engine's KV connector picks the params up out of
|
||||
# ``sampling_params.extra_args``.
|
||||
#
|
||||
# Upstream fix: https://github.com/vllm-project/vllm/pull/42644 — drop
|
||||
# this block once we pin a vLLM version that includes it.
|
||||
if request.kv_transfer_params is not None:
|
||||
extra = sampling_params.extra_args or {}
|
||||
extra["kv_transfer_params"] = request.kv_transfer_params
|
||||
sampling_params.extra_args = extra
|
||||
|
||||
# Server-side ``max_tokens`` defaulting — see module docstring.
|
||||
# Mirrors ``OpenAIServingChat`` (vllm/entrypoints/openai/chat_completion/
|
||||
# serving.py:284) so callers that omit ``max_tokens`` don't get capped
|
||||
|
||||
@@ -32,6 +32,8 @@ class InflightRequest:
|
||||
env_name: str
|
||||
group_id: int | None = None
|
||||
rollout_count: int = 1
|
||||
# Dispatch round the request belongs to (see GroupState.current_round).
|
||||
round_id: int = 0
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -42,6 +44,19 @@ class GroupState:
|
||||
rollouts_to_schedule: int
|
||||
completed_rollouts: list[vf.RolloutOutput] = field(default_factory=list)
|
||||
pinned_client: vf.ClientConfig | None = None
|
||||
# Number of dispatch rounds in which at least one rollout returned errored
|
||||
# or empty trajectories. Compared against
|
||||
# config.max_error_reschedule_attempts to decide when to drop a
|
||||
# permanently-stuck group. Counts rounds, not rollouts: a failed round in
|
||||
# an individual-scoring env that happens to dispatch N rollouts at once
|
||||
# still only counts as 1.
|
||||
failed_attempts: int = 0
|
||||
# Round id assigned to newly-dispatched rollouts. Advances after a failure
|
||||
# is counted so the resulting reschedule starts a new round.
|
||||
current_round: int = 0
|
||||
# Highest round already counted as failed; used to dedupe failures from
|
||||
# multiple rollouts in the same round.
|
||||
last_failed_round: int = -1
|
||||
|
||||
|
||||
class Scheduler:
|
||||
@@ -114,6 +129,7 @@ class Scheduler:
|
||||
self.empty_rollouts_by_env: dict[str, int] = defaultdict(int)
|
||||
self.errored_rollouts_by_env: dict[str, int] = defaultdict(int)
|
||||
self.total_rollouts_by_env: dict[str, int] = defaultdict(int)
|
||||
self.dropped_groups_by_env: dict[str, int] = defaultdict(int)
|
||||
self.last_batch_generation_time = 0.0
|
||||
|
||||
@property
|
||||
@@ -229,6 +245,7 @@ class Scheduler:
|
||||
env_name=env_name,
|
||||
group_id=group_id,
|
||||
rollout_count=rollout_count,
|
||||
round_id=group.current_round,
|
||||
)
|
||||
|
||||
@property
|
||||
@@ -434,18 +451,21 @@ class Scheduler:
|
||||
# Check for empty/errored rollouts and reschedule
|
||||
valid_rollouts = []
|
||||
has_failures = False
|
||||
last_failure_reason: str | None = None
|
||||
for rollout in rollouts:
|
||||
if rollout["error"] is not None:
|
||||
self.errored_rollouts_by_env[env_name] += 1
|
||||
has_failures = True
|
||||
last_failure_reason = rollout["error"]["error_chain_repr"]
|
||||
self.logger.warning(
|
||||
f"Rollout error in group {group_id} ({env_name}), re-scheduling "
|
||||
f"({len(group.completed_rollouts)}/{self.rollouts_per_example} complete): "
|
||||
f"{rollout['error']['error_chain_repr']}"
|
||||
f"{last_failure_reason}"
|
||||
)
|
||||
elif len(rollout["trajectory"]) == 0:
|
||||
self.empty_rollouts_by_env[env_name] += 1
|
||||
has_failures = True
|
||||
last_failure_reason = "empty trajectory"
|
||||
self.logger.warning(
|
||||
f"Empty trajectory in group {group_id} ({env_name}), re-scheduling "
|
||||
f"({len(group.completed_rollouts)}/{self.rollouts_per_example} complete)"
|
||||
@@ -454,6 +474,32 @@ class Scheduler:
|
||||
rollout["env_name"] = env_name
|
||||
valid_rollouts.append(rollout)
|
||||
|
||||
if has_failures:
|
||||
# Dedupe failures within the same dispatch round: an
|
||||
# individual-scoring env dispatches N rollouts at once,
|
||||
# so a single failed round can produce up to N failed
|
||||
# tasks. We only count the round once.
|
||||
if rollout_info.round_id > group.last_failed_round:
|
||||
group.failed_attempts += 1
|
||||
group.last_failed_round = rollout_info.round_id
|
||||
group.current_round = rollout_info.round_id + 1
|
||||
max_attempts = self.config.max_error_reschedule_attempts
|
||||
if max_attempts is not None and group.failed_attempts >= max_attempts:
|
||||
# Permanently-stuck group: drop it from this step and let the
|
||||
# rest of the batch proceed. Avoids a single bad example (e.g.
|
||||
# an agent rollout whose sandbox poll keeps timing out)
|
||||
# blocking step progress forever.
|
||||
self.dropped_groups_by_env[env_name] += 1
|
||||
self.logger.warning(
|
||||
f"Dropping group {group_id} ({env_name}) after {group.failed_attempts} "
|
||||
f"failed dispatch rounds ({len(group.completed_rollouts)}/{self.rollouts_per_example} "
|
||||
f"complete). Last failure: {last_failure_reason}. Set "
|
||||
f"orchestrator.max_error_reschedule_attempts higher (or to None) "
|
||||
f"to retry more aggressively."
|
||||
)
|
||||
await self.drop_group(group_id)
|
||||
continue
|
||||
|
||||
if has_failures and env.requires_group_scoring:
|
||||
# Group scoring requires all rollouts — discard partial results, reschedule full group
|
||||
group.completed_rollouts.clear()
|
||||
@@ -530,6 +576,7 @@ class Scheduler:
|
||||
"scheduler/cancelled_rollouts": self.cancelled_rollouts_count,
|
||||
"empty_rollouts/all": sum(self.empty_rollouts_by_env.values()) / max(total_rollouts, 1),
|
||||
"errored_rollouts/all": sum(self.errored_rollouts_by_env.values()) / max(total_rollouts, 1),
|
||||
"dropped_groups/all": sum(self.dropped_groups_by_env.values()),
|
||||
"off_policy_level/all/max": self.max_off_policy_level,
|
||||
"off_policy_level/all/mean": self.mean_off_policy_level,
|
||||
}
|
||||
@@ -537,6 +584,8 @@ class Scheduler:
|
||||
env_total = max(self.total_rollouts_by_env[env_name], 1)
|
||||
metrics[f"empty_rollouts/{env_name}"] = self.empty_rollouts_by_env.get(env_name, 0) / env_total
|
||||
metrics[f"errored_rollouts/{env_name}"] = self.errored_rollouts_by_env.get(env_name, 0) / env_total
|
||||
for env_name, count in self.dropped_groups_by_env.items():
|
||||
metrics[f"dropped_groups/{env_name}"] = count
|
||||
by_env: dict[str, list[int]] = {}
|
||||
for info in self.inflight_requests.values():
|
||||
by_env.setdefault(info.env_name, []).append(info.off_policy_steps)
|
||||
@@ -547,6 +596,7 @@ class Scheduler:
|
||||
self.empty_rollouts_by_env.clear()
|
||||
self.errored_rollouts_by_env.clear()
|
||||
self.total_rollouts_by_env.clear()
|
||||
self.dropped_groups_by_env.clear()
|
||||
|
||||
# Add inference pool metrics (e.g. elastic pool server counts)
|
||||
metrics.update(self.inference_pool.get_metrics())
|
||||
|
||||
@@ -113,11 +113,11 @@ echo "INFER_URLS=${INFER_URLS}"
|
||||
# termination and cause the next launch to hang (e.g. decode engines stuck at
|
||||
# "Waiting for READY message from DP Coordinator"). Harmless on clean nodes.
|
||||
srun bash -c '
|
||||
pkill -9 -f "python.*prime_rl" 2>/dev/null
|
||||
pkill -9 -f "torchrun" 2>/dev/null
|
||||
pkill -9 -f "vllm-router" 2>/dev/null
|
||||
pkill -9 -f "vllm" 2>/dev/null
|
||||
pkill -9 -f "prime_rl" 2>/dev/null
|
||||
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
|
||||
pkill -9 -f "[t]orchrun" 2>/dev/null
|
||||
pkill -9 -f "[v]llm-router" 2>/dev/null
|
||||
pkill -9 -f "[v]llm" 2>/dev/null
|
||||
pkill -9 -f "[p]rime_rl" 2>/dev/null
|
||||
# Also match prctl-set process names (kernel comm) like "vllm::router"
|
||||
# which pkill -f does not see because -f only matches the cmdline.
|
||||
pkill -9 "vllm" 2>/dev/null
|
||||
|
||||
@@ -157,11 +157,11 @@ uv sync --all-extras
|
||||
# termination and cause the next launch to hang (e.g. decode engines stuck at
|
||||
# "Waiting for READY message from DP Coordinator"). Harmless on clean nodes.
|
||||
srun bash -c '
|
||||
pkill -9 -f "python.*prime_rl" 2>/dev/null
|
||||
pkill -9 -f "torchrun" 2>/dev/null
|
||||
pkill -9 -f "vllm-router" 2>/dev/null
|
||||
pkill -9 -f "vllm" 2>/dev/null
|
||||
pkill -9 -f "prime_rl" 2>/dev/null
|
||||
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
|
||||
pkill -9 -f "[t]orchrun" 2>/dev/null
|
||||
pkill -9 -f "[v]llm-router" 2>/dev/null
|
||||
pkill -9 -f "[v]llm" 2>/dev/null
|
||||
pkill -9 -f "[p]rime_rl" 2>/dev/null
|
||||
# Also match prctl-set process names (kernel comm) like "vllm::router"
|
||||
# which pkill -f does not see because -f only matches the cmdline.
|
||||
pkill -9 "vllm" 2>/dev/null
|
||||
|
||||
@@ -64,11 +64,11 @@ cd $PROJECT_DIR && uv sync --all-extras
|
||||
# processes and vLLM/torch IPC files under /dev/shm and /tmp can survive SLURM
|
||||
# termination and cause the next launch to hang. Harmless on clean nodes.
|
||||
srun bash -c '
|
||||
pkill -9 -f "python.*prime_rl" 2>/dev/null
|
||||
pkill -9 -f "torchrun" 2>/dev/null
|
||||
pkill -9 -f "vllm-router" 2>/dev/null
|
||||
pkill -9 -f "vllm" 2>/dev/null
|
||||
pkill -9 -f "prime_rl" 2>/dev/null
|
||||
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
|
||||
pkill -9 -f "[t]orchrun" 2>/dev/null
|
||||
pkill -9 -f "[v]llm-router" 2>/dev/null
|
||||
pkill -9 -f "[v]llm" 2>/dev/null
|
||||
pkill -9 -f "[p]rime_rl" 2>/dev/null
|
||||
# Also match prctl-set process names (kernel comm) like "vllm::router"
|
||||
# which pkill -f does not see because -f only matches the cmdline.
|
||||
pkill -9 "vllm" 2>/dev/null
|
||||
|
||||
@@ -13,6 +13,7 @@ from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.glm4_moe import Glm4MoeConfig, Glm4MoeForCausalLM
|
||||
from prime_rl.trainer.models.glm_moe_dsa import GlmMoeDsaConfig, GlmMoeDsaForCausalLM
|
||||
from prime_rl.trainer.models.gpt_oss import GptOssConfig, GptOssForCausalLM
|
||||
from prime_rl.trainer.models.laguna import LagunaConfig, LagunaForCausalLM
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput, cast_float_and_contiguous
|
||||
from prime_rl.trainer.models.llama import LlamaForCausalLM
|
||||
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2Config, MiniMaxM2ForCausalLM
|
||||
@@ -24,6 +25,7 @@ from prime_rl.trainer.models.qwen3_moe import Qwen3MoeConfig, Qwen3MoeForCausalL
|
||||
AutoConfig.register("afmoe", AfmoeConfig, exist_ok=True)
|
||||
AutoConfig.register("glm4_moe", Glm4MoeConfig, exist_ok=True)
|
||||
AutoConfig.register("glm_moe_dsa", GlmMoeDsaConfig, exist_ok=True)
|
||||
AutoConfig.register("laguna", LagunaConfig, exist_ok=True)
|
||||
AutoConfig.register("minimax_m2", MiniMaxM2Config, exist_ok=True)
|
||||
AutoConfig.register("nemotron_h", NemotronHConfig, exist_ok=True)
|
||||
AutoConfig.register("qwen3_moe", Qwen3MoeConfig, exist_ok=True)
|
||||
@@ -35,6 +37,7 @@ _CUSTOM_CAUSAL_LM_MAPPING.register(LlamaConfig, LlamaForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(AfmoeConfig, AfmoeForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(Glm4MoeConfig, Glm4MoeForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(GlmMoeDsaConfig, GlmMoeDsaForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(LagunaConfig, LagunaForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(MiniMaxM2Config, MiniMaxM2ForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(NemotronHConfig, NemotronHForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(Qwen3MoeConfig, Qwen3MoeForCausalLM, exist_ok=True)
|
||||
|
||||
@@ -91,7 +91,8 @@ def postprocess(
|
||||
pass_configs={
|
||||
tilelang.PassConfigKey.TL_DISABLE_TMA_LOWER: True,
|
||||
tilelang.PassConfigKey.TL_DISABLE_WARP_SPECIALIZED: True,
|
||||
tilelang.PassConfigKey.TL_ENABLE_AGGRESSIVE_SHARED_MEMORY_MERGE: True,
|
||||
# Avoid TileLang MLA backward NaNs: https://github.com/tile-ai/tilelang/issues/2199
|
||||
tilelang.PassConfigKey.TL_ENABLE_AGGRESSIVE_SHARED_MEMORY_MERGE: False,
|
||||
},
|
||||
)
|
||||
def bwd(
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
from prime_rl.trainer.models.laguna.configuration_laguna import LagunaConfig
|
||||
from prime_rl.trainer.models.laguna.modeling_laguna import (
|
||||
LagunaForCausalLM,
|
||||
LagunaModel,
|
||||
LagunaPreTrainedModel,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"LagunaConfig",
|
||||
"LagunaForCausalLM",
|
||||
"LagunaModel",
|
||||
"LagunaPreTrainedModel",
|
||||
]
|
||||
@@ -0,0 +1,190 @@
|
||||
from typing import Any, Literal
|
||||
|
||||
from transformers.configuration_utils import PretrainedConfig
|
||||
|
||||
|
||||
class LagunaConfig(PretrainedConfig):
|
||||
"""Configuration for Poolside Laguna MoE models."""
|
||||
|
||||
model_type = "laguna"
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
attribute_map = {"num_local_experts": "num_experts"}
|
||||
|
||||
base_model_tp_plan = {
|
||||
"layers.*.self_attn.q_proj": "colwise",
|
||||
"layers.*.self_attn.k_proj": "colwise",
|
||||
"layers.*.self_attn.v_proj": "colwise",
|
||||
"layers.*.self_attn.g_proj": "colwise",
|
||||
"layers.*.self_attn.o_proj": "rowwise",
|
||||
"layers.*.self_attn.q_norm": "replicated_with_grad_allreduce",
|
||||
"layers.*.self_attn.k_norm": "replicated_with_grad_allreduce",
|
||||
"layers.*.mlp.gate_proj": "colwise",
|
||||
"layers.*.mlp.up_proj": "colwise",
|
||||
"layers.*.mlp.down_proj": "rowwise",
|
||||
"layers.*.mlp.experts.gate_up_proj": "packed_colwise",
|
||||
"layers.*.mlp.experts.down_proj": "rowwise",
|
||||
"layers.*.mlp.experts": "moe_tp_experts",
|
||||
"layers.*.shared_expert.w1": "colwise",
|
||||
"layers.*.shared_expert.w2": "rowwise",
|
||||
"layers.*.shared_expert.w3": "colwise",
|
||||
}
|
||||
base_model_pp_plan = {
|
||||
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
||||
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
|
||||
"norm": (["hidden_states"], ["hidden_states"]),
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vocab_size: int = 100352,
|
||||
hidden_size: int = 2048,
|
||||
intermediate_size: int = 8192,
|
||||
num_hidden_layers: int = 40,
|
||||
num_attention_heads: int = 48,
|
||||
num_key_value_heads: int = 8,
|
||||
hidden_act: str = "silu",
|
||||
max_position_embeddings: int = 131072,
|
||||
initializer_range: float = 0.02,
|
||||
rms_norm_eps: float = 1e-6,
|
||||
use_cache: bool = True,
|
||||
tie_word_embeddings: bool = False,
|
||||
rope_parameters: dict[str, Any] | None = None,
|
||||
rope_scaling: dict[str, Any] | None = None,
|
||||
sliding_window: int | None = 512,
|
||||
attention_dropout: float = 0.0,
|
||||
moe_intermediate_size: int = 512,
|
||||
shared_expert_intermediate_size: int = 512,
|
||||
num_experts_per_tok: int = 8,
|
||||
num_experts: int = 256,
|
||||
output_router_logits: bool = False,
|
||||
router_aux_loss_coef: float = 0.001,
|
||||
layer_types: list[str] | None = None,
|
||||
pad_token_id: int | None = None,
|
||||
bos_token_id: int | None = None,
|
||||
eos_token_id: int | list[int] | None = None,
|
||||
head_dim: int = 128,
|
||||
attention_bias: bool = False,
|
||||
partial_rotary_factor: float | None = None,
|
||||
num_attention_heads_per_layer: list[int] | None = None,
|
||||
mlp_layer_types: list[str] | None = None,
|
||||
moe_routed_scaling_factor: float = 1.0,
|
||||
moe_apply_router_weight_on_input: bool = False,
|
||||
moe_router_logit_softcapping: float = 0.0,
|
||||
load_balance_coeff: float | None = 1e-3,
|
||||
use_grouped_mm: bool = True,
|
||||
**kwargs,
|
||||
):
|
||||
raw_rope_parameters = rope_parameters if rope_parameters is not None else rope_scaling
|
||||
|
||||
self.vocab_size = vocab_size
|
||||
self.hidden_size = hidden_size
|
||||
self.intermediate_size = intermediate_size
|
||||
self.num_hidden_layers = num_hidden_layers
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.num_key_value_heads = num_key_value_heads
|
||||
self.hidden_act = hidden_act
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
self.initializer_range = initializer_range
|
||||
self.rms_norm_eps = rms_norm_eps
|
||||
self.use_cache = use_cache
|
||||
self.sliding_window = sliding_window
|
||||
self.attention_dropout = attention_dropout
|
||||
self.moe_intermediate_size = moe_intermediate_size
|
||||
self.shared_expert_intermediate_size = shared_expert_intermediate_size
|
||||
self.num_experts_per_tok = num_experts_per_tok
|
||||
self.num_experts = num_experts
|
||||
self.output_router_logits = output_router_logits
|
||||
self.router_aux_loss_coef = router_aux_loss_coef
|
||||
self.layer_types = layer_types or ["full_attention"] * num_hidden_layers
|
||||
self.head_dim = head_dim
|
||||
self.attention_bias = attention_bias
|
||||
self.partial_rotary_factor = partial_rotary_factor
|
||||
self.num_attention_heads_per_layer = num_attention_heads_per_layer or [num_attention_heads] * num_hidden_layers
|
||||
self.mlp_layer_types = mlp_layer_types or ["dense"] + ["sparse"] * (num_hidden_layers - 1)
|
||||
self.moe_routed_scaling_factor = moe_routed_scaling_factor
|
||||
self.moe_apply_router_weight_on_input = moe_apply_router_weight_on_input
|
||||
self.moe_router_logit_softcapping = moe_router_logit_softcapping
|
||||
self.load_balance_coeff = load_balance_coeff
|
||||
self.use_grouped_mm = use_grouped_mm
|
||||
|
||||
super().__init__(
|
||||
pad_token_id=pad_token_id,
|
||||
bos_token_id=bos_token_id,
|
||||
eos_token_id=eos_token_id,
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
self.rope_parameters = raw_rope_parameters
|
||||
self._normalize_rope_parameters()
|
||||
self.rope_scaling = self.rope_parameters
|
||||
self.validate_architecture()
|
||||
|
||||
def _normalize_rope_parameters(self) -> None:
|
||||
default_rope_params: dict[Literal["full_attention", "sliding_attention"], dict[str, Any]] = {
|
||||
"full_attention": {"rope_type": "default", "rope_theta": 500000.0},
|
||||
"sliding_attention": {"rope_type": "default", "rope_theta": 10000.0},
|
||||
}
|
||||
layer_types = set(self.layer_types)
|
||||
rope_params = self.rope_parameters or {}
|
||||
is_nested = isinstance(rope_params, dict) and any(key in layer_types for key in rope_params)
|
||||
if is_nested:
|
||||
nested = {}
|
||||
for layer_type in layer_types:
|
||||
params = dict(default_rope_params.get(layer_type, {}))
|
||||
params.update(rope_params.get(layer_type, {}))
|
||||
nested[layer_type] = params
|
||||
else:
|
||||
nested = {}
|
||||
for layer_type in layer_types:
|
||||
params = dict(default_rope_params.get(layer_type, {}))
|
||||
params.update(rope_params)
|
||||
nested[layer_type] = params
|
||||
|
||||
if self.partial_rotary_factor is not None:
|
||||
for params in nested.values():
|
||||
params.setdefault("partial_rotary_factor", self.partial_rotary_factor)
|
||||
|
||||
for params in nested.values():
|
||||
params.setdefault("rope_type", "default")
|
||||
|
||||
self.rope_parameters = nested
|
||||
self.partial_rotary_factor = None
|
||||
|
||||
def convert_rope_params_to_dict(self, **kwargs):
|
||||
return kwargs
|
||||
|
||||
def _validate_yarn_rope_parameters(self, rope_parameters: dict, ignore_keys=None) -> None:
|
||||
flat_rope_parameters = self.rope_parameters
|
||||
self.rope_parameters = rope_parameters
|
||||
try:
|
||||
super()._validate_yarn_rope_parameters(rope_parameters, ignore_keys=ignore_keys)
|
||||
finally:
|
||||
self.rope_parameters = flat_rope_parameters
|
||||
|
||||
def validate_architecture(self) -> None:
|
||||
if self.moe_apply_router_weight_on_input:
|
||||
raise NotImplementedError("moe_apply_router_weight_on_input=True is not supported by PrimeRL Laguna.")
|
||||
if len(self.num_attention_heads_per_layer) != self.num_hidden_layers:
|
||||
raise ValueError(
|
||||
f"num_attention_heads_per_layer length ({len(self.num_attention_heads_per_layer)}) "
|
||||
f"must equal num_hidden_layers ({self.num_hidden_layers})."
|
||||
)
|
||||
for num_heads in self.num_attention_heads_per_layer:
|
||||
if num_heads % self.num_key_value_heads != 0:
|
||||
raise ValueError(
|
||||
f"Per-layer attention head count ({num_heads}) must be divisible by "
|
||||
f"num_key_value_heads ({self.num_key_value_heads})."
|
||||
)
|
||||
if len(self.layer_types) != self.num_hidden_layers:
|
||||
raise ValueError(
|
||||
f"layer_types length ({len(self.layer_types)}) must equal num_hidden_layers ({self.num_hidden_layers})."
|
||||
)
|
||||
if len(self.mlp_layer_types) != self.num_hidden_layers:
|
||||
raise ValueError(
|
||||
f"mlp_layer_types length ({len(self.mlp_layer_types)}) "
|
||||
f"must equal num_hidden_layers ({self.num_hidden_layers})."
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["LagunaConfig"]
|
||||
@@ -0,0 +1,120 @@
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
|
||||
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
|
||||
return max(int(key.split(".")[2]) for key in state_dict if key.startswith("model.layers.")) + 1
|
||||
|
||||
|
||||
def _pop_first(state_dict: dict[str, Tensor], keys: tuple[str, ...]) -> Tensor | None:
|
||||
for key in keys:
|
||||
if key in state_dict:
|
||||
return state_dict.pop(key)
|
||||
return None
|
||||
|
||||
|
||||
def convert_hf_layer_to_prime(state_dict: dict[str, Tensor], layer_idx: int) -> None:
|
||||
prefix = f"model.layers.{layer_idx}"
|
||||
gate_key = f"{prefix}.mlp.gate.weight"
|
||||
if gate_key not in state_dict:
|
||||
return
|
||||
|
||||
state_dict[f"{prefix}.mlp.router.gate.weight"] = state_dict.pop(gate_key)
|
||||
|
||||
expert_bias = _pop_first(
|
||||
state_dict,
|
||||
(
|
||||
f"{prefix}.mlp.experts.e_score_correction_bias",
|
||||
f"{prefix}.mlp.gate.e_score_correction_bias",
|
||||
),
|
||||
)
|
||||
if expert_bias is not None:
|
||||
state_dict[f"{prefix}.mlp.expert_bias"] = expert_bias
|
||||
|
||||
fused_key = f"{prefix}.mlp.experts.gate_up_proj"
|
||||
if fused_key in state_dict:
|
||||
gate_up_proj = state_dict.pop(fused_key)
|
||||
down_proj = state_dict.pop(f"{prefix}.mlp.experts.down_proj")
|
||||
moe_dim = gate_up_proj.shape[1] // 2
|
||||
w1 = gate_up_proj[:, :moe_dim, :]
|
||||
w3 = gate_up_proj[:, moe_dim:, :]
|
||||
w2 = down_proj
|
||||
else:
|
||||
expert_ids = sorted(
|
||||
int(key[len(f"{prefix}.mlp.experts.") :].split(".")[0])
|
||||
for key in state_dict
|
||||
if key.startswith(f"{prefix}.mlp.experts.") and key.endswith(".gate_proj.weight")
|
||||
)
|
||||
if not expert_ids:
|
||||
return
|
||||
|
||||
first_down = state_dict[f"{prefix}.mlp.experts.{expert_ids[0]}.down_proj.weight"]
|
||||
dim, moe_dim = first_down.shape
|
||||
w1 = torch.empty((len(expert_ids), moe_dim, dim), dtype=first_down.dtype, device=first_down.device)
|
||||
w2 = torch.empty((len(expert_ids), dim, moe_dim), dtype=first_down.dtype, device=first_down.device)
|
||||
w3 = torch.empty((len(expert_ids), moe_dim, dim), dtype=first_down.dtype, device=first_down.device)
|
||||
for out_idx, expert_idx in enumerate(expert_ids):
|
||||
w1[out_idx].copy_(state_dict.pop(f"{prefix}.mlp.experts.{expert_idx}.gate_proj.weight"))
|
||||
w2[out_idx].copy_(state_dict.pop(f"{prefix}.mlp.experts.{expert_idx}.down_proj.weight"))
|
||||
w3[out_idx].copy_(state_dict.pop(f"{prefix}.mlp.experts.{expert_idx}.up_proj.weight"))
|
||||
|
||||
state_dict[f"{prefix}.mlp.experts.w1"] = w1
|
||||
state_dict[f"{prefix}.mlp.experts.w2"] = w2
|
||||
state_dict[f"{prefix}.mlp.experts.w3"] = w3
|
||||
|
||||
shared_prefix = None
|
||||
for candidate in (f"{prefix}.mlp.shared_expert", f"{prefix}.mlp.shared_experts"):
|
||||
if f"{candidate}.gate_proj.weight" in state_dict:
|
||||
shared_prefix = candidate
|
||||
break
|
||||
|
||||
if shared_prefix is not None:
|
||||
state_dict[f"{prefix}.shared_expert.w1.weight"] = state_dict.pop(f"{shared_prefix}.gate_proj.weight")
|
||||
state_dict[f"{prefix}.shared_expert.w2.weight"] = state_dict.pop(f"{shared_prefix}.down_proj.weight")
|
||||
state_dict[f"{prefix}.shared_expert.w3.weight"] = state_dict.pop(f"{shared_prefix}.up_proj.weight")
|
||||
|
||||
|
||||
def convert_prime_layer_to_hf(state_dict: dict[str, Tensor], layer_idx: int) -> None:
|
||||
prefix = f"model.layers.{layer_idx}"
|
||||
router_key = f"{prefix}.mlp.router.gate.weight"
|
||||
if router_key not in state_dict:
|
||||
return
|
||||
|
||||
if f"{prefix}.mlp.tokens_per_expert" in state_dict:
|
||||
del state_dict[f"{prefix}.mlp.tokens_per_expert"]
|
||||
if f"{prefix}.mlp.expert_bias" in state_dict:
|
||||
state_dict[f"{prefix}.mlp.experts.e_score_correction_bias"] = state_dict.pop(f"{prefix}.mlp.expert_bias")
|
||||
|
||||
state_dict[f"{prefix}.mlp.gate.weight"] = state_dict.pop(router_key)
|
||||
|
||||
w1 = state_dict.pop(f"{prefix}.mlp.experts.w1")
|
||||
w2 = state_dict.pop(f"{prefix}.mlp.experts.w2")
|
||||
w3 = state_dict.pop(f"{prefix}.mlp.experts.w3")
|
||||
for expert_idx in range(w1.shape[0]):
|
||||
state_dict[f"{prefix}.mlp.experts.{expert_idx}.gate_proj.weight"] = w1[expert_idx]
|
||||
state_dict[f"{prefix}.mlp.experts.{expert_idx}.down_proj.weight"] = w2[expert_idx]
|
||||
state_dict[f"{prefix}.mlp.experts.{expert_idx}.up_proj.weight"] = w3[expert_idx]
|
||||
|
||||
shared_key = f"{prefix}.shared_expert.w1.weight"
|
||||
if shared_key in state_dict:
|
||||
state_dict[f"{prefix}.mlp.shared_expert.gate_proj.weight"] = state_dict.pop(shared_key)
|
||||
state_dict[f"{prefix}.mlp.shared_expert.down_proj.weight"] = state_dict.pop(f"{prefix}.shared_expert.w2.weight")
|
||||
state_dict[f"{prefix}.mlp.shared_expert.up_proj.weight"] = state_dict.pop(f"{prefix}.shared_expert.w3.weight")
|
||||
|
||||
|
||||
def convert_hf_to_prime(state_dict: dict[str, Tensor]) -> None:
|
||||
for layer_idx in range(get_max_layer_num(state_dict)):
|
||||
convert_hf_layer_to_prime(state_dict, layer_idx)
|
||||
|
||||
|
||||
def convert_prime_to_hf(state_dict: dict[str, Tensor]) -> None:
|
||||
for layer_idx in range(get_max_layer_num(state_dict)):
|
||||
convert_prime_layer_to_hf(state_dict, layer_idx)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"convert_hf_layer_to_prime",
|
||||
"convert_hf_to_prime",
|
||||
"convert_prime_layer_to_hf",
|
||||
"convert_prime_to_hf",
|
||||
]
|
||||
@@ -0,0 +1,482 @@
|
||||
from collections.abc import Callable
|
||||
from typing import Optional, Union
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import Tensor, nn
|
||||
from transformers.cache_utils import Cache
|
||||
from transformers.generation import GenerationMixin
|
||||
from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask
|
||||
from transformers.modeling_layers import GradientCheckpointingLayer
|
||||
from transformers.modeling_outputs import MoeModelOutputWithPast
|
||||
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
||||
from transformers.processing_utils import Unpack
|
||||
from transformers.utils import TransformersKwargs, can_return_tuple
|
||||
from transformers.utils.generic import maybe_autocast
|
||||
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.laguna.configuration_laguna import LagunaConfig
|
||||
from prime_rl.trainer.models.laguna.converting_laguna import (
|
||||
convert_hf_layer_to_prime,
|
||||
convert_hf_to_prime,
|
||||
convert_prime_layer_to_hf,
|
||||
convert_prime_to_hf,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.attn import AttentionConfig, FlashAttention, SDPAAttention
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.layers.moe import FeedForward, MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
|
||||
|
||||
class LagunaRotaryEmbedding(nn.Module):
|
||||
def __init__(self, config: LagunaConfig, device=None):
|
||||
super().__init__()
|
||||
self.max_seq_len_cached = config.max_position_embeddings
|
||||
self.original_max_seq_len = config.max_position_embeddings
|
||||
self.config = config
|
||||
self.layer_types = list(dict.fromkeys(config.layer_types))
|
||||
self.rope_type = {}
|
||||
|
||||
for layer_type in self.layer_types:
|
||||
rope_params = self.config.rope_parameters[layer_type]
|
||||
self.rope_type[layer_type] = rope_params["rope_type"]
|
||||
rope_init_fn: Callable = self.compute_default_rope_parameters
|
||||
if self.rope_type[layer_type] != "default":
|
||||
rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type[layer_type]]
|
||||
inv_freq, attention_scaling = rope_init_fn(self.config, device, layer_type=layer_type)
|
||||
self.register_buffer(f"{layer_type}_inv_freq", inv_freq, persistent=False)
|
||||
self.register_buffer(f"{layer_type}_original_inv_freq", inv_freq.clone(), persistent=False)
|
||||
setattr(self, f"{layer_type}_attention_scaling", attention_scaling)
|
||||
|
||||
@staticmethod
|
||||
def compute_default_rope_parameters(
|
||||
config: LagunaConfig | None = None,
|
||||
device: Optional[torch.device] = None,
|
||||
seq_len: int | None = None,
|
||||
layer_type: str | None = None,
|
||||
) -> tuple[torch.Tensor, float]:
|
||||
rope_params = config.rope_parameters[layer_type]
|
||||
base = rope_params["rope_theta"]
|
||||
partial_rotary_factor = rope_params.get("partial_rotary_factor", 1.0)
|
||||
head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
|
||||
dim = int(head_dim * partial_rotary_factor)
|
||||
inv_freq = 1.0 / (
|
||||
base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
|
||||
)
|
||||
return inv_freq, 1.0
|
||||
|
||||
@torch.no_grad()
|
||||
@dynamic_rope_update
|
||||
def forward(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
position_ids: torch.LongTensor,
|
||||
layer_type: str,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
inv_freq = getattr(self, f"{layer_type}_inv_freq")
|
||||
attention_scaling = getattr(self, f"{layer_type}_attention_scaling")
|
||||
inv_freq_expanded = inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
|
||||
position_ids_expanded = position_ids[:, None, :].float()
|
||||
|
||||
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
|
||||
with maybe_autocast(device_type=device_type, enabled=False):
|
||||
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
||||
emb = torch.cat((freqs, freqs), dim=-1)
|
||||
cos = emb.cos() * attention_scaling
|
||||
sin = emb.sin() * attention_scaling
|
||||
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
||||
|
||||
|
||||
def _laguna_attention_config(config: LagunaConfig, num_heads: int) -> AttentionConfig:
|
||||
return AttentionConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
head_dim=config.head_dim,
|
||||
num_attention_heads=num_heads,
|
||||
num_key_value_heads=config.num_key_value_heads,
|
||||
is_causal=True,
|
||||
attention_bias=config.attention_bias,
|
||||
use_qk_norm=True,
|
||||
rms_norm_eps=config.rms_norm_eps,
|
||||
qk_norm_type="per_head",
|
||||
)
|
||||
|
||||
|
||||
class LagunaFlashAttention(FlashAttention):
|
||||
def __init__(self, config: LagunaConfig, layer_idx: int, num_heads: int, flash_attn_version: int = 2):
|
||||
super().__init__(_laguna_attention_config(config, num_heads), flash_attn_version=flash_attn_version)
|
||||
self.num_heads = num_heads
|
||||
self.config = config
|
||||
self.layer_idx = layer_idx
|
||||
self.attention_dropout = config.attention_dropout
|
||||
self.is_local_attention = config.layer_types[layer_idx] == "sliding_attention"
|
||||
self.sliding_window = config.sliding_window if self.is_local_attention else None
|
||||
self.g_proj = nn.Linear(config.hidden_size, num_heads, bias=False)
|
||||
self.o_proj = nn.Linear(num_heads * self.head_dim, config.hidden_size, bias=config.attention_bias)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
query_states, key_states, value_states = self.attn_projections(hidden_states, position_embeddings)
|
||||
attn_output = self._attention_core(
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
)
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
attn_output = attn_output.view(*input_shape, self.num_heads, self.head_dim)
|
||||
gate = F.softplus(self.g_proj(hidden_states).float()).to(attn_output.dtype)
|
||||
attn_output = (attn_output * gate.unsqueeze(-1)).view(*input_shape, -1)
|
||||
return self.o_proj(attn_output), None
|
||||
|
||||
|
||||
class LagunaSDPAAttention(SDPAAttention):
|
||||
def __init__(self, config: LagunaConfig, layer_idx: int, num_heads: int):
|
||||
super().__init__(_laguna_attention_config(config, num_heads))
|
||||
self.num_heads = num_heads
|
||||
self.config = config
|
||||
self.layer_idx = layer_idx
|
||||
self.attention_dropout = config.attention_dropout
|
||||
self.is_local_attention = config.layer_types[layer_idx] == "sliding_attention"
|
||||
self.sliding_window = config.sliding_window if self.is_local_attention else None
|
||||
self.g_proj = nn.Linear(config.hidden_size, num_heads, bias=False)
|
||||
self.o_proj = nn.Linear(num_heads * self.head_dim, config.hidden_size, bias=config.attention_bias)
|
||||
|
||||
def _attention_core(
|
||||
self,
|
||||
query_states: torch.Tensor,
|
||||
key_states: torch.Tensor,
|
||||
value_states: torch.Tensor,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
key_states = key_states.repeat_interleave(self.num_key_value_groups, dim=1)
|
||||
value_states = value_states.repeat_interleave(self.num_key_value_groups, dim=1)
|
||||
dropout_p = 0.0 if not self.training else self.attention_dropout
|
||||
out = F.scaled_dot_product_attention(
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
attn_mask=attention_mask,
|
||||
dropout_p=dropout_p,
|
||||
is_causal=attention_mask is None,
|
||||
)
|
||||
out = out.transpose(1, 2).contiguous()
|
||||
return out.view(out.shape[0], out.shape[1], -1)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
query_states, key_states, value_states = self.attn_projections(hidden_states, position_embeddings)
|
||||
attn_output = self._attention_core(query_states, key_states, value_states, attention_mask=attention_mask)
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
attn_output = attn_output.view(*input_shape, self.num_heads, self.head_dim)
|
||||
gate = F.softplus(self.g_proj(hidden_states).float()).to(attn_output.dtype)
|
||||
attn_output = (attn_output * gate.unsqueeze(-1)).view(*input_shape, -1)
|
||||
return self.o_proj(attn_output), None
|
||||
|
||||
|
||||
def _get_laguna_attention(config: LagunaConfig, layer_idx: int):
|
||||
attn_impl = config._attn_implementation
|
||||
if attn_impl == "eager":
|
||||
attn_impl = "sdpa"
|
||||
num_heads = config.num_attention_heads_per_layer[layer_idx]
|
||||
match attn_impl:
|
||||
case "flash_attention_2":
|
||||
return LagunaFlashAttention(config, layer_idx, num_heads, flash_attn_version=2)
|
||||
case "flash_attention_3":
|
||||
return LagunaFlashAttention(config, layer_idx, num_heads, flash_attn_version=3)
|
||||
case "fa4":
|
||||
return LagunaFlashAttention(config, layer_idx, num_heads, flash_attn_version=4)
|
||||
case "sdpa":
|
||||
return LagunaSDPAAttention(config, layer_idx, num_heads)
|
||||
case _:
|
||||
raise ValueError(f"Laguna attention does not support '{config._attn_implementation}'.")
|
||||
|
||||
|
||||
class LagunaDecoderLayer(GradientCheckpointingLayer):
|
||||
def __init__(self, config: LagunaConfig, layer_idx: int):
|
||||
super().__init__()
|
||||
self.hidden_size = config.hidden_size
|
||||
self.layer_type = config.layer_types[layer_idx]
|
||||
self.mlp_layer_type = config.mlp_layer_types[layer_idx]
|
||||
self.self_attn = _get_laguna_attention(config, layer_idx)
|
||||
|
||||
if self.mlp_layer_type == "sparse":
|
||||
moe_args = MoEArgs(
|
||||
num_experts=config.num_experts,
|
||||
num_shared_experts=0,
|
||||
score_func="sigmoid",
|
||||
route_norm=True,
|
||||
route_scale=config.moe_routed_scaling_factor,
|
||||
score_before_experts=False,
|
||||
top_k=config.num_experts_per_tok,
|
||||
use_grouped_mm=config.use_grouped_mm,
|
||||
load_balance_coeff=config.load_balance_coeff,
|
||||
fp8=getattr(config, "fp8", False),
|
||||
)
|
||||
if config.moe_router_logit_softcapping:
|
||||
raise NotImplementedError("Laguna router logit softcapping is not supported by PrimeRL MoE yet.")
|
||||
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
|
||||
self.shared_expert = FeedForward(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.shared_expert_intermediate_size,
|
||||
)
|
||||
else:
|
||||
mlp_config = MLPConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
intermediate_size=config.intermediate_size,
|
||||
gate_act=config.hidden_act,
|
||||
bias=False,
|
||||
)
|
||||
self.mlp = MLP(mlp_config)
|
||||
self.shared_expert = None
|
||||
|
||||
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
routed_experts: Optional[torch.LongTensor] = None,
|
||||
) -> torch.Tensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.input_layernorm(hidden_states)
|
||||
hidden_states, _ = self.self_attn(
|
||||
hidden_states=hidden_states,
|
||||
attention_mask=attention_mask,
|
||||
position_embeddings=position_embeddings,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
)
|
||||
hidden_states = residual + hidden_states
|
||||
|
||||
residual = hidden_states
|
||||
mlp_input = self.post_attention_layernorm(hidden_states)
|
||||
hidden_states = self.mlp(mlp_input, routed_experts=routed_experts)
|
||||
if self.shared_expert is not None:
|
||||
bs, slen, dim = hidden_states.shape
|
||||
shared_output = self.shared_expert(mlp_input.view(-1, dim)).view(bs, slen, dim)
|
||||
hidden_states = hidden_states + shared_output
|
||||
hidden_states = residual + hidden_states
|
||||
return hidden_states
|
||||
|
||||
|
||||
class LagunaPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
config: LagunaConfig
|
||||
config_class = LagunaConfig
|
||||
base_model_prefix = "model"
|
||||
supports_gradient_checkpointing = True
|
||||
_no_split_modules = ["LagunaDecoderLayer"]
|
||||
_skip_keys_device_placement = ["past_key_values"]
|
||||
_supports_flash_attn = True
|
||||
_supports_sdpa = True
|
||||
_supports_flex_attn = False
|
||||
_can_compile_fullgraph = False
|
||||
_supports_attention_backend = True
|
||||
_can_record_outputs = {
|
||||
"hidden_states": LagunaDecoderLayer,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return any(
|
||||
"mlp.experts.0.gate_proj.weight" in name or "mlp.experts.gate_up_proj" in name or "mlp.gate.weight" in name
|
||||
for name in state_dict
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return any("mlp.experts.w1" in name for name in state_dict)
|
||||
|
||||
@classmethod
|
||||
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
convert_prime_to_hf(state_dict)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_to_prime(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
convert_hf_to_prime(state_dict)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_hf(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
convert_prime_layer_to_hf(state_dict, layer_idx)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_prime(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
convert_hf_layer_to_prime(state_dict, layer_idx)
|
||||
return state_dict
|
||||
|
||||
|
||||
class LagunaModel(LagunaPreTrainedModel):
|
||||
def __init__(self, config: LagunaConfig):
|
||||
super().__init__(config)
|
||||
self.padding_idx = config.pad_token_id
|
||||
self.vocab_size = config.vocab_size
|
||||
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
||||
self.layers = nn.ModuleList([LagunaDecoderLayer(config, idx) for idx in range(config.num_hidden_layers)])
|
||||
self.norm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
self.rotary_emb = LagunaRotaryEmbedding(config=config)
|
||||
self.gradient_checkpointing = False
|
||||
self.post_init()
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.LongTensor | None = None,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
position_ids: torch.LongTensor | None = None,
|
||||
inputs_embeds: torch.FloatTensor | None = None,
|
||||
routed_experts: torch.LongTensor | None = None,
|
||||
) -> MoeModelOutputWithPast:
|
||||
if (input_ids is None) ^ (inputs_embeds is not None):
|
||||
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
||||
|
||||
if inputs_embeds is None:
|
||||
inputs_embeds = self.embed_tokens(input_ids)
|
||||
if position_ids is None:
|
||||
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
||||
|
||||
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
causal_mask_mapping = dict.fromkeys(set(self.config.layer_types), None)
|
||||
else:
|
||||
cu_seqlens = None
|
||||
max_seqlen = None
|
||||
if isinstance(attention_mask, dict):
|
||||
causal_mask_mapping = attention_mask
|
||||
else:
|
||||
mask_kwargs = {
|
||||
"config": self.config,
|
||||
"inputs_embeds": inputs_embeds,
|
||||
"attention_mask": attention_mask,
|
||||
"past_key_values": None,
|
||||
"position_ids": position_ids,
|
||||
}
|
||||
causal_mask_mapping = {
|
||||
"full_attention": create_causal_mask(**mask_kwargs),
|
||||
"sliding_attention": create_sliding_window_causal_mask(**mask_kwargs),
|
||||
}
|
||||
|
||||
hidden_states = inputs_embeds
|
||||
position_embeddings = {
|
||||
layer_type: self.rotary_emb(hidden_states, position_ids, layer_type)
|
||||
for layer_type in set(self.config.layer_types)
|
||||
}
|
||||
|
||||
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
|
||||
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
attention_mask=causal_mask_mapping[self.config.layer_types[layer_idx]],
|
||||
position_embeddings=position_embeddings[self.config.layer_types[layer_idx]],
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
routed_experts=routed_experts_layer,
|
||||
)
|
||||
|
||||
hidden_states = self.norm(hidden_states)
|
||||
return MoeModelOutputWithPast(last_hidden_state=hidden_states)
|
||||
|
||||
|
||||
class LagunaForCausalLM(LagunaPreTrainedModel, GenerationMixin):
|
||||
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
||||
_tp_plan = {"lm_head": "colwise_gather_output"}
|
||||
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
||||
|
||||
def __init__(self, config: LagunaConfig):
|
||||
super().__init__(config)
|
||||
self.model = LagunaModel(config)
|
||||
self.vocab_size = config.vocab_size
|
||||
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
||||
self.router_aux_loss_coef = config.router_aux_loss_coef
|
||||
self.num_experts = config.num_experts
|
||||
self.num_experts_per_tok = config.num_experts_per_tok
|
||||
self.post_init()
|
||||
|
||||
def set_decoder(self, decoder):
|
||||
self.model = decoder
|
||||
|
||||
def get_decoder(self):
|
||||
return self.model
|
||||
|
||||
@can_return_tuple
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.LongTensor | None = None,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
position_ids: torch.LongTensor | None = None,
|
||||
past_key_values: Cache | None = None,
|
||||
inputs_embeds: torch.FloatTensor | None = None,
|
||||
labels: torch.LongTensor | None = None,
|
||||
use_cache: bool | None = None,
|
||||
output_router_logits: bool | None = None,
|
||||
cache_position: torch.LongTensor | None = None,
|
||||
logits_to_keep: Union[int, torch.Tensor] = 0,
|
||||
temperature: torch.Tensor | None = None,
|
||||
routed_experts: torch.LongTensor | None = None,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> PrimeLmOutput:
|
||||
assert use_cache is None, "use_cache is not supported for custom Laguna"
|
||||
assert past_key_values is None, "past_key_values is not supported for custom Laguna"
|
||||
|
||||
outputs = self.model(
|
||||
input_ids=input_ids,
|
||||
attention_mask=attention_mask,
|
||||
position_ids=position_ids,
|
||||
inputs_embeds=inputs_embeds,
|
||||
routed_experts=routed_experts,
|
||||
)
|
||||
hidden_states = outputs.last_hidden_state
|
||||
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
||||
return self.lm_head(
|
||||
hidden_states[:, slice_indices, :],
|
||||
labels[:, slice_indices] if labels is not None else None,
|
||||
temperature=temperature,
|
||||
)
|
||||
|
||||
def init_buffers_post_meta(self) -> None:
|
||||
rotary_emb = self.model.rotary_emb
|
||||
for layer_type in rotary_emb.layer_types:
|
||||
rope_init_fn = rotary_emb.compute_default_rope_parameters
|
||||
if rotary_emb.rope_type[layer_type] != "default":
|
||||
rope_init_fn = ROPE_INIT_FUNCTIONS[rotary_emb.rope_type[layer_type]]
|
||||
inv_freq, attention_scaling = rope_init_fn(
|
||||
rotary_emb.config,
|
||||
getattr(rotary_emb, f"{layer_type}_inv_freq").device,
|
||||
layer_type=layer_type,
|
||||
)
|
||||
getattr(rotary_emb, f"{layer_type}_inv_freq").copy_(inv_freq)
|
||||
getattr(rotary_emb, f"{layer_type}_original_inv_freq").copy_(inv_freq)
|
||||
setattr(rotary_emb, f"{layer_type}_attention_scaling", attention_scaling)
|
||||
|
||||
for module in self.modules():
|
||||
if isinstance(module, MoE) and module.tokens_per_expert.device.type != "meta":
|
||||
module.tokens_per_expert.zero_()
|
||||
if module.expert_bias is not None:
|
||||
module.expert_bias.zero_()
|
||||
|
||||
|
||||
__all__ = [
|
||||
"LagunaForCausalLM",
|
||||
"LagunaModel",
|
||||
"LagunaPreTrainedModel",
|
||||
]
|
||||
@@ -127,11 +127,14 @@ def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossO
|
||||
probs_diff = trainer_probs - inference_probs
|
||||
dppo_invalid_mask_high = probs_diff > loss_config.dppo_mask_high
|
||||
dppo_invalid_mask_low = probs_diff < -loss_config.dppo_mask_low
|
||||
dppo_invalid_mask = torch.where(advantages > 0, dppo_invalid_mask_high, dppo_invalid_mask_low)
|
||||
positive_advantages = advantages > 0
|
||||
negative_advantages = advantages < 0
|
||||
dppo_invalid_mask = torch.where(positive_advantages, dppo_invalid_mask_high, dppo_invalid_mask_low)
|
||||
|
||||
is_masked = dppo_invalid_mask
|
||||
is_masked_high = (advantages > 0) & dppo_invalid_mask_high
|
||||
is_masked_low = (advantages < 0) & dppo_invalid_mask_low
|
||||
is_masked_high = positive_advantages & dppo_invalid_mask_high
|
||||
is_masked_low = negative_advantages & dppo_invalid_mask_low
|
||||
drop_mask = loss_mask & is_masked
|
||||
keep_mask = loss_mask & ~is_masked
|
||||
|
||||
log_importance_ratio = trainer_logprobs - inference_logprobs
|
||||
@@ -156,6 +159,8 @@ def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossO
|
||||
"is_masked": _safe_mean(is_masked, loss_mask),
|
||||
"is_masked_low": _safe_mean(is_masked_low, loss_mask),
|
||||
"is_masked_high": _safe_mean(is_masked_high, loss_mask),
|
||||
"masked_advantage_positive": _safe_mean(positive_advantages, drop_mask),
|
||||
"masked_advantage_negative": _safe_mean(negative_advantages, drop_mask),
|
||||
}
|
||||
if teacher_kl is not None:
|
||||
metrics["teacher_kl"] = _safe_mean(teacher_kl, loss_mask)
|
||||
|
||||
@@ -6,6 +6,7 @@ from typing import Literal, TypedDict, cast
|
||||
import torch
|
||||
from datasets import Dataset, interleave_datasets, load_dataset
|
||||
from jaxtyping import Bool, Int
|
||||
from renderers.base import Renderer, build_training_sample
|
||||
from torch import Tensor
|
||||
from torch.distributed.checkpoint.stateful import Stateful
|
||||
from torch.utils.data import IterableDataset, get_worker_info
|
||||
@@ -127,6 +128,7 @@ class SFTDataset(StatefulIterableDataset):
|
||||
loss_mask_config: LossMaskConfig = LossMaskConfig(),
|
||||
max_examples: int | None = None,
|
||||
max_epochs: int | None = None,
|
||||
renderer: Renderer | None = None,
|
||||
):
|
||||
super().__init__()
|
||||
self.logger = get_logger()
|
||||
@@ -139,6 +141,8 @@ class SFTDataset(StatefulIterableDataset):
|
||||
self.loss_mask_config = loss_mask_config
|
||||
self.max_examples = max_examples
|
||||
self.max_epochs = max_epochs
|
||||
self.renderer = renderer
|
||||
self._warned_chat_template_kwargs = False
|
||||
|
||||
if self.tokenizer is None:
|
||||
self.logger.warning("No tokenizer provided, will not process examples")
|
||||
@@ -190,7 +194,30 @@ class SFTDataset(StatefulIterableDataset):
|
||||
|
||||
# Parse available tools, if present - assumes OAI format
|
||||
# Reference: https://platform.openai.com/docs/guides/function-calling#function-tool-example
|
||||
tools = json.loads(example.get("tools") or "[]")
|
||||
# Accepts either `tools` or `tool_defs` (the verifiers rollout format),
|
||||
# as either a JSON-encoded string of a list or a list of dicts. Tools
|
||||
# arriving in the verifiers shape are converted to OAI form so any
|
||||
# downstream chat template can consume them.
|
||||
raw_tools = example.get("tools", example.get("tool_defs"))
|
||||
if not raw_tools:
|
||||
tools = []
|
||||
else:
|
||||
if isinstance(raw_tools, str):
|
||||
raw_tools = json.loads(raw_tools)
|
||||
tools = [
|
||||
t
|
||||
if isinstance(t, dict) and t.get("type") == "function" and "function" in t
|
||||
else {
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": t.get("name"),
|
||||
"description": t.get("description"),
|
||||
"parameters": t.get("parameters"),
|
||||
**({} if t.get("strict") is None else {"strict": t["strict"]}),
|
||||
},
|
||||
}
|
||||
for t in raw_tools
|
||||
]
|
||||
|
||||
def should_mask(message: dict) -> bool:
|
||||
assert "role" in message, "Message must have a role"
|
||||
@@ -206,18 +233,35 @@ class SFTDataset(StatefulIterableDataset):
|
||||
case _:
|
||||
raise ValueError(f"Invalid message role: {message['role']}")
|
||||
|
||||
try:
|
||||
input_ids, loss_mask = build_incremental_token_mask(
|
||||
self.tokenizer,
|
||||
if self.renderer is not None:
|
||||
if example.get("chat_template_kwargs") and not self._warned_chat_template_kwargs:
|
||||
self.logger.warning(
|
||||
"Example carries chat_template_kwargs but use_renderer=True; "
|
||||
"renderers don't forward chat_template_kwargs (model-specific "
|
||||
"renderers bake their template behavior in). These kwargs will "
|
||||
"be ignored. Further warnings suppressed for this dataset."
|
||||
)
|
||||
self._warned_chat_template_kwargs = True
|
||||
|
||||
input_ids, loss_mask = build_training_sample(
|
||||
self.renderer,
|
||||
messages,
|
||||
role_to_mask=should_mask,
|
||||
tools=tools,
|
||||
chat_template_kwargs=example.get("chat_template_kwargs", {}),
|
||||
collapse_consecutive_tool_messages=True,
|
||||
)
|
||||
except IncrementalTokenizationError as e:
|
||||
self.logger.warning(f"Skipping example {example.get('__index', '')}: {e}")
|
||||
return None
|
||||
else:
|
||||
try:
|
||||
input_ids, loss_mask = build_incremental_token_mask(
|
||||
self.tokenizer,
|
||||
messages,
|
||||
role_to_mask=should_mask,
|
||||
tools=tools,
|
||||
chat_template_kwargs=example.get("chat_template_kwargs", {}),
|
||||
collapse_consecutive_tool_messages=True,
|
||||
)
|
||||
except IncrementalTokenizationError as e:
|
||||
self.logger.warning(f"Skipping example {example.get('__index', '')}: {e}")
|
||||
return None
|
||||
|
||||
# If EOS token is not found, manually append it
|
||||
if not self.tokenizer.eos_token_id in input_ids:
|
||||
@@ -537,6 +581,7 @@ def setup_dataset(
|
||||
*,
|
||||
max_epochs: int | None = None,
|
||||
raw_dataset: Dataset | None = None,
|
||||
renderer: Renderer | None = None,
|
||||
) -> StatefulIterableDataset:
|
||||
if config.type == "fake":
|
||||
return FakeDataset(
|
||||
@@ -554,6 +599,7 @@ def setup_dataset(
|
||||
loss_mask_config=config.loss_mask,
|
||||
non_dp_size=non_dp_size,
|
||||
max_epochs=max_epochs,
|
||||
renderer=renderer,
|
||||
)
|
||||
else:
|
||||
raise ValueError(f"Invalid dataset type: {config.type}")
|
||||
|
||||
@@ -4,6 +4,8 @@ import time
|
||||
from contextlib import nullcontext
|
||||
from datetime import timedelta
|
||||
|
||||
from renderers.base import create_renderer
|
||||
from renderers.default import DefaultRenderer
|
||||
from ring_flash_attn import substitute_hf_flash_attn
|
||||
from torch.nn import CrossEntropyLoss
|
||||
|
||||
@@ -157,6 +159,24 @@ def train(config: SFTConfig):
|
||||
logger.info(f"Initializing tokenizer ({config.tokenizer})")
|
||||
tokenizer = setup_tokenizer(config.tokenizer)
|
||||
|
||||
renderer = None
|
||||
if config.use_renderer:
|
||||
renderer = create_renderer(
|
||||
tokenizer,
|
||||
renderer=config.renderer.name,
|
||||
tool_parser=config.renderer.tool_parser,
|
||||
reasoning_parser=config.renderer.reasoning_parser,
|
||||
)
|
||||
if isinstance(renderer, DefaultRenderer):
|
||||
raise ValueError(
|
||||
f"use_renderer=True for {config.tokenizer.name!r} resolved to DefaultRenderer. "
|
||||
"DefaultRenderer falls back to incremental apply_chat_template and does NOT "
|
||||
"fix position-dependent chat templates — the bug use_renderer is meant to solve. "
|
||||
"Either use a model with a hand-coded renderer (see renderers.base.MODEL_RENDERER_MAP), "
|
||||
"set [renderer] name=<hand-coded renderer> explicitly, or set use_renderer=false."
|
||||
)
|
||||
logger.info(f"Initialized {type(renderer).__name__} for {config.tokenizer.name}")
|
||||
|
||||
# Set up the optimizer
|
||||
logger.info(f"Initializing optimizer ({config.optim})")
|
||||
optimizer = setup_optimizer(
|
||||
@@ -175,7 +195,7 @@ def train(config: SFTConfig):
|
||||
|
||||
# Set up the dataset and dataloader
|
||||
logger.info(f"Initializing data ({config.data})")
|
||||
dataset = setup_dataset(tokenizer, config.data, config.model.cp)
|
||||
dataset = setup_dataset(tokenizer, config.data, config.model.cp, renderer=renderer)
|
||||
dataloader = setup_dataloader(dataset, config.data)
|
||||
dataiter = iter(dataloader)
|
||||
|
||||
@@ -283,7 +303,12 @@ def train(config: SFTConfig):
|
||||
|
||||
def run_validation(step: int) -> None:
|
||||
val_dataset = setup_dataset(
|
||||
tokenizer, config.val.data, config.model.cp, max_epochs=1, raw_dataset=val_raw_dataset
|
||||
tokenizer,
|
||||
config.val.data,
|
||||
config.model.cp,
|
||||
max_epochs=1,
|
||||
raw_dataset=val_raw_dataset,
|
||||
renderer=renderer,
|
||||
)
|
||||
val_dataloader = setup_dataloader(val_dataset, config.val.data)
|
||||
|
||||
|
||||
@@ -389,6 +389,8 @@ def filter_rl_trainer_tensor_stats_for_wandb(metrics: dict[str, float | int]) ->
|
||||
"is_masked/",
|
||||
"is_masked_low/",
|
||||
"is_masked_high/",
|
||||
"masked_advantage_positive/",
|
||||
"masked_advantage_negative/",
|
||||
"mismatch_kl/",
|
||||
"masked_mismatch_kl/",
|
||||
"unmasked_mismatch_kl/",
|
||||
|
||||
@@ -47,7 +47,10 @@ class WandbMonitor(Monitor):
|
||||
self.logger.info(f"Initializing {self.__class__.__name__} ({config})")
|
||||
self._maybe_overwrite_wandb_command()
|
||||
|
||||
shared_mode = os.environ.get("WANDB_SHARED_MODE") == "1"
|
||||
# WANDB_MODE=disabled/offline takes precedence over shared mode — shared mode
|
||||
# requires a server connection and can't work offline.
|
||||
_wandb_mode = os.environ.get("WANDB_MODE")
|
||||
shared_mode = os.environ.get("WANDB_SHARED_MODE") == "1" and _wandb_mode not in ("disabled", "offline")
|
||||
if shared_mode:
|
||||
run_id = os.environ.get("WANDB_SHARED_RUN_ID")
|
||||
label = os.environ.get("WANDB_SHARED_LABEL")
|
||||
@@ -65,9 +68,8 @@ class WandbMonitor(Monitor):
|
||||
else:
|
||||
run_id = None
|
||||
primary = False
|
||||
settings = wandb.Settings(
|
||||
mode="offline" if config.offline else "online",
|
||||
)
|
||||
mode = os.environ.get("WANDB_MODE", "offline" if config.offline else "online")
|
||||
settings = wandb.Settings(mode=mode)
|
||||
|
||||
def init_wandb(max_retries: int):
|
||||
for attempt in range(max_retries):
|
||||
|
||||
@@ -4,7 +4,13 @@ from typing import Callable
|
||||
import pytest
|
||||
|
||||
from tests.conftest import ProcessResult
|
||||
from tests.utils import check_no_error, check_reward_goes_up, check_reward_in_range, strip_escape_codes
|
||||
from tests.utils import (
|
||||
check_avg_mismatch_kl_in_range,
|
||||
check_no_error,
|
||||
check_reward_goes_up,
|
||||
check_reward_in_range,
|
||||
strip_escape_codes,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
@@ -12,23 +18,16 @@ pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
TIMEOUT = 900 # 15 minutes
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def rl_output_dir(output_dir: Path) -> Path:
|
||||
rl_dir = output_dir / "alphabet_sort_start"
|
||||
rl_dir.mkdir(parents=True, exist_ok=True)
|
||||
return rl_dir
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
"""Fixture for W&B name for alphabet sort RL CI integration tests."""
|
||||
return f"test-alphabet-sort-{branch_name}"
|
||||
return f"test-alphabet-sort:{branch_name}"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def rl_process(
|
||||
run_process: Callable[..., ProcessResult],
|
||||
rl_output_dir: Path,
|
||||
output_dir: Path,
|
||||
wandb_project: str,
|
||||
wandb_name: str,
|
||||
) -> ProcessResult:
|
||||
@@ -37,32 +36,39 @@ def rl_process(
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/alphabet_sort/start.toml",
|
||||
"configs/ci/integration/alphabet_sort.toml",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
rl_output_dir.as_posix(),
|
||||
output_dir.as_posix(),
|
||||
]
|
||||
return run_process(cmd, timeout=TIMEOUT)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error(rl_process: ProcessResult, rl_output_dir: Path):
|
||||
def test_no_error(rl_process: ProcessResult, output_dir: Path):
|
||||
"""Tests that the RL process does not fail."""
|
||||
check_no_error(rl_process, rl_output_dir)
|
||||
check_no_error(rl_process, output_dir)
|
||||
|
||||
|
||||
def test_reward_goes_up(rl_process: ProcessResult, test_no_error, rl_output_dir: Path):
|
||||
def test_reward_goes_up(rl_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
"""Tests that the reward goes up in the RL process."""
|
||||
with open(rl_output_dir / "logs" / "orchestrator.log", "r") as f:
|
||||
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_goes_up(orchestrator_stdout)
|
||||
|
||||
|
||||
def test_reward_in_range(rl_process: ProcessResult, test_no_error, rl_output_dir: Path):
|
||||
def test_reward_in_range(rl_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
"""Tests that the reward is in range in the RL process."""
|
||||
with open(rl_output_dir / "logs" / "orchestrator.log", "r") as f:
|
||||
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_in_range(orchestrator_stdout, min_threshold=0.05)
|
||||
check_reward_in_range(orchestrator_stdout, min_threshold=0.10)
|
||||
|
||||
|
||||
def test_mismatch_kl_in_range(rl_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
"""Tests that the average mismatch KL is below 0.15 across the last 5 steps."""
|
||||
with open(output_dir / "logs" / "trainer.log", "r") as f:
|
||||
trainer_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_avg_mismatch_kl_in_range(trainer_stdout, last_n_steps=5, max_threshold=0.15)
|
||||
|
||||
@@ -4,7 +4,13 @@ from typing import Callable
|
||||
import pytest
|
||||
|
||||
from tests.conftest import ProcessResult
|
||||
from tests.utils import check_no_error, check_reward_goes_up, check_reward_in_range, strip_escape_codes
|
||||
from tests.utils import (
|
||||
check_avg_mismatch_kl_in_range,
|
||||
check_no_error,
|
||||
check_reward_goes_up,
|
||||
check_reward_in_range,
|
||||
strip_escape_codes,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
@@ -15,7 +21,7 @@ TIMEOUT = 600 # 10 minutes
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
"""Fixture for W&B name for RL CI integration tests."""
|
||||
return f"test-rl-{branch_name}"
|
||||
return f"test-reverse-text:{branch_name}"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
@@ -30,7 +36,7 @@ def rl_process(
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/rl/start.toml",
|
||||
"configs/ci/integration/reverse_text/start.toml",
|
||||
"--clean-output-dir",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
@@ -58,7 +64,7 @@ def rl_resume_process(
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/rl/resume.toml",
|
||||
"configs/ci/integration/reverse_text/resume.toml",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
@@ -90,6 +96,13 @@ def test_reward_in_range(rl_process: ProcessResult, test_no_error, output_dir: P
|
||||
check_reward_in_range(orchestrator_stdout, min_threshold=0.65)
|
||||
|
||||
|
||||
def test_mismatch_kl_in_range(rl_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
"""Tests that the average mismatch KL is below 0.01 across all steps"""
|
||||
with open(output_dir / "logs" / "trainer.log", "r") as f:
|
||||
trainer_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_avg_mismatch_kl_in_range(trainer_stdout, last_n_steps=3, max_threshold=0.01)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error_resume(rl_resume_process: ProcessResult, output_dir: Path):
|
||||
"""Tests that the RL resume process does not fail."""
|
||||
@@ -15,7 +15,7 @@ TIMEOUT = 600 # 10 minutes
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
"""Fixture for W&B name for RL CI integration tests."""
|
||||
return f"test-rl-lora-{branch_name}"
|
||||
return f"test-reverse-text-lora:{branch_name}"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
@@ -30,7 +30,7 @@ def rl_process(
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/rl_lora/start.toml",
|
||||
"configs/ci/integration/reverse_text_lora/start.toml",
|
||||
"--clean-output-dir",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
@@ -58,7 +58,7 @@ def rl_resume_process(
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/rl_lora/resume.toml",
|
||||
"configs/ci/integration/reverse_text_lora/resume.toml",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
@@ -0,0 +1,50 @@
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import ProcessResult
|
||||
from tests.utils import check_no_error
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
TIMEOUT = 900 # 15 minutes
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
return f"test-reverse-text-moe:{branch_name}"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def rl_process(
|
||||
run_process: Callable[..., ProcessResult],
|
||||
wandb_project: str,
|
||||
wandb_name: str,
|
||||
output_dir: Path,
|
||||
) -> ProcessResult:
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/reverse_text_moe/start.toml",
|
||||
"--trainer.model.impl",
|
||||
"custom",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
f"{wandb_name}-custom",
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
]
|
||||
return run_process(cmd, timeout=TIMEOUT)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error(rl_process: ProcessResult, output_dir: Path):
|
||||
check_no_error(rl_process, output_dir)
|
||||
|
||||
|
||||
def test_moe_runs(rl_process: ProcessResult, test_no_error):
|
||||
"""MoE RL with custom model impl completes without error."""
|
||||
+4
-4
@@ -88,7 +88,7 @@ def wait_for_log(
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
"""Fixture for W&B name for multi-run RL CI integration tests."""
|
||||
return f"test-rl-multi-run-{branch_name}"
|
||||
return f"test-reverse-text-multi-run:{branch_name}"
|
||||
|
||||
|
||||
INFERENCE_PORTS = [8000, 8001]
|
||||
@@ -111,7 +111,7 @@ def start_inference_and_trainer(
|
||||
"run",
|
||||
"inference",
|
||||
"@",
|
||||
"configs/ci/integration/rl_multi_run/inference.toml",
|
||||
"configs/ci/integration/reverse_text_multi_run/inference.toml",
|
||||
"--server.port",
|
||||
str(port),
|
||||
],
|
||||
@@ -134,7 +134,7 @@ def start_inference_and_trainer(
|
||||
"-m",
|
||||
"prime_rl.trainer.rl.train",
|
||||
"@",
|
||||
"configs/ci/integration/rl_multi_run/trainer.toml",
|
||||
"configs/ci/integration/reverse_text_multi_run/trainer.toml",
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
"--wandb.project",
|
||||
@@ -200,7 +200,7 @@ def start_orchestrator(
|
||||
"run",
|
||||
"orchestrator",
|
||||
"@",
|
||||
"configs/ci/integration/rl_multi_run/orchestrator.toml",
|
||||
"configs/ci/integration/reverse_text_multi_run/orchestrator.toml",
|
||||
"--output-dir",
|
||||
run_dir.as_posix(),
|
||||
"--max-steps",
|
||||
@@ -14,7 +14,7 @@ TIMEOUT = 300 # 5 minutes
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
"""Fixture for W&B name for SFT CI integration tests."""
|
||||
return f"test-sft-{branch_name}"
|
||||
return f"test-reverse-text-sft:{branch_name}"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
@@ -30,7 +30,7 @@ def sft_process(
|
||||
"run",
|
||||
"sft",
|
||||
"@",
|
||||
"configs/ci/integration/sft/start.toml",
|
||||
"configs/ci/integration/reverse_text_sft/start.toml",
|
||||
"--deployment.num-gpus",
|
||||
"2",
|
||||
"--clean-output-dir",
|
||||
@@ -60,7 +60,7 @@ def sft_resume_process(
|
||||
"run",
|
||||
"sft",
|
||||
"@",
|
||||
"configs/ci/integration/sft/resume.toml",
|
||||
"configs/ci/integration/reverse_text_sft/resume.toml",
|
||||
"--deployment.num-gpus",
|
||||
"2",
|
||||
"--wandb.project",
|
||||
+5
-5
@@ -24,7 +24,7 @@ def assert_adapter_checkpoint(adapter_dir: Path) -> None:
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
"""Fixture for W&B name for SFT LoRA CI integration tests."""
|
||||
return f"test-sft-lora-{branch_name}"
|
||||
return f"test-reverse-text-sft-lora:{branch_name}"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
@@ -40,7 +40,7 @@ def sft_lora_process(
|
||||
"run",
|
||||
"sft",
|
||||
"@",
|
||||
"configs/ci/integration/sft_lora/start.toml",
|
||||
"configs/ci/integration/reverse_text_sft_lora/start.toml",
|
||||
"--deployment.num-gpus",
|
||||
"2",
|
||||
"--clean-output-dir",
|
||||
@@ -70,7 +70,7 @@ def sft_lora_resume_process(
|
||||
"run",
|
||||
"sft",
|
||||
"@",
|
||||
"configs/ci/integration/sft_lora/resume.toml",
|
||||
"configs/ci/integration/reverse_text_sft_lora/resume.toml",
|
||||
"--deployment.num-gpus",
|
||||
"2",
|
||||
"--wandb.project",
|
||||
@@ -100,7 +100,7 @@ def test_loss_goes_down(sft_lora_process: ProcessResult, output_dir: Path):
|
||||
|
||||
def test_adapter_checkpoint_written(sft_lora_process: ProcessResult, output_dir: Path):
|
||||
"""Tests that the adapter checkpoint is written with valid PEFT-compatible keys."""
|
||||
adapter_dir = output_dir / "weights" / "step_10" / "lora_adapters"
|
||||
adapter_dir = output_dir / "weights" / "step_5" / "lora_adapters"
|
||||
assert_adapter_checkpoint(adapter_dir)
|
||||
|
||||
|
||||
@@ -120,5 +120,5 @@ def test_loss_goes_down_resume(sft_lora_resume_process: ProcessResult, output_di
|
||||
|
||||
def test_adapter_checkpoint_written_resume(sft_lora_resume_process: ProcessResult, output_dir: Path):
|
||||
"""Tests that the adapter checkpoint is written after resuming with valid PEFT-compatible keys."""
|
||||
adapter_dir = output_dir / "weights" / "step_20" / "lora_adapters"
|
||||
adapter_dir = output_dir / "weights" / "step_10" / "lora_adapters"
|
||||
assert_adapter_checkpoint(adapter_dir)
|
||||
@@ -1,104 +0,0 @@
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import ProcessResult
|
||||
from tests.utils import check_no_error
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
TIMEOUT = 900 # 15 minutes
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
return f"test-rl-moe-{branch_name}"
|
||||
|
||||
|
||||
# --- MoE with HF impl (default) ---
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def moe_hf_output_dir(output_dir: Path) -> Path:
|
||||
d = output_dir / "rl_moe_hf"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def moe_hf_process(
|
||||
run_process: Callable[..., ProcessResult],
|
||||
moe_hf_output_dir: Path,
|
||||
wandb_project: str,
|
||||
wandb_name: str,
|
||||
) -> ProcessResult:
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/rl_moe/start.toml",
|
||||
"--trainer.model.impl",
|
||||
"hf",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
f"{wandb_name}-hf",
|
||||
"--output-dir",
|
||||
moe_hf_output_dir.as_posix(),
|
||||
]
|
||||
return run_process(cmd, timeout=TIMEOUT)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error_hf(moe_hf_process: ProcessResult, moe_hf_output_dir: Path):
|
||||
check_no_error(moe_hf_process, moe_hf_output_dir)
|
||||
|
||||
|
||||
def test_moe_hf_runs(moe_hf_process: ProcessResult, test_no_error_hf):
|
||||
"""MoE RL with HF model impl completes without error."""
|
||||
|
||||
|
||||
# --- MoE with custom impl ---
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def moe_custom_output_dir(output_dir: Path) -> Path:
|
||||
d = output_dir / "rl_moe_custom"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def moe_custom_process(
|
||||
run_process: Callable[..., ProcessResult],
|
||||
moe_custom_output_dir: Path,
|
||||
wandb_project: str,
|
||||
wandb_name: str,
|
||||
) -> ProcessResult:
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/rl_moe/start.toml",
|
||||
"--trainer.model.impl",
|
||||
"custom",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
f"{wandb_name}-custom",
|
||||
"--output-dir",
|
||||
moe_custom_output_dir.as_posix(),
|
||||
]
|
||||
return run_process(cmd, timeout=TIMEOUT)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error_custom(moe_custom_process: ProcessResult, moe_custom_output_dir: Path):
|
||||
check_no_error(moe_custom_process, moe_custom_output_dir)
|
||||
|
||||
|
||||
def test_moe_custom_runs(moe_custom_process: ProcessResult, test_no_error_custom):
|
||||
"""MoE RL with custom model impl completes without error."""
|
||||
@@ -25,8 +25,9 @@ CONFIG_CLASSES = [
|
||||
|
||||
|
||||
def get_config_files() -> list[Path]:
|
||||
"""Any TOML file inside `configs/` or `examples/`"""
|
||||
config_files = list(Path("configs").rglob("*.toml"))
|
||||
"""Any TOML file inside `configs/` or `examples/` (skips the configs/private/ submodule)."""
|
||||
private = Path("configs/private")
|
||||
config_files = [p for p in Path("configs").rglob("*.toml") if private not in p.parents]
|
||||
example_files = list(Path("examples").rglob("*.toml"))
|
||||
|
||||
return config_files + example_files
|
||||
|
||||
+35
-2
@@ -14,10 +14,10 @@ def check_no_error(process: ProcessResult, output_dir: Path) -> None:
|
||||
if process.returncode != 0:
|
||||
print("=== Inference Outputs ===")
|
||||
with open(output_dir / "logs" / "inference.log", "r") as f:
|
||||
print(*f.readlines()[-100:], sep="\n")
|
||||
print(*f.readlines()[-100:], sep="")
|
||||
print("=== Orchestrator Outputs ===")
|
||||
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
|
||||
print(*f.readlines()[-1000:], sep="\n")
|
||||
print(*f.readlines()[-1000:], sep="")
|
||||
assert process.returncode == 0, f"Process has non-zero return code ({process})"
|
||||
|
||||
|
||||
@@ -157,6 +157,39 @@ def check_avg_reward_in_range(
|
||||
)
|
||||
|
||||
|
||||
def check_avg_mismatch_kl_in_range(
|
||||
lines: list[str],
|
||||
last_n_steps: int,
|
||||
min_threshold: float | None = None,
|
||||
max_threshold: float | None = None,
|
||||
):
|
||||
"""Helper to assert that the average mismatch KL over the last N steps is within a threshold"""
|
||||
pattern = r"Mismatch KL:\s*(\d+\.\d{4})"
|
||||
step_lines = [line for line in lines if "SUCCESS" in line and "Step" in line and re.search(pattern, line)]
|
||||
assert len(step_lines) >= last_n_steps, (
|
||||
f"Not enough step lines found. Expected at least {last_n_steps}, got {len(step_lines)}"
|
||||
)
|
||||
|
||||
recent_lines = step_lines[-last_n_steps:]
|
||||
kl_values = []
|
||||
for line in recent_lines:
|
||||
match = re.search(pattern, line)
|
||||
assert match is not None, f"Could not find Mismatch KL in line: {line}"
|
||||
kl_values.append(float(match.group(1)))
|
||||
|
||||
avg_kl = sum(kl_values) / len(kl_values)
|
||||
if min_threshold is not None:
|
||||
assert avg_kl >= min_threshold, (
|
||||
f"Average mismatch KL over last {last_n_steps} steps did not reach minimum threshold. "
|
||||
f"Found avg_kl={avg_kl:.4f} < {min_threshold} (kl_values={kl_values})"
|
||||
)
|
||||
if max_threshold is not None:
|
||||
assert avg_kl <= max_threshold, (
|
||||
f"Average mismatch KL over last {last_n_steps} steps exceeded maximum threshold. "
|
||||
f"Found avg_kl={avg_kl:.4f} > {max_threshold} (kl_values={kl_values})"
|
||||
)
|
||||
|
||||
|
||||
def check_mismatch_kl_in_range(
|
||||
lines: list[str],
|
||||
step: int = -1,
|
||||
|
||||
Reference in New Issue
Block a user