Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d334ea5294 | ||
|
|
57d2b84330 | ||
|
|
4f5e06fcb6 | ||
|
|
390dfdc556 | ||
|
|
2fdffa7d3d | ||
|
|
7cbc77a27f | ||
|
|
21c072a8f9 | ||
|
|
cb43db2ad1 | ||
|
|
2c6ac2bd47 |
@@ -25,7 +25,7 @@ jobs:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync --extra flash-attn --extra envs --locked
|
||||
run: uv sync --extra flash-attn --all-packages --locked
|
||||
- name: Run tests
|
||||
env:
|
||||
USERNAME_CI: CI_RUNNER
|
||||
|
||||
@@ -36,7 +36,7 @@ jobs:
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v5
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --locked
|
||||
run: uv sync --all-extras --all-packages --locked
|
||||
- name: Run unit tests
|
||||
env:
|
||||
USERNAME_CI: CI_RUNNER
|
||||
@@ -107,7 +107,7 @@ jobs:
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v5
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --locked
|
||||
run: uv sync --all-extras --all-packages --locked
|
||||
- name: Run integration tests
|
||||
env:
|
||||
USERNAME_CI: CI_RUNNER
|
||||
|
||||
@@ -86,7 +86,7 @@ jobs:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --locked
|
||||
run: uv sync --all-extras --all-packages --locked
|
||||
- name: Run experiment
|
||||
env:
|
||||
USERNAME_CI: CI_RUNNER
|
||||
|
||||
+1
-1
@@ -111,7 +111,7 @@ RUN --mount=type=cache,target=/app/.cache/uv \
|
||||
&& \
|
||||
EXTRA_DISAGG_FLAG=""; if [ "$INCLUDE_DISAGG_EXTRAS" = "1" ]; then EXTRA_DISAGG_FLAG="--extra disagg"; fi \
|
||||
&& \
|
||||
uv sync --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra envs --extra gpt-oss --extra modelexpress $EXTRA_DISAGG_FLAG --group mamba-ssm --locked --no-dev
|
||||
uv sync --all-packages --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra gpt-oss --extra modelexpress $EXTRA_DISAGG_FLAG --group mamba-ssm --locked --no-dev
|
||||
|
||||
# Optional: build NIXL from source against the UCX 1.19 baked above. The PyPI
|
||||
# nixl wheel ships its own UCX which segfaults on prefill→decode KV transfer
|
||||
|
||||
@@ -111,6 +111,8 @@ source $HOME/.local/bin/env
|
||||
uv sync --all-extras
|
||||
```
|
||||
|
||||
> *NOTE*: Environments are opt-in uv workspace members — `uv sync --all-extras` does not install them. To train on them, install all with `uv sync --all-extras --all-packages`, or a subset with `uv sync --package prime-rl --package <env>`.
|
||||
|
||||
4.1. On aarch64 hosts: build flash-attn from source for your GPU
|
||||
|
||||
> *NOTE*: aarch64 has no prebuilt flash-attn wheel. This step compiles the CUDA extension for your local GPU (~20-30 minutes). Compute capability is auto-detected from `nvidia-smi`; override with `TORCH_CUDA_ARCH_LIST=9.0` (Hopper) / `10.0` (Blackwell) if needed.
|
||||
|
||||
@@ -5,7 +5,7 @@ seq_len = 2048
|
||||
|
||||
[slurm]
|
||||
job_name = "nemotron-4node"
|
||||
pre_run_command = "uv sync --all-extras --group mamba-ssm"
|
||||
pre_run_command = "uv sync --all-extras --all-packages --group mamba-ssm"
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
|
||||
+1
-1
@@ -179,7 +179,7 @@ The defaults already cover: fused LM head chunking (`1024`), `torch.compile` (fu
|
||||
|
||||
The `rl`, `sft`, and `inference` entrypoints all submit to SLURM when a `[slurm]` table is present — there's no separate entrypoint.
|
||||
|
||||
> **The prime-rl checkout and its `uv` venv must live on a shared filesystem** visible to every node. The generated sbatch script runs a single `uv sync --all-extras` on the batch node (not once per node), so all ranks share that one environment — a node-local venv would leave the other nodes stale.
|
||||
> **The prime-rl checkout and its `uv` venv must live on a shared filesystem** visible to every node. The generated sbatch script runs a single `uv sync --all-extras --all-packages` on the batch node (not once per node), so all ranks share that one environment — a node-local venv would leave the other nodes stale.
|
||||
|
||||
### Activation
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ You also need prime-rl cloned on your cluster into the shared filesystem.
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
uv sync --all-extras
|
||||
uv sync --all-extras --all-packages
|
||||
```
|
||||
|
||||
### Install llm-d
|
||||
|
||||
@@ -11,7 +11,7 @@ You also need to have prime-rl cloned on your cluster into the shared filesystem
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
uv sync --all-extras
|
||||
uv sync --all-extras --all-packages
|
||||
```
|
||||
|
||||
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
|
||||
|
||||
@@ -15,7 +15,7 @@ You also need to have prime-rl cloned on your cluster into the shared filesystem
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
uv sync --all-extras
|
||||
uv sync --all-extras --all-packages
|
||||
```
|
||||
|
||||
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
|
||||
|
||||
@@ -11,7 +11,7 @@ You also need to have prime-rl cloned on your cluster into the shared filesystem
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
uv sync --all-extras
|
||||
uv sync --all-extras --all-packages
|
||||
```
|
||||
|
||||
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
|
||||
|
||||
@@ -11,7 +11,7 @@ You also need to have prime-rl cloned on your cluster into the shared filesystem
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
uv sync --all-extras
|
||||
uv sync --all-extras --all-packages
|
||||
```
|
||||
|
||||
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
|
||||
|
||||
@@ -11,7 +11,7 @@ You also need to have prime-rl cloned on your cluster into the shared filesystem
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
uv sync --all-extras
|
||||
uv sync --all-extras --all-packages
|
||||
```
|
||||
|
||||
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
|
||||
|
||||
@@ -347,6 +347,14 @@ class RLConfig(BaseConfig):
|
||||
self.weight_broadcast = SharedWeightBroadcastConfig(type="filesystem")
|
||||
else:
|
||||
self.weight_broadcast = SharedWeightBroadcastConfig()
|
||||
if self.weight_broadcast.type == "nccl" and self.trainer.model.lora is not None:
|
||||
# LoRA adapters are transferred via the filesystem (loaded from disk by the inference
|
||||
# servers); NCCL broadcast only writes a STABLE marker, so LoRA over NCCL cannot transfer
|
||||
# an adapter and would hang/fail on the startup weight sync.
|
||||
raise ValueError(
|
||||
"LoRA training is not yet supported with NCCL weight broadcast. "
|
||||
"Set weight_broadcast.type = 'filesystem'."
|
||||
)
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
inference_world_size = self.inference.parallel.dp * self.inference.parallel.tp if self.inference else 1
|
||||
self.trainer.weight_broadcast = TrainerNCCLWeightBroadcastConfig(
|
||||
|
||||
@@ -117,6 +117,9 @@ class DebugModelConfig(BaseConfig):
|
||||
|
||||
|
||||
class ModelConfig(BaseModelConfig):
|
||||
conversion_dir: Path | None = None
|
||||
"""Directory for the auto-converted weights (written to a `prime`/`hf` subdirectory). If not set, we write into the model snapshot directory."""
|
||||
|
||||
seq_len: int = 2048
|
||||
"""Sequence length the model is trained on."""
|
||||
|
||||
|
||||
+26
-137
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "prime-rl"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
description = "Async RL Training at Scale"
|
||||
readme = "README.md"
|
||||
requires-python = "~=3.12.0"
|
||||
@@ -66,79 +66,12 @@ flash-attn-3 = ["flash_attn_3"]
|
||||
flash-attn-cute = [
|
||||
"flash-attn-4",
|
||||
]
|
||||
envs = [
|
||||
"aime24-v1",
|
||||
"aime25-v1",
|
||||
"aime26-v1",
|
||||
"alphabet-sort",
|
||||
"alphabet-sort-v1",
|
||||
"apex-shortlist-v1",
|
||||
"arxivmath-v1",
|
||||
"browsecomp-v1",
|
||||
"code-golf-v1",
|
||||
"color-codeword-v1",
|
||||
"deepdive-v1",
|
||||
"deepwiki-v1",
|
||||
"forth-lang-v1",
|
||||
"general-agent-v1",
|
||||
"glossary-v1",
|
||||
"gpqa-v1",
|
||||
"graphwalks-v1",
|
||||
"gsm8k-v1",
|
||||
"i3-code-v1",
|
||||
"i3-logic-v1",
|
||||
"i3-math-v1",
|
||||
"i3-science-v1",
|
||||
"ifbench-v1",
|
||||
"ifeval-v1",
|
||||
"lean-v1",
|
||||
"livecodebench-v1",
|
||||
"longcot-mini-v1",
|
||||
"longcot-v1",
|
||||
"longpdfs-v1",
|
||||
"math-env-v1",
|
||||
"math-python",
|
||||
"math500-v1",
|
||||
"mmlu-pro-v1",
|
||||
"mrcr-v2-v1",
|
||||
"oolong-pairs-v1",
|
||||
"oolong-real-v1",
|
||||
"oolong-synth-v1",
|
||||
"openseeker-v1",
|
||||
"openthoughts-tblite-v1",
|
||||
"papersearchqa-v1",
|
||||
"patterned-needle-in-haystack-v1",
|
||||
"prolog-v1",
|
||||
"r2e-gym-v1",
|
||||
"redsearcher-v1",
|
||||
"reverse-text",
|
||||
"reverse-text-v1",
|
||||
"s1-deepresearch-v1",
|
||||
"scaleswe-v1",
|
||||
"simpleqa-v1",
|
||||
"simpleqa-verified-v1",
|
||||
"swebench-pro-v1",
|
||||
"swebench-verified-v1",
|
||||
"swelego-v1",
|
||||
"tau2-bench-v1",
|
||||
"terminal-bench-2-v1",
|
||||
"tmax-v1",
|
||||
"unscramble-v1",
|
||||
"uuid-ctf-v1",
|
||||
"verbatim-copy-v1",
|
||||
"wideseek-v1",
|
||||
"wiki-search",
|
||||
"wiki-search-v1",
|
||||
"wikispeedia-v1",
|
||||
"wordle",
|
||||
"wordle-v1",
|
||||
]
|
||||
disagg = [
|
||||
"deep-ep ; platform_machine == 'x86_64'",
|
||||
"deep-gemm ; platform_machine == 'x86_64'",
|
||||
"deep-gemm",
|
||||
"nixl",
|
||||
"nixl-cu12 ; platform_machine == 'x86_64'",
|
||||
"vllm-router ; platform_machine == 'x86_64'",
|
||||
"vllm-router",
|
||||
]
|
||||
gpt-oss = [
|
||||
"kernels",
|
||||
@@ -192,6 +125,21 @@ override-dependencies = [
|
||||
"openenv-core",
|
||||
]
|
||||
|
||||
# Environment packages (research-environments + verifiers) are auto-discovered as
|
||||
# workspace members, so new envs need no per-package registration. Install them
|
||||
# with `uv sync --all-packages`.
|
||||
[tool.uv.workspace]
|
||||
members = [
|
||||
"deps/research-environments/environments/*/*",
|
||||
"deps/verifiers/environments/*",
|
||||
]
|
||||
# tau2-synth-v1 and tau3-bench-v1 pin `tau2` forks/revs that conflict with the
|
||||
# canonical tau2-bench-v1; a workspace shares one lock, so these can't coexist.
|
||||
exclude = [
|
||||
"deps/research-environments/environments/tool_use/tau2_synth_v1",
|
||||
"deps/research-environments/environments/tool_use/tau3_bench_v1",
|
||||
]
|
||||
|
||||
# ModelExpress 0.3.0 publishes protobuf<6 metadata, but its generated proto is
|
||||
# compatible with protobuf 6. prime-sandboxes requires protobuf>=6.31.1; keep
|
||||
# this capped to the validated protobuf major.
|
||||
@@ -241,84 +189,25 @@ prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
|
||||
verifiers = { path = "deps/verifiers", editable = true }
|
||||
renderers = { path = "deps/renderers", editable = true }
|
||||
prime-pydantic-config = { path = "deps/pydantic-config", editable = true }
|
||||
aime24-v1 = { path = "deps/research-environments/environments/math/aime24_v1", editable = true }
|
||||
aime25-v1 = { path = "deps/research-environments/environments/math/aime25_v1", editable = true }
|
||||
aime26-v1 = { path = "deps/research-environments/environments/math/aime26_v1", editable = true }
|
||||
alphabet-sort = { path = "deps/verifiers/environments/alphabet_sort", editable = true }
|
||||
alphabet-sort-v1 = { path = "deps/verifiers/environments/alphabet_sort_v1", editable = true }
|
||||
apex-shortlist-v1 = { path = "deps/research-environments/environments/math/apex_shortlist_v1", editable = true }
|
||||
arxivmath-v1 = { path = "deps/research-environments/environments/math/arxivmath_v1", editable = true }
|
||||
browsecomp-v1 = { path = "deps/research-environments/environments/search/browsecomp_v1", editable = true }
|
||||
code-golf-v1 = { path = "deps/verifiers/environments/code_golf_v1", editable = true }
|
||||
color-codeword-v1 = { path = "deps/verifiers/environments/color_codeword_v1", editable = true }
|
||||
deepdive-v1 = { path = "deps/research-environments/environments/search/deepdive_v1", editable = true }
|
||||
deepwiki-v1 = { path = "deps/verifiers/environments/deepwiki_v1", editable = true }
|
||||
forth-lang-v1 = { path = "deps/research-environments/environments/code/forth_lang_v1", editable = true }
|
||||
general-agent-v1 = { path = "deps/research-environments/environments/tool_use/general_agent_v1", editable = true }
|
||||
glossary-v1 = { path = "deps/verifiers/environments/glossary_v1", editable = true }
|
||||
gpqa-v1 = { path = "deps/research-environments/environments/science/gpqa_v1", editable = true }
|
||||
graphwalks-v1 = { path = "deps/research-environments/environments/long_context/graphwalks_v1", editable = true }
|
||||
gsm8k-v1 = { path = "deps/verifiers/environments/gsm8k_v1", editable = true }
|
||||
i3-code-v1 = { path = "deps/research-environments/environments/code/i3_code_v1", editable = true }
|
||||
i3-logic-v1 = { path = "deps/research-environments/environments/reasoning/i3_logic_v1", editable = true }
|
||||
i3-math-v1 = { path = "deps/research-environments/environments/math/i3_math_v1", editable = true }
|
||||
i3-science-v1 = { path = "deps/research-environments/environments/science/i3_science_v1", editable = true }
|
||||
ifbench-v1 = { path = "deps/research-environments/environments/if/ifbench_v1", editable = true }
|
||||
ifeval-v1 = { path = "deps/research-environments/environments/if/ifeval_v1", editable = true }
|
||||
lean-v1 = { path = "deps/research-environments/environments/math/lean_v1", editable = true }
|
||||
livecodebench-v1 = { path = "deps/research-environments/environments/code/livecodebench_v1", editable = true }
|
||||
longcot-mini-v1 = { path = "deps/research-environments/environments/long_context/longcot_mini_v1", editable = true }
|
||||
longcot-v1 = { path = "deps/research-environments/environments/long_context/longcot_v1", editable = true }
|
||||
longpdfs-v1 = { path = "deps/research-environments/environments/long_context/longpdfs_v1", editable = true }
|
||||
math-env-v1 = { path = "deps/research-environments/environments/math/math_env_v1", editable = true }
|
||||
math-python = { path = "deps/verifiers/environments/math_python", editable = true }
|
||||
math500-v1 = { path = "deps/research-environments/environments/math/math500_v1", editable = true }
|
||||
mmlu-pro-v1 = { path = "deps/research-environments/environments/knowledge/mmlu_pro_v1", editable = true }
|
||||
mrcr-v2-v1 = { path = "deps/research-environments/environments/long_context/mrcr_v2_v1", editable = true }
|
||||
oolong-pairs-v1 = { path = "deps/research-environments/environments/long_context/oolong_pairs_v1", editable = true }
|
||||
oolong-real-v1 = { path = "deps/research-environments/environments/long_context/oolong_real_v1", editable = true }
|
||||
oolong-synth-v1 = { path = "deps/research-environments/environments/long_context/oolong_synth_v1", editable = true }
|
||||
openseeker-v1 = { path = "deps/research-environments/environments/search/openseeker_v1", editable = true }
|
||||
openthoughts-tblite-v1 = { path = "deps/research-environments/environments/terminal/openthoughts_tblite_v1", editable = true }
|
||||
papersearchqa-v1 = { path = "deps/research-environments/environments/search/papersearchqa_v1", editable = true }
|
||||
patterned-needle-in-haystack-v1 = { path = "deps/research-environments/environments/long_context/patterned_needle_in_haystack_v1", editable = true }
|
||||
prolog-v1 = { path = "deps/research-environments/environments/reasoning/prolog_v1", editable = true }
|
||||
r2e-gym-v1 = { path = "deps/research-environments/environments/swe/r2e_gym_v1", editable = true }
|
||||
redsearcher-v1 = { path = "deps/research-environments/environments/search/redsearcher_v1", editable = true }
|
||||
reverse-text = { path = "deps/verifiers/environments/reverse_text", editable = true }
|
||||
reverse-text-v1 = { path = "deps/verifiers/environments/reverse_text_v1", editable = true }
|
||||
s1-deepresearch-v1 = { path = "deps/research-environments/environments/search/s1_deepresearch_v1", editable = true }
|
||||
scaleswe-v1 = { path = "deps/research-environments/environments/swe/scaleswe_v1", editable = true }
|
||||
simpleqa-v1 = { path = "deps/research-environments/environments/knowledge/simpleqa_v1", editable = true }
|
||||
simpleqa-verified-v1 = { path = "deps/research-environments/environments/knowledge/simpleqa_verified_v1", editable = true }
|
||||
swebench-pro-v1 = { path = "deps/research-environments/environments/swe/swebench_pro_v1", editable = true }
|
||||
swebench-verified-v1 = { path = "deps/research-environments/environments/swe/swebench_verified_v1", editable = true }
|
||||
swelego-v1 = { path = "deps/research-environments/environments/swe/swelego_v1", editable = true }
|
||||
tau2-bench-v1 = { path = "deps/research-environments/environments/tool_use/tau2_bench_v1", editable = true }
|
||||
terminal-bench-2-v1 = { path = "deps/research-environments/environments/terminal/terminal_bench_2_v1", editable = true }
|
||||
tmax-v1 = { path = "deps/research-environments/environments/terminal/tmax_v1", editable = true }
|
||||
unscramble-v1 = { path = "deps/research-environments/environments/reasoning/unscramble_v1", editable = true }
|
||||
uuid-ctf-v1 = { path = "deps/research-environments/environments/reasoning/uuid_ctf_v1", editable = true }
|
||||
verbatim-copy-v1 = { path = "deps/research-environments/environments/long_context/verbatim_copy_v1", editable = true }
|
||||
wideseek-v1 = { path = "deps/research-environments/environments/search/wideseek_v1", editable = true }
|
||||
wiki-search = { path = "deps/verifiers/environments/wiki_search", editable = true }
|
||||
wiki-search-v1 = { path = "deps/verifiers/environments/wiki_search_v1", editable = true }
|
||||
wikispeedia-v1 = { path = "deps/research-environments/environments/reasoning/wikispeedia_v1", editable = true }
|
||||
wordle = { path = "deps/verifiers/environments/wordle", editable = true }
|
||||
wordle-v1 = { path = "deps/verifiers/environments/wordle_v1", editable = true }
|
||||
torch = { index = "pytorch-cu128" }
|
||||
torchvision = { index = "pytorch-cu128" }
|
||||
torchaudio = { index = "pytorch-cu128" }
|
||||
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "23e4dfc" }
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
|
||||
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
|
||||
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_x86_64.whl" }
|
||||
vllm-router = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
vllm = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
deep-ep = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl" }
|
||||
deep-gemm = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl" }
|
||||
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", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
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" }
|
||||
flash-linear-attention = { git = "https://github.com/fla-org/flash-linear-attention" }
|
||||
flash_attn_3 = { index = "pytorch-cu128-test" }
|
||||
|
||||
@@ -59,9 +59,9 @@ if [ -n "$PRIME_RL_REF" ]; then
|
||||
# startup. --inexact keeps the seeded venv's pre-built wheels
|
||||
# (flash-attn-3, mamba-ssm) in place; uv only rebuilds them if the
|
||||
# override's lockfile pins different versions.
|
||||
( cd "$DEST" && uv sync --inexact --no-dev \
|
||||
( cd "$DEST" && uv sync --inexact --no-dev --all-packages \
|
||||
--extra flash-attn --extra flash-attn-3 --extra flash-attn-cute \
|
||||
--extra envs --extra gpt-oss --extra modelexpress \
|
||||
--extra gpt-oss --extra modelexpress \
|
||||
--group mamba-ssm )
|
||||
export VIRTUAL_ENV="$DEST/.venv"
|
||||
export PATH="$DEST/.venv/bin:$PATH"
|
||||
|
||||
+6
-10
@@ -22,12 +22,14 @@ git submodule update --init --recursive
|
||||
## Sync
|
||||
|
||||
```bash
|
||||
uv sync # core only
|
||||
uv sync --group dev # + pytest, ruff, pre-commit
|
||||
uv sync --all-extras # recommended: envs, flash-attn, flash-attn-cute, etc.
|
||||
uv sync # core only
|
||||
uv sync --group dev # + pytest, ruff, pre-commit
|
||||
uv sync --all-extras # + extras (flash-attn, flash-attn-cute, …)
|
||||
uv sync --all-extras --all-packages # + all env packages (needed to train on them)
|
||||
uv sync --package prime-rl --package gsm8k-v1 # core + just one env
|
||||
```
|
||||
|
||||
The `envs` extra installs environments listed under `[project.optional-dependencies].envs`, resolved through `[tool.uv.sources]`. Adding a new env means adding its package name to `envs` and its editable source path to `[tool.uv.sources]`.
|
||||
Environment packages under `deps/research-environments/environments/*/*` and `deps/verifiers/environments/*` are uv **workspace members**, auto-discovered — adding a new env needs no `pyproject.toml` change. They are opt-in: a plain `uv sync` / `--all-extras` does not install them (and would remove them if already present — re-run with `--all-packages`, or `--inexact` to keep them). Install all with `--all-packages`, or a subset with repeated `--package <env>` (include `--package prime-rl` to keep the core). If two envs pin conflicting transitive versions (all members share one lock), add the loser to `[tool.uv.workspace].exclude`.
|
||||
|
||||
When bumping a package past the workspace-wide `exclude-newer = "7 days"` window, add it (and any newly-required transitives) to `[tool.uv.exclude-newer-package]` before refreshing `uv.lock`.
|
||||
|
||||
@@ -41,12 +43,6 @@ CUDA_HOME=/usr/local/cuda uv pip install mamba-ssm
|
||||
|
||||
Requires `nvcc`. Without `mamba-ssm`, NemotronH falls back to HF's pure-PyTorch SSD path, which computes softplus in bf16 and yields ~0.4 KL divergence vs vLLM. Do **not** install `causal-conv1d` unless your GPU arch matches the prebuilt kernels — the code falls back to `nn.Conv1d` when it's absent.
|
||||
|
||||
### FP8 inference (GLM-5-FP8, etc.)
|
||||
|
||||
```bash
|
||||
uv sync --group fp8-inference # installs the prebuilt deep-gemm wheel
|
||||
```
|
||||
|
||||
### Trainer DeepEP backend
|
||||
|
||||
`scripts/install_ep_kernels.sh` auto-detects the CUDA toolkit matching torch and the GPU arch, builds NVSHMEM + DeepEP from source, and skips if `deep_ep` already imports.
|
||||
|
||||
@@ -37,9 +37,10 @@ uv run rl @ examples/reverse_text/rl.toml --dry-run
|
||||
- Environment packages: before launching a config with a non-core verifier env id,
|
||||
verify the package imports under `uv run` (for example
|
||||
`uv run python -c "import importlib.util; print(importlib.util.find_spec('r2e_gym_v1'))"`).
|
||||
If a local env exists under `deps/research-environments/environments/` but does not
|
||||
import, add it to the root `pyproject.toml` env extra, workspace members, and
|
||||
`[tool.uv.sources]`, then run `uv sync --all-extras`.
|
||||
If a local env exists under `deps/research-environments/environments/` or
|
||||
`deps/verifiers/environments/` but does not import, install the env workspace
|
||||
members with `uv sync --all-packages` (all) or `uv sync --package prime-rl
|
||||
--package <env>` (one) — they're auto-discovered, no `pyproject.toml` edit needed.
|
||||
|
||||
## `sft` — SFT training
|
||||
|
||||
|
||||
@@ -101,6 +101,11 @@ MAX_CONSECUTIVE_EMPTY_BATCHES = 10
|
||||
# resumed when the watcher advances ``policy.version``.
|
||||
TARGET_LAG = 1
|
||||
|
||||
# Default wait for the trainer's startup weight broadcast when no ckpt block
|
||||
# configures ``wait_for_weights_timeout`` (e.g. a from-scratch run). The
|
||||
# broadcast is always coming, so wait rather than fail immediately.
|
||||
STARTUP_WEIGHT_WAIT_TIMEOUT_S = 1200
|
||||
|
||||
|
||||
class Orchestrator:
|
||||
# Set in ``__init__``
|
||||
@@ -315,19 +320,29 @@ class Orchestrator:
|
||||
# trainer even when ``ckpt.skip_progress`` left the counter unrestored.
|
||||
self.progress.step = self.resume_step + 1
|
||||
get_logger().info(f"Resuming orchestrator from checkpoint step {self.resume_step}")
|
||||
check_exists = config.weight_broadcast.type != "nccl"
|
||||
wait_timeout = config.ckpt.wait_for_weights_timeout if config.ckpt else None
|
||||
weights_path = get_weight_dir(
|
||||
config.output_dir, self.resume_step, check_exists=check_exists, wait_timeout=wait_timeout
|
||||
)
|
||||
await self.policy_inference.update_weights(weights_path, lora_name=self.lora_name, step=self.resume_step)
|
||||
if self.lora_name is not None:
|
||||
self.policy_inference.update_model_name(self.lora_name)
|
||||
self.policy.model_name = self.lora_name
|
||||
self.policy.version = self.resume_step
|
||||
else:
|
||||
get_logger().info("Training from scratch")
|
||||
|
||||
# Sync inference to the incoming policy before the first step, whether fresh (v0 = base) or
|
||||
# resumed (v{resume_step}). This pauses inference and rendezvouses with the trainer's
|
||||
# first-step broadcast (train.py), so inference serves the correct policy from step 1. Keeping
|
||||
# it unconditional makes trainer/orchestrator startup symmetric and avoids the resume deadlock
|
||||
# where inference waited for weights the trainer only sent at the end of a step.
|
||||
sync_version = self.resume_step if self.resume_step is not None else 0
|
||||
check_exists = config.weight_broadcast.type != "nccl"
|
||||
# Wait for the trainer's startup broadcast to land. On a fresh start there is no ckpt block,
|
||||
# so fall back to a default timeout instead of not waiting at all (which would raise before
|
||||
# broadcasts/step_0/STABLE is written when using filesystem weight broadcast).
|
||||
wait_timeout = config.ckpt.wait_for_weights_timeout if config.ckpt else STARTUP_WEIGHT_WAIT_TIMEOUT_S
|
||||
weights_path = get_weight_dir(
|
||||
config.output_dir, sync_version, check_exists=check_exists, wait_timeout=wait_timeout
|
||||
)
|
||||
await self.policy_inference.update_weights(weights_path, lora_name=self.lora_name, step=sync_version)
|
||||
if self.lora_name is not None:
|
||||
self.policy_inference.update_model_name(self.lora_name)
|
||||
self.policy.model_name = self.lora_name
|
||||
self.policy.version = sync_version
|
||||
|
||||
self.train_source = TrainSource(self.train_envs, seed=42)
|
||||
self.eval_source: EvalSource | None = (
|
||||
EvalSource(
|
||||
|
||||
@@ -70,10 +70,13 @@ class TrainSink:
|
||||
self.pre_filters = pre_filters
|
||||
self.post_filters = post_filters
|
||||
|
||||
# Observation window for the next shipped batch: rollouts of groups
|
||||
# finalized since the last ship (errored + filtered + survivors).
|
||||
# In-progress groups stay out until they finalize.
|
||||
self.pending_rollouts: TrainRollouts = TrainRollouts()
|
||||
# Keyed by the dispatcher's group UUID. ``(env_name, task_idx)``
|
||||
# isn't unique — the same task can be re-sampled while an
|
||||
# earlier group is still in flight
|
||||
self.pending_rollouts: TrainRollouts = TrainRollouts()
|
||||
self.pending_groups: dict[uuid.UUID, list[Rollout]] = defaultdict(list)
|
||||
self.pending_batch: list[Rollout] = []
|
||||
# Running payload-token total of ``pending_batch`` (token-batched
|
||||
@@ -130,13 +133,18 @@ class TrainSink:
|
||||
|
||||
async def add(self, rollout: Rollout) -> TrainBatch | None:
|
||||
"""Process one arrival; finalize the group on the ``group_size``-th
|
||||
arrival; return a ``TrainBatch`` if the batch threshold is met."""
|
||||
arrival; return a ``TrainBatch`` if the finalization pushed (or left)
|
||||
the batch over its threshold. Arrivals into still-incomplete groups
|
||||
never ship a batch."""
|
||||
await self.process_rollout(rollout)
|
||||
env_name = rollout.env_name
|
||||
self.pending_rollouts.append(rollout)
|
||||
self.pending_groups[rollout.group_id].append(rollout)
|
||||
if len(self.pending_groups[rollout.group_id]) >= self.group_size_for(env_name):
|
||||
await self.process_group(rollout.group_id)
|
||||
if len(self.pending_groups[rollout.group_id]) < self.group_size_for(env_name):
|
||||
return None
|
||||
await self.process_group(rollout.group_id)
|
||||
# ``pending_batch`` only grows on group finalization, so readiness is
|
||||
# only re-checked here — the window of a shipped batch then always
|
||||
# contains at least the group that finalized it.
|
||||
ready = (
|
||||
len(self.pending_batch) >= self.batch_size
|
||||
if self.batch_size is not None
|
||||
@@ -172,6 +180,12 @@ class TrainSink:
|
||||
group = self.pending_groups.pop(group_id, [])
|
||||
if not group:
|
||||
return
|
||||
# Window membership follows group finalization, not arrival: a rollout
|
||||
# only becomes observable (metrics / persistence) once its whole group
|
||||
# is finalized, so a batch's window never claims rollouts of a group
|
||||
# that ships later. Dropped groups still land here — they were observed.
|
||||
for r in group:
|
||||
self.pending_rollouts.append(r)
|
||||
env_name = group[0].env_name
|
||||
task_idx = group[0].task.data.idx
|
||||
survivors = [r for r in group if not r.has_error]
|
||||
@@ -266,11 +280,12 @@ class TrainSink:
|
||||
# advantage stream and loss routing on each sample. Filtered rollouts don't ship.
|
||||
samples: list[TrainingSample] = [sample for r in cohort if not r.is_filtered for sample in r.samples]
|
||||
|
||||
# ``rollouts`` is the whole arrival window (errored + filtered + survivors); ``samples`` is
|
||||
# the shipped cohort's trainable payload. ``rollouts.effective`` / ``rollouts.metrics`` derive
|
||||
# the clean subset + metric views on demand. Reset the window only when the batch actually
|
||||
# ships (non-empty samples) — an empty batch is dropped unlogged by the orchestrator, so keep
|
||||
# accumulating its arrivals (and any overflow) into the next shipped batch's window.
|
||||
# ``rollouts`` is the observation window — every rollout of every group finalized since the
|
||||
# last ship (errored + filtered + survivors) — while ``samples`` is the shipped cohort's
|
||||
# trainable payload. ``rollouts.effective`` / ``rollouts.metrics`` derive the clean subset +
|
||||
# metric views on demand. Reset the window only when the batch actually ships (non-empty
|
||||
# samples) — an empty batch is dropped unlogged by the orchestrator, so keep accumulating its
|
||||
# finalized groups (and any overflow) into the next shipped batch's window.
|
||||
rollouts = self.pending_rollouts
|
||||
if samples:
|
||||
self.pending_rollouts = TrainRollouts()
|
||||
|
||||
@@ -147,11 +147,12 @@ class Rollout(vf.Trace[DataT], Generic[DataT]):
|
||||
|
||||
@dataclass
|
||||
class TrainBatch:
|
||||
"""``rollouts`` is the full arrival window since the last ship (errored + filtered included; its
|
||||
``.effective`` / ``.metrics`` views drive logging). ``samples`` is the trainer-bound payload (the
|
||||
shipped cohort's post-filter survivors) — an empty list means nothing ships, which would stall the
|
||||
trainer. Trainable counts derive from ``rollouts`` (``r.is_trainable``) and token totals from
|
||||
``samples``, so neither is carried as a field."""
|
||||
"""``rollouts`` is the observation window since the last ship — every rollout of every group
|
||||
finalized in that span (errored + filtered included; rollouts of still-incomplete groups wait
|
||||
for a later window). Its ``.effective`` / ``.metrics`` views drive logging. ``samples`` is the
|
||||
trainer-bound payload (the shipped cohort's post-filter survivors) — an empty list means nothing
|
||||
ships, which would stall the trainer. Trainable counts derive from ``rollouts``
|
||||
(``r.is_trainable``) and token totals from ``samples``, so neither is carried as a field."""
|
||||
|
||||
rollouts: TrainRollouts
|
||||
samples: list[TrainingSample]
|
||||
|
||||
@@ -67,10 +67,10 @@ source .venv/bin/activate
|
||||
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
|
||||
# inside the task because unexported vars in .env don't cross srun even with normal
|
||||
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
|
||||
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras'
|
||||
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages'
|
||||
{% else %}
|
||||
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
|
||||
uv sync --all-extras
|
||||
uv sync --all-extras --all-packages
|
||||
{% endif %}
|
||||
|
||||
# Print inference URLs
|
||||
|
||||
@@ -150,10 +150,10 @@ source .venv/bin/activate
|
||||
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
|
||||
# inside the task because unexported vars in .env don't cross srun even with normal
|
||||
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
|
||||
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras'
|
||||
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages'
|
||||
{% else %}
|
||||
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
|
||||
uv sync --all-extras
|
||||
uv sync --all-extras --all-packages
|
||||
{% endif %}
|
||||
|
||||
{% if pre_run_command %}
|
||||
|
||||
@@ -54,10 +54,10 @@ source $PROJECT_DIR/.venv/bin/activate
|
||||
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
|
||||
# inside the task because unexported vars in .env don't cross srun even with normal
|
||||
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
|
||||
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras'
|
||||
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages'
|
||||
{% else %}
|
||||
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
|
||||
cd $PROJECT_DIR && uv sync --all-extras
|
||||
cd $PROJECT_DIR && uv sync --all-extras --all-packages
|
||||
{% endif %}
|
||||
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ export PROJECT_DIR={{ project_dir }}
|
||||
cd $PROJECT_DIR
|
||||
[ -f .env ] && source .env
|
||||
source .venv/bin/activate
|
||||
uv sync --all-extras
|
||||
uv sync --all-extras --all-packages
|
||||
|
||||
{% if pre_run_command %}
|
||||
# Pre-run command
|
||||
|
||||
@@ -31,7 +31,7 @@ export PROJECT_DIR={{ project_dir }}
|
||||
cd $PROJECT_DIR
|
||||
[ -f .env ] && source .env
|
||||
source .venv/bin/activate
|
||||
uv sync --all-extras
|
||||
uv sync --all-extras --all-packages
|
||||
|
||||
{% if pre_run_command %}
|
||||
# Pre-run command
|
||||
|
||||
@@ -834,19 +834,21 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
|
||||
# All ranks read just the key names (cheap) to determine the path independently.
|
||||
# Only master loads the full state dict when conversion is actually needed.
|
||||
if isinstance(model, PreTrainedModelPrimeRL):
|
||||
snapshot_keys = dict.fromkeys(load_state_dict_keys(snapshot_path))
|
||||
source_path = snapshot_path
|
||||
convert_dir = config.conversion_dir or source_path
|
||||
snapshot_keys = dict.fromkeys(load_state_dict_keys(source_path))
|
||||
model_keys = dict.fromkeys(model.state_dict().keys())
|
||||
|
||||
if model.is_hf_state_dict(snapshot_keys) and model.is_prime_state_dict(model_keys):
|
||||
logger.warning(
|
||||
"Found HF weight format in snapshot state dict and PrimeRL weight format in model state dict. Trying to auto-convert..."
|
||||
)
|
||||
snapshot_path = snapshot_path / "prime"
|
||||
snapshot_path = convert_dir / "prime"
|
||||
if not snapshot_path.exists() and get_world().is_master:
|
||||
logger.debug(
|
||||
f"Converting snapshot state dict to PrimeRL format and saving to {snapshot_path} on master rank. This is a one-time operation."
|
||||
)
|
||||
snapshot_state_dict = load_state_dict(snapshot_path.parent)
|
||||
snapshot_state_dict = load_state_dict(source_path)
|
||||
model.convert_to_prime(snapshot_state_dict)
|
||||
save_state_dict(snapshot_state_dict, snapshot_path)
|
||||
del snapshot_state_dict
|
||||
@@ -855,12 +857,12 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
|
||||
logger.warning(
|
||||
"Found PrimeRL weight format in snapshot state dict and HF weight format in model state dict. Trying to auto-convert..."
|
||||
)
|
||||
snapshot_path = snapshot_path / "hf"
|
||||
snapshot_path = convert_dir / "hf"
|
||||
if not snapshot_path.exists() and get_world().is_master:
|
||||
logger.debug(
|
||||
f"Converting snapshot state dict to HF format and saving to {snapshot_path} on master rank. This is a one-time operation."
|
||||
)
|
||||
snapshot_state_dict = load_state_dict(snapshot_path.parent)
|
||||
snapshot_state_dict = load_state_dict(source_path)
|
||||
model.convert_to_hf(snapshot_state_dict)
|
||||
save_state_dict(snapshot_state_dict, snapshot_path)
|
||||
del snapshot_state_dict
|
||||
|
||||
@@ -249,7 +249,7 @@ def _grouped_per_token_fp8_kernel(
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _grouped_per_channel_fp8_sm90_kmajor_kernel(
|
||||
def _grouped_per_channel_fp8_kernel(
|
||||
x_ptr,
|
||||
block_to_group_ptr,
|
||||
starts_ptr,
|
||||
@@ -264,6 +264,7 @@ def _grouped_per_channel_fp8_sm90_kmajor_kernel(
|
||||
stride_sf0,
|
||||
stride_sf1,
|
||||
USE_UE8M0: tl.constexpr,
|
||||
K_MAJOR: tl.constexpr,
|
||||
BLOCK_K: tl.constexpr,
|
||||
BLOCK_N: tl.constexpr,
|
||||
):
|
||||
@@ -293,8 +294,20 @@ def _grouped_per_channel_fp8_sm90_kmajor_kernel(
|
||||
scale = tl.exp2(tl.ceil(tl.log2(scale)))
|
||||
y = x / scale[None, :]
|
||||
flat_base = block_start.to(tl.int64) * BLOCK_K * cols
|
||||
out_ptrs = out_ptr + flat_base + col_offsets_i64[:, None] * aligned_m + row_offsets_i64[None, :]
|
||||
tl.store(out_ptrs, tl.trans(y).to(tl.float8e4nv), mask=valid_cols[:, None] & (row_offsets[None, :] < aligned_m))
|
||||
if K_MAJOR:
|
||||
out_ptrs = out_ptr + flat_base + col_offsets_i64[:, None] * aligned_m + row_offsets_i64[None, :]
|
||||
tl.store(
|
||||
out_ptrs,
|
||||
tl.trans(y).to(tl.float8e4nv),
|
||||
mask=valid_cols[:, None] & (row_offsets[None, :] < aligned_m),
|
||||
)
|
||||
else:
|
||||
out_ptrs = out_ptr + flat_base + row_offsets_i64[:, None] * cols + col_offsets_i64[None, :]
|
||||
tl.store(
|
||||
out_ptrs,
|
||||
y.to(tl.float8e4nv),
|
||||
mask=(row_offsets[:, None] < aligned_m) & valid_cols[None, :],
|
||||
)
|
||||
tl.store(
|
||||
sf_ptr + pid_blk * stride_sf0 + col_offsets_i64 * stride_sf1,
|
||||
scale,
|
||||
@@ -477,7 +490,7 @@ def grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
|
||||
if block_to_group.numel() == 0:
|
||||
return out, sf.T
|
||||
grid = (block_to_group.numel(), ceil_div(x.size(1), 128))
|
||||
_grouped_per_channel_fp8_sm90_kmajor_kernel[grid](
|
||||
_grouped_per_channel_fp8_kernel[grid](
|
||||
x,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
@@ -492,6 +505,7 @@ def grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
|
||||
sf.stride(0),
|
||||
sf.stride(1),
|
||||
USE_UE8M0=use_ue8m0,
|
||||
K_MAJOR=True,
|
||||
BLOCK_K=gran_k,
|
||||
BLOCK_N=128,
|
||||
num_warps=4,
|
||||
@@ -499,6 +513,48 @@ def grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
|
||||
return out, sf.T
|
||||
|
||||
|
||||
def grouped_per_channel_cast_to_fp8_rowmajor_triton(
|
||||
x: torch.Tensor,
|
||||
padded_total_m: int,
|
||||
block_to_group: torch.Tensor,
|
||||
starts_tensor: torch.Tensor,
|
||||
actual_ms_tensor: torch.Tensor,
|
||||
ks_tensor: torch.Tensor,
|
||||
block_starts_tensor: torch.Tensor,
|
||||
use_ue8m0: bool,
|
||||
gran_k: int = GROUP_ALIGNMENT,
|
||||
) -> Tuple[torch.Tensor, torch.Tensor]:
|
||||
assert x.dim() == 2
|
||||
assert gran_k == GROUP_ALIGNMENT
|
||||
out = torch.empty((padded_total_m, x.size(1)), device=x.device, dtype=torch.float8_e4m3fn)
|
||||
total_blocks = padded_total_m // gran_k
|
||||
sf = torch.empty((total_blocks, x.size(1)), device=x.device, dtype=torch.float32)
|
||||
if block_to_group.numel() == 0:
|
||||
return out, sf
|
||||
grid = (block_to_group.numel(), ceil_div(x.size(1), 128))
|
||||
_grouped_per_channel_fp8_kernel[grid](
|
||||
x,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
ks_tensor,
|
||||
block_starts_tensor,
|
||||
out,
|
||||
sf,
|
||||
x.size(1),
|
||||
x.stride(0),
|
||||
x.stride(1),
|
||||
sf.stride(0),
|
||||
sf.stride(1),
|
||||
USE_UE8M0=use_ue8m0,
|
||||
K_MAJOR=False,
|
||||
BLOCK_K=gran_k,
|
||||
BLOCK_N=128,
|
||||
num_warps=4,
|
||||
)
|
||||
return out, sf
|
||||
|
||||
|
||||
def grouped_per_block_cast_to_fp8_triton(
|
||||
x: torch.Tensor, use_ue8m0: bool, gran_k: int = GROUP_ALIGNMENT
|
||||
) -> Tuple[torch.Tensor, torch.Tensor]:
|
||||
|
||||
@@ -18,6 +18,45 @@ import torch
|
||||
import torch.distributed as dist
|
||||
|
||||
|
||||
def _build_seq_idx(boundaries: list[int], seq_len: int, device: torch.device) -> torch.Tensor:
|
||||
"""Return the packed-document id for each token in a full CP sequence."""
|
||||
if boundaries[0] != 0 or boundaries[-1] != seq_len:
|
||||
raise ValueError(f"cu_seqlens must span the full sequence length {seq_len}, got {boundaries}")
|
||||
|
||||
seq_idx = torch.empty(seq_len, dtype=torch.int32, device=device)
|
||||
for sequence_id, (start, end) in enumerate(zip(boundaries[:-1], boundaries[1:])):
|
||||
if end <= start:
|
||||
raise ValueError(f"cu_seqlens must be strictly increasing, got {boundaries}")
|
||||
seq_idx[start:end] = sequence_id
|
||||
return seq_idx.unsqueeze(0)
|
||||
|
||||
|
||||
def _causal_conv1d_varlen(
|
||||
hidden_states: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
bias: torch.Tensor | None,
|
||||
boundaries: list[int],
|
||||
) -> torch.Tensor:
|
||||
"""Apply a depthwise causal convolution independently to packed documents."""
|
||||
batch_size, _, channels = hidden_states.shape
|
||||
if batch_size != 1:
|
||||
raise ValueError(f"packed CP Mamba expects batch_size=1, got {batch_size}")
|
||||
|
||||
inputs = hidden_states.transpose(1, 2)
|
||||
outputs = []
|
||||
for start, end in zip(boundaries[:-1], boundaries[1:]):
|
||||
convolved = torch.nn.functional.conv1d(
|
||||
inputs[:, :, start:end],
|
||||
weight,
|
||||
bias,
|
||||
groups=channels,
|
||||
padding=weight.shape[2] - 1,
|
||||
)
|
||||
outputs.append(convolved[:, :, : end - start])
|
||||
|
||||
return torch.cat(outputs, dim=-1).transpose(1, 2)
|
||||
|
||||
|
||||
class _SeqToHeadParallel(torch.autograd.Function):
|
||||
"""[B, S/cp, D] -> [B, S, D/cp] via all-to-all."""
|
||||
|
||||
@@ -93,7 +132,14 @@ def head_to_seq_parallel(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size:
|
||||
return _HeadToSeqParallel.apply(x, cp_group, cp_size)
|
||||
|
||||
|
||||
def mamba_cp_forward(mixer, hidden_states: torch.Tensor, cp_group: dist.ProcessGroup, cp_rank: int, cp_size: int):
|
||||
def mamba_cp_forward(
|
||||
mixer,
|
||||
hidden_states: torch.Tensor,
|
||||
cp_group: dist.ProcessGroup,
|
||||
cp_rank: int,
|
||||
cp_size: int,
|
||||
cu_seqlens: torch.Tensor,
|
||||
):
|
||||
"""CP-aware Mamba-2 forward: in_proj -> all-to-all -> conv+SSM(local heads) -> all-to-all -> out_proj.
|
||||
|
||||
Replaces the mixer's cuda_kernels_forward when CP > 1. Parameters are
|
||||
@@ -134,6 +180,8 @@ def mamba_cp_forward(mixer, hidden_states: torch.Tensor, cp_group: dist.ProcessG
|
||||
hidden_states_B_C = torch.cat([x_part, B_part, C_part], dim=-1)
|
||||
|
||||
full_seq_len = hidden_states_B_C.shape[1] # S (full sequence)
|
||||
boundaries = cu_seqlens.tolist()
|
||||
seq_idx = _build_seq_idx(boundaries, full_seq_len, hidden_states.device)
|
||||
|
||||
# ── 3. Local head dimensions ──
|
||||
local_num_heads = mixer.num_heads // cp_size
|
||||
@@ -151,7 +199,6 @@ def mamba_cp_forward(mixer, hidden_states: torch.Tensor, cp_group: dist.ProcessG
|
||||
# Slice conv1d weight/bias for local channels
|
||||
# conv1d channels = intermediate_size + 2 * ngroups * dstate (same as conv_dim)
|
||||
# After all-to-all, we have local channels: local_intermediate + 2 * local_ngroups * dstate
|
||||
local_conv_dim = local_intermediate_size + 2 * local_n_groups * mixer.ssm_state_size
|
||||
conv_x_start = cp_rank * local_intermediate_size
|
||||
conv_x_end = conv_x_start + local_intermediate_size
|
||||
conv_b_start = mixer.intermediate_size + cp_rank * local_n_groups * mixer.ssm_state_size
|
||||
@@ -169,15 +216,9 @@ def mamba_cp_forward(mixer, hidden_states: torch.Tensor, cp_group: dist.ProcessG
|
||||
local_conv_weight = mixer.conv1d.weight[conv_indices]
|
||||
local_conv_bias = mixer.conv1d.bias[conv_indices] if mixer.conv1d.bias is not None else None
|
||||
|
||||
# ── 4. Conv1d on full sequence, local heads ──
|
||||
# ── 4. Conv1d on each packed document, local heads ──
|
||||
hidden_states_B_C = torch.nn.functional.silu(
|
||||
torch.nn.functional.conv1d(
|
||||
hidden_states_B_C.transpose(1, 2),
|
||||
local_conv_weight,
|
||||
local_conv_bias,
|
||||
groups=local_conv_dim,
|
||||
padding=mixer.conv1d.weight.shape[2] - 1,
|
||||
).transpose(1, 2)[:, :full_seq_len]
|
||||
_causal_conv1d_varlen(hidden_states_B_C, local_conv_weight, local_conv_bias, boundaries)
|
||||
)
|
||||
|
||||
local_groups_time_state_size = local_n_groups * mixer.ssm_state_size
|
||||
@@ -190,7 +231,7 @@ def mamba_cp_forward(mixer, hidden_states: torch.Tensor, cp_group: dist.ProcessG
|
||||
# ── 5. SSM scan on full sequence, local heads ──
|
||||
dt_limit_kwargs = {} if mixer.time_step_limit is None else {"dt_limit": mixer.time_step_limit}
|
||||
|
||||
scan_output, _ = mamba_chunk_scan_combined(
|
||||
scan_output = mamba_chunk_scan_combined(
|
||||
hidden_states_local.view(batch_size, full_seq_len, local_num_heads, mixer.head_dim),
|
||||
time_step,
|
||||
local_A,
|
||||
@@ -199,8 +240,8 @@ def mamba_cp_forward(mixer, hidden_states: torch.Tensor, cp_group: dist.ProcessG
|
||||
chunk_size=mixer.chunk_size,
|
||||
D=local_D,
|
||||
z=None,
|
||||
seq_idx=None,
|
||||
return_final_states=True,
|
||||
seq_idx=seq_idx,
|
||||
return_final_states=False,
|
||||
dt_bias=local_dt_bias,
|
||||
dt_softplus=True,
|
||||
**dt_limit_kwargs,
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
|
||||
try:
|
||||
import deep_gemm
|
||||
except ImportError:
|
||||
deep_gemm = None # CPU-only environments don't ship deep_gemm; FP8 paths
|
||||
# are GPU-only at runtime, so leaving the symbol None is safe — only the
|
||||
# autograd Function bodies below actually call into it.
|
||||
import torch
|
||||
|
||||
from prime_rl.trainer.models.kernels.fp8_utils import (
|
||||
GROUP_ALIGNMENT,
|
||||
build_grouped_layout,
|
||||
grouped_per_block_cast_to_fp8_triton,
|
||||
grouped_per_channel_cast_to_fp8_rowmajor_triton,
|
||||
grouped_per_channel_cast_to_fp8_sm90_kmajor_triton,
|
||||
grouped_per_token_cast_to_fp8_triton,
|
||||
unpack_rows_triton,
|
||||
@@ -30,32 +32,60 @@ def _compute_grad_weight(
|
||||
block_starts_tensor: torch.Tensor,
|
||||
aligned_ms: list[int],
|
||||
) -> torch.Tensor:
|
||||
x_k_major = grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
|
||||
x,
|
||||
padded_total_m,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
ks_tensor,
|
||||
block_starts_tensor,
|
||||
False,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
dy_k_major = grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
|
||||
grad_output,
|
||||
padded_total_m,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
ks_tensor,
|
||||
block_starts_tensor,
|
||||
False,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
is_sm100 = torch.cuda.get_device_capability(x.device)[0] >= 10
|
||||
if is_sm100:
|
||||
x_fp8 = grouped_per_channel_cast_to_fp8_rowmajor_triton(
|
||||
x,
|
||||
padded_total_m,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
ks_tensor,
|
||||
block_starts_tensor,
|
||||
True,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
dy_fp8 = grouped_per_channel_cast_to_fp8_rowmajor_triton(
|
||||
grad_output,
|
||||
padded_total_m,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
ks_tensor,
|
||||
block_starts_tensor,
|
||||
True,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
grouped_weight_grad = deep_gemm.k_grouped_fp8_gemm_tn_contiguous
|
||||
else:
|
||||
x_fp8 = grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
|
||||
x,
|
||||
padded_total_m,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
ks_tensor,
|
||||
block_starts_tensor,
|
||||
True,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
dy_fp8 = grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
|
||||
grad_output,
|
||||
padded_total_m,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
ks_tensor,
|
||||
block_starts_tensor,
|
||||
True,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
grouped_weight_grad = deep_gemm.k_grouped_fp8_gemm_nt_contiguous
|
||||
|
||||
grad_weight = torch.zeros(weight_shape, device=x.device, dtype=torch.float32)
|
||||
deep_gemm.k_grouped_fp8_gemm_nt_contiguous(
|
||||
x_k_major,
|
||||
dy_k_major,
|
||||
grouped_weight_grad(
|
||||
x_fp8,
|
||||
dy_fp8,
|
||||
grad_weight,
|
||||
aligned_ms,
|
||||
ks_tensor,
|
||||
@@ -90,12 +120,12 @@ class _GroupedFP8Gemm(torch.autograd.Function):
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
False,
|
||||
True,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
weight_fp8 = grouped_per_block_cast_to_fp8_triton(
|
||||
weight.transpose(1, 2),
|
||||
False,
|
||||
True,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
|
||||
@@ -174,12 +204,12 @@ class _GroupedFP8Gemm(torch.autograd.Function):
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
False,
|
||||
True,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
weight_dx_fp8 = grouped_per_block_cast_to_fp8_triton(
|
||||
weight,
|
||||
False,
|
||||
True,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
grad_x_padded = torch.empty(
|
||||
|
||||
@@ -2,14 +2,15 @@ from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
try:
|
||||
import deep_gemm
|
||||
except ImportError:
|
||||
deep_gemm = None # CPU-only environments don't ship deep_gemm; FP8 paths
|
||||
# are GPU-only at runtime, so leaving the symbol None is safe — only the
|
||||
# autograd Function bodies below actually call into it.
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.trainer.models.kernels.fp8_utils import (
|
||||
per_block_cast_to_fp8_tp_triton,
|
||||
@@ -25,8 +26,8 @@ class _FP8BlockwiseMM(torch.autograd.Function):
|
||||
def forward(ctx, x, weight, block_size, out_dtype=torch.bfloat16):
|
||||
x_shape = x.shape
|
||||
x_2d = x.reshape(-1, x_shape[-1]).contiguous()
|
||||
x_fp8 = per_token_cast_to_fp8_triton(x_2d, False, block_size)
|
||||
weight_fp8 = per_block_cast_to_fp8_triton(weight, False, block_size)
|
||||
x_fp8 = per_token_cast_to_fp8_triton(x_2d, True, block_size)
|
||||
weight_fp8 = per_block_cast_to_fp8_triton(weight, True, block_size)
|
||||
|
||||
out = torch.empty((x_2d.size(0), weight.size(0)), device=x.device, dtype=out_dtype)
|
||||
deep_gemm.fp8_gemm_nt(x_fp8, weight_fp8, out)
|
||||
@@ -44,8 +45,8 @@ class _FP8BlockwiseMM(torch.autograd.Function):
|
||||
|
||||
grad_x = grad_weight = None
|
||||
if ctx.needs_input_grad[0]:
|
||||
grad_output_fp8 = per_token_cast_to_fp8_triton(grad_output_2d, False, block_size)
|
||||
weight_dx_fp8 = per_block_cast_to_fp8_tp_triton(weight, False, block_size)
|
||||
grad_output_fp8 = per_token_cast_to_fp8_triton(grad_output_2d, True, block_size)
|
||||
weight_dx_fp8 = per_block_cast_to_fp8_tp_triton(weight, True, block_size)
|
||||
grad_x_2d = torch.empty_like(x_2d)
|
||||
deep_gemm.fp8_gemm_nt(grad_output_fp8, weight_dx_fp8, grad_x_2d)
|
||||
grad_x = grad_x_2d.reshape(ctx.x_shape)
|
||||
@@ -63,8 +64,8 @@ class _FP8BlockwiseMM(torch.autograd.Function):
|
||||
else:
|
||||
grad_output_2d_padded = grad_output_2d
|
||||
x_2d_padded = x_2d
|
||||
grad_output_t_fp8 = per_token_cast_to_fp8_tp_triton(grad_output_2d_padded, False, block_size)
|
||||
x_t_fp8 = per_token_cast_to_fp8_tp_triton(x_2d_padded, False, block_size)
|
||||
grad_output_t_fp8 = per_token_cast_to_fp8_tp_triton(grad_output_2d_padded, True, block_size)
|
||||
x_t_fp8 = per_token_cast_to_fp8_tp_triton(x_2d_padded, True, block_size)
|
||||
grad_weight_fp32 = torch.zeros_like(weight, dtype=torch.float32)
|
||||
deep_gemm.fp8_gemm_nt(
|
||||
grad_output_t_fp8,
|
||||
@@ -82,7 +83,7 @@ class Float8BlockwiseLinear(nn.Linear):
|
||||
"""nn.Linear replacement that uses FP8 blockwise matmul via DeepGEMM.
|
||||
|
||||
Requires:
|
||||
- SM90 (Hopper) GPU
|
||||
- SM90 (Hopper) or SM100 (Blackwell) GPU
|
||||
- bfloat16 inputs/weights
|
||||
- No bias
|
||||
- in_features and out_features divisible by 128
|
||||
|
||||
@@ -23,6 +23,7 @@ from prime_rl.trainer.models.layers.cp_mamba import mamba_cp_forward
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.moe import LatentMoE, NemotronHRouter, NonGatedGroupedExperts
|
||||
from prime_rl.trainer.models.layers.rms_norm import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.ulysses_attn import ULYSSES_PARAMS
|
||||
from prime_rl.trainer.models.nemotron_h.configuration_nemotron_h import NemotronHConfig
|
||||
from prime_rl.trainer.models.nemotron_h.converting_nemotron_h import (
|
||||
convert_hf_layer_to_prime,
|
||||
@@ -229,9 +230,15 @@ class NemotronHMambaLayer(GradientCheckpointingLayer):
|
||||
hidden_states = self.norm(hidden_states)
|
||||
|
||||
if self.cp_enabled:
|
||||
# TODO: This path doesnt support cu_seqlens so packing makes it wrong
|
||||
# The local cu_seqlens cover only this shard; conv/scan need the full
|
||||
# pre-shard document boundaries published by setup_cp_params.
|
||||
hidden_states = mamba_cp_forward(
|
||||
self.mamba, hidden_states, self._cp_group, self._cp_rank, self._cp_world_size
|
||||
self.mamba,
|
||||
hidden_states,
|
||||
self._cp_group,
|
||||
self._cp_rank,
|
||||
self._cp_world_size,
|
||||
ULYSSES_PARAMS["cu_seqlens"],
|
||||
)
|
||||
else:
|
||||
hidden_states = self.mamba(hidden_states, cu_seqlens=cu_seqlens)
|
||||
|
||||
@@ -24,6 +24,7 @@ from prime_rl.trainer.models.layers.attn import (
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.moe import FeedForward, MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.rotary_emb import apply_rotary_pos_emb
|
||||
from prime_rl.trainer.models.layers.ulysses_attn import ULYSSES_PARAMS
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids, get_cu_seqlens_from_seq_lens
|
||||
|
||||
from .configuration_qwen3_5_moe import Qwen3_5MoeConfig
|
||||
@@ -43,6 +44,7 @@ except ImportError:
|
||||
|
||||
try:
|
||||
from fla.modules import FusedRMSNormGated
|
||||
from fla.modules.conv import causal_conv1d as fla_causal_conv1d
|
||||
from fla.ops.cp import FLACPContext, build_cp_context
|
||||
from fla.ops.gated_delta_rule import chunk_gated_delta_rule
|
||||
except ImportError:
|
||||
@@ -50,6 +52,7 @@ except ImportError:
|
||||
FusedRMSNormGated = None # type: ignore
|
||||
FLACPContext = None # type: ignore
|
||||
build_cp_context = None # type: ignore
|
||||
fla_causal_conv1d = None # type: ignore
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
@@ -233,16 +236,16 @@ class Qwen3_5MoeGatedDeltaNet(nn.Module):
|
||||
self._causal_conv1d_fn = causal_conv1d_fn
|
||||
self._chunk_gated_delta_rule = chunk_gated_delta_rule or torch_chunk_gated_delta_rule
|
||||
|
||||
def _build_cp_context(self, local_seq_len: int, device: torch.device) -> "FLACPContext | None":
|
||||
"""Build fla CP context from the local (sharded) sequence length."""
|
||||
def _build_cp_context(self) -> "FLACPContext | None":
|
||||
"""Build fla CP context from the full pre-shard document boundaries."""
|
||||
cp_group = getattr(self, "cp_group", None)
|
||||
if cp_group is None or build_cp_context is None:
|
||||
return None
|
||||
# Reconstruct global cu_seqlens: single contiguous sequence across all CP ranks
|
||||
global_seq_len = local_seq_len * self.cp_world_size
|
||||
global_cu_seqlens = torch.tensor([0, global_seq_len], dtype=torch.int32, device=device)
|
||||
# Local cu_seqlens cannot describe documents straddling shard boundaries;
|
||||
# use the full (un-sharded) cu_seqlens published by setup_cp_params. fla
|
||||
# derives per-rank boundaries and document-aware state passing from them.
|
||||
return build_cp_context(
|
||||
cu_seqlens=global_cu_seqlens,
|
||||
cu_seqlens=ULYSSES_PARAMS["cu_seqlens"],
|
||||
group=cp_group,
|
||||
conv1d_kernel_size=self.conv_kernel_size,
|
||||
)
|
||||
@@ -259,9 +262,23 @@ class Qwen3_5MoeGatedDeltaNet(nn.Module):
|
||||
b = self.in_proj_b(hidden_states)
|
||||
a = self.in_proj_a(hidden_states)
|
||||
|
||||
cp_context = self._build_cp_context()
|
||||
|
||||
# Causal conv1d — must reset at sequence boundaries for packed batches,
|
||||
# otherwise the kernel-1 left pad leaks state across sequences.
|
||||
if self._causal_conv1d_fn is not None:
|
||||
if cp_context is not None:
|
||||
# fla's CP conv resets at the true document boundaries and exchanges
|
||||
# tail tokens with the previous rank for documents straddling the
|
||||
# shard boundary; the local cu_seqlens can express neither.
|
||||
conv_out, _ = fla_causal_conv1d(
|
||||
x=mixed_qkv.transpose(1, 2),
|
||||
weight=self.conv1d.weight.squeeze(1),
|
||||
bias=self.conv1d.bias,
|
||||
activation=self.activation,
|
||||
cp_context=cp_context,
|
||||
)
|
||||
mixed_qkv = conv_out.transpose(1, 2)
|
||||
elif self._causal_conv1d_fn is not None:
|
||||
seq_idx = None
|
||||
if cu_seqlens is not None:
|
||||
seg_lens = cu_seqlens[1:] - cu_seqlens[:-1]
|
||||
@@ -303,7 +320,6 @@ class Qwen3_5MoeGatedDeltaNet(nn.Module):
|
||||
key = key.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
|
||||
|
||||
# Use fla's native CP when available, otherwise fall back to PyTorch kernel
|
||||
cp_context = self._build_cp_context(seq_len, hidden_states.device)
|
||||
if cp_context is not None:
|
||||
cu_seqlens = cp_context.cu_seqlens
|
||||
core_attn_out, _ = self._chunk_gated_delta_rule(
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import copy
|
||||
import time
|
||||
from typing import Callable
|
||||
|
||||
import torch
|
||||
@@ -12,7 +11,6 @@ from prime_rl.configs.trainer import OptimizerConfig
|
||||
from prime_rl.trainer.parallel_dims import ParallelDims
|
||||
from prime_rl.trainer.runs import get_multi_run_manager
|
||||
from prime_rl.trainer.sign_sgd import SignSGD
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
@@ -121,14 +119,7 @@ def setup_optimizer(
|
||||
# Wait for run 0 to be created in the multi run manager
|
||||
# Otherwise, the creation will reset the parameters
|
||||
multi_run_manager = get_multi_run_manager()
|
||||
world = get_world()
|
||||
logger = get_logger()
|
||||
while 0 not in multi_run_manager.idx_2_id:
|
||||
if world.is_master:
|
||||
multi_run_manager.discover_runs()
|
||||
multi_run_manager.synchronize_state()
|
||||
logger.info(f"Waiting for run 0 to be created {multi_run_manager.id_2_idx=}")
|
||||
time.sleep(1)
|
||||
multi_run_manager.wait_for_run(0)
|
||||
named_params = multi_run_manager.get_named_parameters_for_run(0)
|
||||
|
||||
optimizer = _create_optimizer(config, named_params, parallel_dims)
|
||||
|
||||
@@ -255,6 +255,7 @@ def train(config: TrainerConfig):
|
||||
logger.info(f"Tracing to {config.trace_path}")
|
||||
prof = profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA], record_shapes=True).__enter__()
|
||||
maybe_record_function = record_function
|
||||
start_step = progress.step
|
||||
while True:
|
||||
# Reset peak memory stats
|
||||
torch.cuda.reset_peak_memory_stats()
|
||||
@@ -265,6 +266,18 @@ def train(config: TrainerConfig):
|
||||
logger.debug(f"Starting training step {progress.step}")
|
||||
step_start_time = time.perf_counter()
|
||||
|
||||
# Broadcast the incoming policy (v{progress.step-1}) before waiting for its rollouts. #2896
|
||||
# broadcasts at the END of a step, so the first step would otherwise block on rollouts the
|
||||
# inference engines cannot produce until they receive v{progress.step-1} (the orchestrator
|
||||
# pauses inference at startup to sync it). This happens whether resuming (v{checkpoint_step})
|
||||
# or starting fresh (v0), keeping trainer and orchestrator startup symmetric.
|
||||
if progress.step == start_step and weight_broadcast is not None:
|
||||
logger.info(f"Broadcasting startup policy weights (v{progress.step - 1}) to inference engines")
|
||||
multi_run_manager.wait_for_run(0)
|
||||
for idx in multi_run_manager.used_idxs:
|
||||
multi_run_manager.ready_to_update[idx] = True
|
||||
weight_broadcast.broadcast_weights(model, step=progress.step - 1)
|
||||
|
||||
# Wait for the batch to be available
|
||||
logger.debug("Waiting for training batch to arrive")
|
||||
wait_for_batch_start_time = time.perf_counter()
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import pickle
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Callable, Optional
|
||||
@@ -463,6 +464,20 @@ class MultiRunManager:
|
||||
# Properties and Accessors
|
||||
# =========================================================================
|
||||
|
||||
def wait_for_run(self, idx: int = 0, poll_interval: float = 1.0) -> None:
|
||||
"""Block until run ``idx`` is registered. Master discovers from disk; all ranks synchronize.
|
||||
|
||||
Runs are otherwise only discovered during batch collection (``packer.discover_runs``), so
|
||||
callers that need a run before the first batch (optimizer setup, first-step weight sync)
|
||||
use this to populate ``idx_2_id``/``used_idxs``.
|
||||
"""
|
||||
while idx not in self.idx_2_id:
|
||||
if self.world.is_master:
|
||||
self.discover_runs()
|
||||
self.synchronize_state()
|
||||
self.logger.info(f"Waiting for run {idx} to be created ({self.id_2_idx=})")
|
||||
time.sleep(poll_interval)
|
||||
|
||||
@property
|
||||
def used_idxs(self):
|
||||
return sorted(self.idx_2_id.keys())
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import sys
|
||||
import types
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from prime_rl.trainer.models.layers import cp_mamba
|
||||
|
||||
|
||||
class _FakeMixer(torch.nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.intermediate_size = 1
|
||||
self.conv_dim = 3
|
||||
self.num_heads = 1
|
||||
self.n_groups = 1
|
||||
self.ssm_state_size = 1
|
||||
self.head_dim = 1
|
||||
self.chunk_size = 1
|
||||
self.time_step_limit = None
|
||||
self.variance_epsilon = 1e-5
|
||||
|
||||
self.in_proj = torch.nn.Linear(1, 5, bias=False)
|
||||
self.in_proj.weight.data.copy_(torch.tensor([[1.0], [1.0], [1.0], [1.0], [1.0]]))
|
||||
self.A_log = torch.nn.Parameter(torch.zeros(1))
|
||||
self.D = torch.nn.Parameter(torch.ones(1))
|
||||
self.dt_bias = torch.nn.Parameter(torch.zeros(1))
|
||||
self.conv1d = torch.nn.Conv1d(3, 3, kernel_size=2, groups=3, bias=False)
|
||||
self.conv1d.weight.data.fill_(1.0)
|
||||
self.norm = types.SimpleNamespace(weight=torch.ones(1), variance_epsilon=self.variance_epsilon, group_size=1)
|
||||
self.out_proj = torch.nn.Identity()
|
||||
|
||||
|
||||
def _install_fake_scan(monkeypatch, seen_seq_idx: list[torch.Tensor]) -> None:
|
||||
def fake_scan(hidden_states, time_step, A, B, C, **kwargs):
|
||||
assert kwargs["return_final_states"] is False
|
||||
seen_seq_idx.append(kwargs["seq_idx"].clone())
|
||||
return hidden_states
|
||||
|
||||
ssd_combined = types.ModuleType("mamba_ssm.ops.triton.ssd_combined")
|
||||
ssd_combined.mamba_chunk_scan_combined = fake_scan
|
||||
monkeypatch.setitem(sys.modules, "mamba_ssm", types.ModuleType("mamba_ssm"))
|
||||
monkeypatch.setitem(sys.modules, "mamba_ssm.ops", types.ModuleType("mamba_ssm.ops"))
|
||||
monkeypatch.setitem(sys.modules, "mamba_ssm.ops.triton", types.ModuleType("mamba_ssm.ops.triton"))
|
||||
monkeypatch.setitem(sys.modules, "mamba_ssm.ops.triton.ssd_combined", ssd_combined)
|
||||
|
||||
|
||||
def test_mamba_cp_forward_resets_conv_and_scan_at_packed_boundaries(monkeypatch):
|
||||
"""Changing document A must not change document B under Ulysses CP."""
|
||||
seen_seq_idx: list[torch.Tensor] = []
|
||||
_install_fake_scan(monkeypatch, seen_seq_idx)
|
||||
monkeypatch.setattr(cp_mamba, "seq_to_head_parallel", lambda value, *_: value)
|
||||
monkeypatch.setattr(cp_mamba, "head_to_seq_parallel", lambda value, *_: value)
|
||||
|
||||
mixer = _FakeMixer()
|
||||
cu_seqlens = torch.tensor([0, 2, 4], dtype=torch.int32)
|
||||
first = torch.tensor([[[1.0], [2.0], [3.0], [4.0]]])
|
||||
second = first.clone()
|
||||
second[0, 1, 0] = 200.0
|
||||
|
||||
first_out = cp_mamba.mamba_cp_forward(mixer, first, None, 0, 1, cu_seqlens)
|
||||
second_out = cp_mamba.mamba_cp_forward(mixer, second, None, 0, 1, cu_seqlens)
|
||||
|
||||
assert torch.equal(seen_seq_idx[0], torch.tensor([[0, 0, 1, 1]], dtype=torch.int32))
|
||||
assert torch.equal(seen_seq_idx[1], seen_seq_idx[0])
|
||||
torch.testing.assert_close(first_out[:, 2:], second_out[:, 2:])
|
||||
|
||||
|
||||
def test_mamba_cp_forward_rejects_local_boundaries():
|
||||
with pytest.raises(ValueError, match="full sequence length 4"):
|
||||
cp_mamba._build_seq_idx([0, 2], 4, torch.device("cpu"))
|
||||
Reference in New Issue
Block a user