Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0164aab72c | ||
|
|
243cfba0fb | ||
|
|
9ff04f56bf | ||
|
|
afe37d1c7a | ||
|
|
ecbf3e657f | ||
|
|
23017482f9 |
@@ -146,7 +146,7 @@ uv run inference --vllm.model Qwen/Qwen3-0.6B
|
||||
5. Check that the full RL stack (inference + orchestrator + trainer) runs end-to-end (*this requires 2 GPUs*)
|
||||
|
||||
```bash
|
||||
uv run rl @ configs/basic/reverse-text/rl.toml
|
||||
uv run rl @ examples/basic/reverse-text/rl.toml
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
+3
-8
@@ -2,24 +2,19 @@
|
||||
|
||||
Configurations for running prime-rl.
|
||||
|
||||
- **[`basic/`](basic)** — small, 2-GPU (1 trainer + 1 inference) configs for the core
|
||||
environments, sized to run on a single dev machine. Each mirrors the matching
|
||||
[`examples/basic/`](../examples/basic) tutorial and is smoke-tested for one step.
|
||||
Envs: `reverse-text`, `alphabet-sort`, `wiki-search`, `wordle`, `hendrycks-sanity`.
|
||||
- **[`advanced/`](advanced)** — frontier-model training configs without launch walkthroughs:
|
||||
`minimax-m2.5` (swe), `nemotron-3-super` (swe), `deepseek-v4-flash` (sft + a standalone
|
||||
vLLM serving pre-flight). For the tutorialized equivalents, see
|
||||
[`examples/advanced/`](../examples/advanced).
|
||||
- **`ci/`** — integration and nightly configs used by CI.
|
||||
- **`debug/`** — throwaway configs for developing the framework itself: `algo/`
|
||||
(per-algorithm smokes), `fake/` (fake-data trainer/SFT smokes), `multi-env/`
|
||||
(two reverse-text train sources + one eval source, one env server per source), and
|
||||
(per-algorithm smokes), `fake/` (fake-data trainer/SFT smokes), and
|
||||
`eval/` (`uv run eval` smokes against Prime Inference, one per shape: `single-turn`
|
||||
(gsm8k), `multi-turn` (terminal-bench-2 fix-git in sandboxes against a local vLLM deployment with the adaptive band), `resume`, `multi-env`).
|
||||
Not guaranteed functional or up to date.
|
||||
|
||||
```bash
|
||||
uv run rl @ configs/basic/<env>/rl.toml
|
||||
uv run sft @ configs/basic/<env>/sft.toml # where present
|
||||
uv run rl @ configs/debug/algo/<algo>.toml
|
||||
uv run sft @ configs/debug/fake/sft.toml
|
||||
uv run eval @ configs/debug/eval/<shape>.toml
|
||||
```
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
# alphabet-sort (2 GPU)
|
||||
|
||||
Multi-turn task driven by a colocated user simulator, LoRA on `Qwen3-4B`. Dev mirror of
|
||||
[`examples/basic/alphabet-sort`](../../../examples/basic/alphabet-sort).
|
||||
|
||||
```bash
|
||||
uv run rl @ configs/basic/alphabet-sort/rl.toml
|
||||
```
|
||||
@@ -1,48 +0,0 @@
|
||||
# Alphabet-sort on 2 GPUs (1 trainer + 1 inference) — a multi-turn task driven by a colocated
|
||||
# user simulator, trained with LoRA on Qwen3-4B. Dev-sized mirror of examples/basic/alphabet-sort.
|
||||
|
||||
max_steps = 200
|
||||
seq_len = 2048
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 1
|
||||
num_infer_gpus = 1
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[monitors.wandb]
|
||||
project = "alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[trainer.model.lora]
|
||||
rank = 32
|
||||
alpha = 64
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-5
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
|
||||
[orchestrator.train]
|
||||
group_size = 8
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 768
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "alphabet-sort"
|
||||
env.taskset.id = "alphabet-sort"
|
||||
env.taskset.min_turns = 3
|
||||
env.taskset.max_turns = 5
|
||||
env.taskset.task.power_per_turn = false
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
[inference]
|
||||
@@ -1,9 +0,0 @@
|
||||
# hendrycks-sanity (2 GPU)
|
||||
|
||||
Single-turn math sanity run (reward climbs slowly, meant to run long),
|
||||
`DeepSeek-R1-Distill-Qwen-1.5B`. Dev mirror of
|
||||
[`examples/basic/hendrycks-sanity`](../../../examples/basic/hendrycks-sanity).
|
||||
|
||||
```bash
|
||||
uv run rl @ configs/basic/hendrycks-sanity/rl.toml
|
||||
```
|
||||
@@ -1,39 +0,0 @@
|
||||
# Hendrycks-math sanity on 2 GPUs (1 trainer + 1 inference) — a single-turn math env meant to
|
||||
# run long (reward climbs slowly). Dev-sized mirror of examples/basic/hendrycks-sanity.
|
||||
|
||||
max_steps = 5000
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 1
|
||||
num_infer_gpus = 1
|
||||
|
||||
[model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
|
||||
[monitors.wandb]
|
||||
project = "hendrycks-sanity"
|
||||
name = "hendrycks-sanity"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
seq_len = 8192
|
||||
|
||||
[orchestrator.train]
|
||||
group_size = 8
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "hendrycks-math"
|
||||
env.taskset.id = "math-env"
|
||||
env.taskset.dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
|
||||
env.taskset.dataset_subset = "default"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.model]
|
||||
seq_len = 16384
|
||||
|
||||
[inference.vllm]
|
||||
max_model_len = 8192
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
reasoning_parser = "think"
|
||||
@@ -1,9 +0,0 @@
|
||||
# reverse-text (2 GPU)
|
||||
|
||||
Smallest end-to-end RL loop — single-turn, `Qwen3-0.6B`. Dev mirror of
|
||||
[`examples/basic/reverse-text`](../../../examples/basic/reverse-text).
|
||||
|
||||
```bash
|
||||
uv run sft @ configs/basic/reverse-text/sft.toml # optional warmup
|
||||
uv run rl @ configs/basic/reverse-text/rl.toml
|
||||
```
|
||||
@@ -1,43 +0,0 @@
|
||||
# Reverse-text on 2 GPUs (1 trainer + 1 inference) — the smallest end-to-end RL loop
|
||||
# (single-turn, 0.6B). Dev-sized mirror of examples/basic/reverse-text.
|
||||
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 1
|
||||
num_infer_gpus = 1
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[monitors.wandb]
|
||||
project = "reverse-text"
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
|
||||
[orchestrator.train]
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
[inference]
|
||||
|
||||
# PrimeIntellect Qwen3 fine-tune - select its renderer explicitly (the -SFT
|
||||
# suffix misses the MODEL_RENDERER_MAP exact match).
|
||||
[orchestrator.renderer]
|
||||
name = "prime-qwen3"
|
||||
@@ -1,38 +0,0 @@
|
||||
# SFT warmup for reverse-text on 2 GPUs (1 train + 1 infer for online evals).
|
||||
# Dev-sized mirror of examples/basic/reverse-text/sft.toml.
|
||||
|
||||
max_steps = 100
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 1
|
||||
num_infer_gpus = 1
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B"
|
||||
|
||||
[data]
|
||||
name = "willcb/R1-reverse-wikipedia-paragraphs-v1-1000"
|
||||
seq_len = 4096
|
||||
batch_size = 32
|
||||
|
||||
[optim]
|
||||
lr = 2e-5
|
||||
|
||||
[eval]
|
||||
interval = 25
|
||||
|
||||
[eval.select]
|
||||
limit = 32
|
||||
|
||||
[eval.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
[[eval.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[inference]
|
||||
@@ -1,8 +0,0 @@
|
||||
# wiki-search (2 GPU)
|
||||
|
||||
Multi-turn tool calling (search a wiki corpus via native V1 tools), LoRA on `Qwen3-4B`. Dev mirror
|
||||
of [`examples/basic/wiki-search`](../../../examples/basic/wiki-search).
|
||||
|
||||
```bash
|
||||
uv run rl @ configs/basic/wiki-search/rl.toml
|
||||
```
|
||||
@@ -1,54 +0,0 @@
|
||||
# Wiki-search on 2 GPUs (1 trainer + 1 inference) — a multi-turn tool-calling task (the model
|
||||
# searches a wiki corpus via MCP tools), trained with LoRA on Qwen3-4B. Dev-sized mirror of
|
||||
# examples/basic/wiki-search.
|
||||
|
||||
max_steps = 200
|
||||
seq_len = 4096
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 1
|
||||
num_infer_gpus = 1
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[monitors.wandb]
|
||||
project = "wiki-search"
|
||||
name = "wiki-search"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-5
|
||||
weight_decay = 0.0
|
||||
|
||||
[trainer.model.lora]
|
||||
rank = 8
|
||||
dropout = 0.0
|
||||
target_modules = [
|
||||
"q_proj",
|
||||
"k_proj",
|
||||
"v_proj",
|
||||
"o_proj",
|
||||
"gate_proj",
|
||||
"up_proj",
|
||||
"down_proj",
|
||||
]
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
|
||||
[orchestrator.train]
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "wiki-search"
|
||||
env.taskset.id = "wiki-search"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
[inference.vllm]
|
||||
tool_call_parser = "hermes"
|
||||
@@ -1,9 +0,0 @@
|
||||
# wordle (2 GPU)
|
||||
|
||||
Multi-turn Wordle (~6-turn games), `Qwen3-1.7B-Wordle-SFT`. Dev mirror of
|
||||
[`examples/basic/wordle`](../../../examples/basic/wordle).
|
||||
|
||||
```bash
|
||||
uv run sft @ configs/basic/wordle/sft.toml # optional warmup
|
||||
uv run rl @ configs/basic/wordle/rl.toml
|
||||
```
|
||||
@@ -1,41 +0,0 @@
|
||||
# Wordle on 2 GPUs (1 trainer + 1 inference). The Wordle-SFT model plays a
|
||||
# full ~6-turn game per rollout.
|
||||
|
||||
max_steps = 200
|
||||
seq_len = 8192
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 1
|
||||
num_infer_gpus = 1
|
||||
|
||||
[monitors.wandb]
|
||||
project = "wordle"
|
||||
name = "wordle"
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
|
||||
[orchestrator.train]
|
||||
group_size = 8
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "wordle"
|
||||
env.taskset.id = "wordle"
|
||||
env.player.harness.id = "null"
|
||||
env.player.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
[trainer] # Default trainer config
|
||||
|
||||
[inference] # single inference GPU (no data parallelism)
|
||||
|
||||
# Fine-tune inherits the PrimeIntellect Qwen3 template byte-for-byte.
|
||||
[orchestrator.renderer]
|
||||
name = "prime-qwen3"
|
||||
@@ -1,20 +0,0 @@
|
||||
# SFT warmup for wordle on 2 GPUs. Dev-sized mirror of examples/basic/wordle/sft.toml.
|
||||
|
||||
max_steps = 20
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 2
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-1.7B"
|
||||
|
||||
[data]
|
||||
name = "willcb/V3-wordle"
|
||||
seq_len = 1024
|
||||
batch_size = 64
|
||||
micro_batch_size = 1
|
||||
|
||||
[optim]
|
||||
lr = 1e-5
|
||||
@@ -1,141 +0,0 @@
|
||||
# Concurrency-controller debug run: GLM-4.5-Air on the v1 `scaleswe` SWE taskset,
|
||||
# bash harness on a prime sandbox runtime, 1 train + 1 infer node, eval on 100
|
||||
# SWE-Bench Verified instances. Concurrency is fully default: the controller
|
||||
# derives its start from the measured KV budget and adapts from there — watch
|
||||
# the concurrency/* gauges in W&B or the "Concurrency ..." lines in the
|
||||
# orchestrator log.
|
||||
#
|
||||
# Inference serves FP8 via online per-tensor quantization of the bf16
|
||||
# checkpoint; weight broadcasts re-quantize through the same path on every
|
||||
# update. The trainer fits on one node via cp=4 (ulysses), full CPU optimizer
|
||||
# offload with the stateless sign-SGD optimizer, plus the memory improvements
|
||||
# from the GLM-5.1 prod run: LM-head token chunking, activation checkpointing
|
||||
# (freq=1) + activation offloading (max_inflight=1), and skip-gather /
|
||||
# skip-optimizer checkpointing. Router replay is enabled — GLM-4.5-Air is a
|
||||
# glm4_moe model, which supports routed_experts.
|
||||
#
|
||||
# GRPO uses the linear length penalty with the input-token and turns
|
||||
# coefficients set to 0.1.
|
||||
|
||||
max_steps = 1000
|
||||
seq_len = 131072
|
||||
|
||||
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
|
||||
# slow/contended shared-FS caches and FS lock deadlocks.
|
||||
[env_vars]
|
||||
TRITON_CACHE_DIR = "/tmp/.triton-cache"
|
||||
|
||||
[slurm]
|
||||
job_name = "debug-concurrency"
|
||||
partition = "all"
|
||||
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
|
||||
pre_run_command = 'timeout 120 prime sandbox delete --label "debug-concurrency" -y || true'
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 1
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 1
|
||||
|
||||
[monitors.wandb]
|
||||
project = "swe-ablations"
|
||||
name = "debug-concurrency"
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
|
||||
[resume]
|
||||
|
||||
# --- Trainer ---
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 3600
|
||||
enable_router_replay = true
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-4.5-Air"
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
cp = 4
|
||||
cp_style = "ulysses"
|
||||
optim_cpu_offload = false
|
||||
full_offload = true
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
|
||||
[trainer.model.ac]
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
type = "sign_sgd"
|
||||
|
||||
# --- Orchestrator ---
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
max_off_policy_steps = 32
|
||||
|
||||
[orchestrator.train]
|
||||
group_size = 8
|
||||
|
||||
[orchestrator.train.algo]
|
||||
type = "grpo"
|
||||
|
||||
[orchestrator.train.algo.length_penalty]
|
||||
type = "linear"
|
||||
num_output_tokens_weight = 0.0
|
||||
num_input_tokens_weight = 0.1
|
||||
num_turns_weight = 0.1
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "glm-4.5"
|
||||
thinking_retention = "all"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "scaleswe"
|
||||
env.taskset.id = "scaleswe"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["debug-concurrency"]
|
||||
|
||||
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, rlm harness on prime ---
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swebench-verified"
|
||||
select.limit = 100
|
||||
env.taskset.id = "swebench-verified"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["debug-concurrency"]
|
||||
env.agent.timeout.rollout = 3600
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.vllm]
|
||||
max_model_len = 131072
|
||||
tensor_parallel_size = 8
|
||||
quantization = "fp8_per_block"
|
||||
enable_return_routed_experts = true
|
||||
@@ -1,55 +0,0 @@
|
||||
# Minimal multi-env debug run: two reverse-text train sources + one eval source.
|
||||
# The launcher spawns one env server per source at its derived address
|
||||
# (each on an OS-assigned loopback port it publishes); the orchestrator connects to each.
|
||||
max_steps = 10
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
|
||||
[orchestrator.train]
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "prime-qwen3"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text-a"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text-b"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 5
|
||||
|
||||
[orchestrator.eval.select]
|
||||
limit = 64
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[inference]
|
||||
|
||||
[inference.vllm]
|
||||
gpu_memory_utilization = 0.5
|
||||
Vendored
+1
-1
Submodule deps/prime-kernels updated: 3fb83eb7aa...6f481769ca
+1
-1
@@ -137,7 +137,7 @@ With DeepEP, gradient clipping is currently not supported. (`optim.max_norm` is
|
||||
enabled = ["gate_up", "qkv"] # [] disables
|
||||
```
|
||||
|
||||
Fusions are runtime-only. Checkpoints keep the canonical parameter names and shapes, so a run can turn a fusion on or off at any point and still load its own checkpoints, and exported weights are unaffected. Only modules that support a fusion are packed; a requested fusion that no module supports logs a warning, or fails at startup with `raise_on_fail = true`. Fusions are skipped when LoRA is enabled.
|
||||
Fusions are runtime-only. Checkpoints keep the canonical parameter names and shapes, so a run can turn a fusion on or off at any point and still load its own checkpoints, and exported weights are unaffected. Only modules that support a fusion are packed; a requested fusion that no module supports logs a warning and is skipped. Fusions are skipped when LoRA is enabled.
|
||||
|
||||
Muon receives the packed layout as matrix partitions and orthogonalizes each logical matrix on its own, so a packed parameter trains exactly as the parameters it replaces would — including per-projection learning-rate scaling for grouped-query attention — while keeping a single momentum tensor.
|
||||
|
||||
|
||||
@@ -35,4 +35,3 @@ Examples that don't follow the basic eval → SFT → RL walk-through pattern:
|
||||
## Related config folders
|
||||
|
||||
- Frontier-model configs without launch walkthroughs (`minimax-m2.5`, `nemotron-3-super`, `deepseek-v4-flash`) live in [`configs/advanced/`](../configs/advanced).
|
||||
- Dev-sized (2-GPU) counterparts of `basic/` live in [`configs/basic/`](../configs/basic).
|
||||
|
||||
@@ -15,3 +15,5 @@ uv run rl @ examples/basic/hendrycks-sanity/rl.toml \
|
||||
--monitors.wandb.project your-project \
|
||||
--monitors.wandb.name your-run
|
||||
```
|
||||
|
||||
To run on 2 GPUs (1 inference, 1 trainer), add `--deployment.num-train-gpus 1 --deployment.num-infer-gpus 1 --orchestrator.batch-size 128`.
|
||||
|
||||
@@ -9,7 +9,7 @@ In this example, we demonstrate how to train `Qwen3-4B-Instruct-2507` to answer
|
||||
- **LLM judges**: Uses an LLM judge to evaluate answer quality alongside tool execution metrics
|
||||
- **Online difficulty buffer**: Uses difficulty-based sampling to ensure rollouts have strictly non-zero advantages
|
||||
|
||||
> This example runs on 8 GPUs (6 for inference, 2 for training).
|
||||
> This example runs on 8 GPUs (6 for inference, 2 for training). To run on 2 GPUs (1 inference, 1 trainer), add `--deployment.num-train-gpus 1 --deployment.num-infer-gpus 1 --orchestrator.batch-size 128` to the `rl` command.
|
||||
|
||||
## Setup
|
||||
|
||||
|
||||
@@ -82,6 +82,8 @@ uv run rl @ examples/basic/wordle/rl.toml \
|
||||
--monitors.wandb.name ...
|
||||
```
|
||||
|
||||
This config runs on 8 GPUs (6 for inference, 2 for training). To run on 2 GPUs (1 inference, 1 trainer), add `--deployment.num-train-gpus 1 --deployment.num-infer-gpus 1 --orchestrator.batch-size 128`.
|
||||
|
||||
This will write a DCP checkpoint in `outputs/rl/checkpoints/step_100`.
|
||||
|
||||
We have uploaded the final model as [`PrimeIntellect/Qwen3-1.7B-Wordle-RL`](https://huggingface.co/PrimeIntellect/Qwen3-1.7B-Wordle-RL).
|
||||
|
||||
@@ -61,9 +61,6 @@ class OptimizerInBackwardOffloadConfig(BaseConfig):
|
||||
bit-faithful to that path, disable offloading.
|
||||
"""
|
||||
|
||||
cpu_optimizer_backend: Literal["native", "torch"] = "native"
|
||||
"""CPU optimizer implementation used by full offload (AdamW or SignSGD). ``native`` is the production kernel; ``torch`` is a slower debugging and parity fallback."""
|
||||
|
||||
numa_bind: bool = True
|
||||
"""Pin each rank's CPUs to its GPU's NUMA node. Disable when the launcher already manages CPU affinity or GPU sysfs topology is unavailable."""
|
||||
|
||||
@@ -93,9 +90,6 @@ class FusionsConfig(BaseConfig):
|
||||
enabled: list[Literal["gate_up", "qkv"]] = ["gate_up", "qkv"]
|
||||
"""Runtime parameter fusions. ``gate_up`` runs each MoE expert's gate and up projections as one grouped GEMM; ``qkv`` runs attention's q, k and v projections as one GEMM. Only modules that support a fusion are packed, checkpoints keep the canonical parameter names and shapes, and fusions are skipped when LoRA is enabled. Set to ``[]`` to disable."""
|
||||
|
||||
raise_on_fail: bool = False
|
||||
"""Fail at startup when no module supports a requested fusion, instead of logging a warning and continuing without it."""
|
||||
|
||||
shard_fused_on_dim1: bool = False
|
||||
"""Experimental. Shard fused 2-D weights along dim 1 under FSDP so that weight loading and checkpointing are zero-copy: the checkpoint reads and writes the fused weights and their optimizer state in place, instead of assembling a full copy of every fused weight on each rank first. Requires the hidden size to be divisible by the FSDP shard mesh size."""
|
||||
|
||||
|
||||
+2
-2
@@ -290,8 +290,8 @@ deep-gemm = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
prime-kernels = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.0-6f48176/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.0-6f48176/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
flash-linear-attention = { git = "https://github.com/fla-org/flash-linear-attention" }
|
||||
mamba-ssm = { git = "https://github.com/state-spaces/mamba", rev = "f577286" }
|
||||
|
||||
@@ -31,7 +31,7 @@ SLURM launches write generated scripts and coordination files under `<run_dir>/l
|
||||
`model.optim_cpu_offload = false` and `model.full_offload = true`. This mode uses the native
|
||||
CPU optimizer kernel, only supports AdamW and SignSGD (SignSGD is stateless and
|
||||
halves the host RAM footprint), and disables gradient clipping. Use a
|
||||
`[model.full_offload]` table only to select the Torch debugging backend or disable NUMA binding.
|
||||
`[model.full_offload]` table only to disable NUMA binding.
|
||||
|
||||
## `rl` — RL training
|
||||
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
import os
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
def apply_shared_vllm_patches():
|
||||
"""vLLM general plugin: prime-rl patches that must run in every vLLM process.
|
||||
"""vLLM general plugin and the single place prime-rl applies its vLLM patches; vLLM runs it once in every process.
|
||||
|
||||
Registered as a ``vllm.general_plugins`` entry-point so it runs automatically
|
||||
in every vLLM process, including spawned workers. Note vLLM swallows plugin
|
||||
load failures (``load_plugins_by_group`` logs and continues), so a broken
|
||||
vLLM swallows plugin load failures (``load_plugins_by_group`` logs and continues), so a broken
|
||||
entry-point target silently skips ALL of these patches.
|
||||
"""
|
||||
from prime_rl.inference.vllm.gpt_oss_weight_loading import patch_gpt_oss_weight_loading
|
||||
from prime_rl.inference.vllm.qwen38_weight_loading import patch_qwen38_weight_loading
|
||||
|
||||
patch_gpt_oss_weight_loading()
|
||||
patch_qwen38_weight_loading()
|
||||
_patch_lora_key_prefix()
|
||||
_patch_qwen35_moe_lora_format()
|
||||
monkey_patch_nano_v3_reasoning_parser()
|
||||
@@ -21,6 +23,13 @@ def apply_shared_vllm_patches():
|
||||
monkey_patch_online_fp8_parameter_cast()
|
||||
monkey_patch_deepseek_v4_allowed_layer_types()
|
||||
monkey_patch_deepseek_v4_request_tools_placement()
|
||||
monkey_patch_tokenize_params_validation()
|
||||
monkey_patch_strip_routed_experts_from_chat()
|
||||
monkey_patch_dp_coordinator_startup_timeout()
|
||||
monkey_patch_minimax_m2_for_lora()
|
||||
# Set by `server()` when the LoRA target modules include no expert layers.
|
||||
if os.environ.get("PRIME_NO_MOE_LORA") == "1":
|
||||
monkey_patch_no_moe_lora()
|
||||
|
||||
|
||||
def monkey_patch_deepseek_v4_allowed_layer_types():
|
||||
@@ -574,8 +583,8 @@ def monkey_patch_minimax_m2_for_lora():
|
||||
"""Patch vLLM's MiniMaxM2 model for LoRA compatibility.
|
||||
|
||||
These patches are only needed when using LoRA with MiniMax M2 but are safe
|
||||
to apply unconditionally (verified with non-LoRA runs). We apply them at
|
||||
import time because the worker __init__ runs before the vLLM config is
|
||||
to apply unconditionally (verified with non-LoRA runs). We apply them
|
||||
unconditionally because the vLLM plugin runs before the vLLM config is
|
||||
available, so we can't check if LoRA is enabled.
|
||||
|
||||
Problem 1 — Gate dtype mismatch:
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import re
|
||||
from collections.abc import Iterable
|
||||
from functools import wraps
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
def patch_qwen38_weight_loading() -> None:
|
||||
"""Skip nonlocal PLE checkpoint pieces before vLLM buffers parameter loads.
|
||||
|
||||
Remove when vLLM's Qwen4ExpNGramEmbedding.load_weights checks TP overlap
|
||||
before calling the embedding parameter's weight_loader.
|
||||
"""
|
||||
from vllm.models.qwen4_exp.common.ple import compute_ple_shard_overlap
|
||||
from vllm.models.qwen4_exp.nvidia.ngram_embedding import Qwen4ExpNGramEmbedding
|
||||
|
||||
original_load_weights = Qwen4ExpNGramEmbedding.load_weights
|
||||
if getattr(original_load_weights, "_prime_rl_filters_ple_shards", False):
|
||||
return
|
||||
|
||||
@wraps(original_load_weights)
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
embedding = self.ngram_embedding
|
||||
shard_size = (embedding.org_vocab_size + self.split_ngram_parts - 1) // self.split_ngram_parts
|
||||
skipped: set[str] = set()
|
||||
|
||||
def local_weights():
|
||||
for name, weight in weights:
|
||||
match = re.fullmatch(r"ngram_embedding\.shard_(\d+)\.weight", name)
|
||||
if match is not None:
|
||||
shard_index = int(match[1])
|
||||
checkpoint_start = shard_index * shard_size
|
||||
expected_rows = max(0, min(shard_size, embedding.org_vocab_size - checkpoint_start))
|
||||
# Leave malformed shards to the original loader's validation.
|
||||
if shard_index < self.split_ngram_parts and weight.shape == (
|
||||
expected_rows,
|
||||
embedding.embedding_dim,
|
||||
):
|
||||
overlap = compute_ple_shard_overlap(
|
||||
checkpoint_start=checkpoint_start,
|
||||
checkpoint_rows=expected_rows,
|
||||
tp_start=embedding.shard_indices.org_vocab_start_index,
|
||||
tp_end=embedding.shard_indices.org_vocab_end_index,
|
||||
)
|
||||
if overlap is None:
|
||||
skipped.add("ngram_embedding.weight")
|
||||
continue
|
||||
yield name, weight
|
||||
|
||||
loaded = original_load_weights(self, local_weights())
|
||||
return loaded | skipped
|
||||
|
||||
load_weights._prime_rl_filters_ple_shards = True
|
||||
Qwen4ExpNGramEmbedding.load_weights = load_weights
|
||||
@@ -15,32 +15,6 @@ from vllm.logger import init_logger
|
||||
from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
logger = get_logger()
|
||||
from prime_rl.inference.patches import (
|
||||
monkey_patch_dp_coordinator_startup_timeout,
|
||||
monkey_patch_nano_v3_reasoning_parser,
|
||||
monkey_patch_strip_routed_experts_from_chat,
|
||||
monkey_patch_tokenize_params_validation,
|
||||
)
|
||||
|
||||
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
|
||||
# Still needed in vLLM 0.30 — upstream rejects prompt_len > max_model_len - max_tokens
|
||||
monkey_patch_tokenize_params_validation()
|
||||
# NOTE: Register Nano V3 reasoning parser so configs can use
|
||||
# `reasoning_parser = "nano_v3"` without a vLLM plugin file.
|
||||
monkey_patch_nano_v3_reasoning_parser()
|
||||
# NOTE: routed_experts are consumed only via the serialized /generate path (router
|
||||
# replay). The chat-completions path encodes them as a base64 np.save string the PD
|
||||
# router cannot merge, which fails eval rollouts (they use chat completions). Strip
|
||||
# routed_experts from chat responses since the server-wide enable flag has no
|
||||
# per-request toggle.
|
||||
monkey_patch_strip_routed_experts_from_chat()
|
||||
# NOTE: vLLM hard-codes a 120s DP coordinator startup timeout, which the rank-0
|
||||
# API server blows through when all engine-core ranks on the node are loading
|
||||
# weights concurrently (multi-node disaggregated deployments).
|
||||
monkey_patch_dp_coordinator_startup_timeout()
|
||||
|
||||
logger = init_logger("vllm.entrypoints.launchers.api_server.entry")
|
||||
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
import logging
|
||||
import os
|
||||
|
||||
from prime_rl.inference.patches import (
|
||||
monkey_patch_minimax_m2_for_lora,
|
||||
monkey_patch_no_moe_lora,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Monkeypatch MiniMaxM2 MoE gate dtype and adapter key mapping for LoRA compatibility
|
||||
monkey_patch_minimax_m2_for_lora()
|
||||
# Disable LoRA on MoE layers so vLLM picks better kernels (e.g. TRTLLMFlashInfer on Blackwell)
|
||||
if os.environ.get("PRIME_NO_MOE_LORA") == "1":
|
||||
logger.info("PRIME_NO_MOE_LORA=1: disabling LoRA on MoE layers")
|
||||
monkey_patch_no_moe_lora()
|
||||
else:
|
||||
logger.info("PRIME_NO_MOE_LORA=0: no patch applied")
|
||||
|
||||
@@ -8,7 +8,7 @@ from vllm.distributed.utils import StatelessProcessGroup
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from prime_rl.inference.vllm.worker.weight_transfer import load_weights_checkpoint_layerwise
|
||||
from prime_rl.utils.nccl import disable_nccl_p2p_if_unavailable
|
||||
from prime_rl.utils.nccl import disable_nccl_p2p_if_unavailable, iter_tensor_buckets
|
||||
|
||||
# This is to get type hints for the Worker class but not actually extend it at runtime as this is required by vLLM worker extension
|
||||
if TYPE_CHECKING:
|
||||
@@ -39,22 +39,24 @@ def receive_state_dict(communicator: PyNcclCommunicator) -> Generator[tuple[str,
|
||||
|
||||
# Receive concatenated tensors per dtype and split them back
|
||||
for dtype, tensor_info_list in metadata.items():
|
||||
# Receive concatenated tensor for this dtype
|
||||
total_elements = sum(numel for _, _, numel in tensor_info_list)
|
||||
concatenated = torch.empty(total_elements, dtype=dtype, device=communicator.device)
|
||||
communicator.broadcast(concatenated, src=0)
|
||||
for bucket in iter_tensor_buckets(tensor_info_list, dtype):
|
||||
# Receive concatenated tensor for this dtype
|
||||
total_elements = sum(numel for _, _, numel in bucket)
|
||||
concatenated = torch.empty(total_elements, dtype=dtype, device=communicator.device)
|
||||
if total_elements:
|
||||
communicator.broadcast(concatenated, src=0)
|
||||
|
||||
# Split concatenated tensor back into individual tensors
|
||||
offset = 0
|
||||
for key, shape, numel in tensor_info_list:
|
||||
tensor = concatenated[offset : offset + numel].view(shape)
|
||||
offset += numel
|
||||
try:
|
||||
yield key, tensor
|
||||
finally:
|
||||
del tensor
|
||||
# Split concatenated tensor back into individual tensors
|
||||
offset = 0
|
||||
for key, shape, numel in bucket:
|
||||
tensor = concatenated[offset : offset + numel].view(shape)
|
||||
offset += numel
|
||||
try:
|
||||
yield key, tensor
|
||||
finally:
|
||||
del tensor
|
||||
|
||||
del concatenated
|
||||
del concatenated
|
||||
|
||||
|
||||
class NCCLWeightBroadcastReceiver:
|
||||
|
||||
@@ -33,6 +33,7 @@ MANDATORY_SAVE_OPERATIONS = frozenset(
|
||||
{
|
||||
"aten::topk",
|
||||
"prime_rl::fp8_indexer",
|
||||
"prime_kernels::select_indexed_blocks",
|
||||
"prime_rl::record_moe_routing_statistics",
|
||||
}
|
||||
)
|
||||
@@ -73,6 +74,7 @@ DEFAULT_SELECTIVE_SAVE_OPERATIONS = frozenset(
|
||||
"quack::gemm_act_out",
|
||||
"quack::gemm_gated_out",
|
||||
"quack::gemm_out",
|
||||
"prime_kernels::indexed_attention_forward",
|
||||
}
|
||||
)
|
||||
# An operation target matches one qualified operator name, while a namespace
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import torch.distributed as dist
|
||||
import torch.nn.functional as F
|
||||
from torch.distributed.tensor import Shard
|
||||
from torch.distributed.tensor.parallel import RowwiseParallel
|
||||
|
||||
|
||||
class EmbeddingParallel(RowwiseParallel):
|
||||
"""Vocabulary-parallel embedding with uneven token batches on each rank."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__(input_layouts=Shard(0), output_layouts=Shard(0))
|
||||
|
||||
def _prepare_input_fn(self, input_layouts, desired_input_layouts, module, inputs, device_mesh):
|
||||
indices = inputs[0]
|
||||
self.local_tokens = indices.shape[0]
|
||||
max_tokens = indices.new_tensor(self.local_tokens)
|
||||
dist.all_reduce(max_tokens, op=dist.ReduceOp.MAX, group=device_mesh.get_group())
|
||||
# TODO: Avoid the D2H sync in max_tokens.item(); F.pad needs the dynamic
|
||||
# cross-rank token count on the host to size the padded tensor.
|
||||
indices = F.pad(indices, (0, 0, 0, max_tokens.item() - self.local_tokens))
|
||||
return super()._prepare_input_fn(input_layouts, desired_input_layouts, module, (indices,), device_mesh)
|
||||
|
||||
def _prepare_output_fn(self, output_layouts, use_local_output, module, outputs, device_mesh):
|
||||
output = super()._prepare_output_fn(output_layouts, use_local_output, module, outputs, device_mesh)
|
||||
return output[: self.local_tokens]
|
||||
@@ -22,6 +22,7 @@ from torch.distributed.fsdp import CPUOffloadPolicy, FSDPModule, MixedPrecisionP
|
||||
from torch.distributed.fsdp._fully_shard._fsdp_common import FSDPMeshInfo, ShardPlacementResult
|
||||
from torch.distributed.fsdp._fully_shard._fsdp_init import _get_mesh_info
|
||||
from torch.distributed.tensor import Shard
|
||||
from torch.distributed.tensor.parallel import parallelize_module
|
||||
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, GenerationConfig, PretrainedConfig
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
from transformers.utils.import_utils import is_flash_attn_3_available
|
||||
@@ -36,6 +37,7 @@ from prime_rl.configs.trainer import (
|
||||
)
|
||||
from prime_rl.multimodal import ForwardPolicy
|
||||
from prime_rl.trainer.activation_checkpointing import get_activation_checkpoint_wrapper
|
||||
from prime_rl.trainer.distributed.embedding_parallel import EmbeddingParallel
|
||||
from prime_rl.trainer.lora import apply_lora_to_model, freeze_all_except_lora_and_specified, strip_lora_from_state_dict
|
||||
from prime_rl.trainer.models import (
|
||||
AutoModelForCausalLMPrimeRL,
|
||||
@@ -57,6 +59,8 @@ from prime_rl.trainer.models.layers.fp8_linear import replace_linear_with_fp8_bl
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
from prime_rl.trainer.models.layers.moe import MoE, TokenChoiceTopKRouter
|
||||
from prime_rl.trainer.models.layers.mxfp8_linear import replace_linear_with_mxfp8_linear
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next.indexer import SparseAttentionIndexer
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next.ngram_embedding import NGramEmbedding
|
||||
from prime_rl.trainer.moe_runtime import configure_moe_runtime
|
||||
from prime_rl.trainer.parallel_dims import ParallelDims
|
||||
from prime_rl.trainer.world import get_world
|
||||
@@ -209,7 +213,7 @@ def freeze_sparse_indexer(model: nn.Module) -> None:
|
||||
num_frozen = 0
|
||||
|
||||
for module in model.modules():
|
||||
if isinstance(module, (Indexer, DeepseekV4Indexer)):
|
||||
if isinstance(module, (Indexer, DeepseekV4Indexer, SparseAttentionIndexer)):
|
||||
for param in module.parameters():
|
||||
param.requires_grad = False
|
||||
num_frozen += 1
|
||||
@@ -566,6 +570,18 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
|
||||
|
||||
fullgraph = config.compile is not None and config.compile.fullgraph
|
||||
for transformer_block in transformer_layers:
|
||||
for module in transformer_block.modules():
|
||||
if isinstance(module, NGramEmbedding) and parallel_dims.get_mesh("head").size() > 1:
|
||||
embedding = module.ngram_embedding
|
||||
dp_mod_head_mesh = (
|
||||
parallel_dims.world_mesh["dp_replicate", "dp_shard_mod_head"]
|
||||
if parallel_dims.dp_replicate_enabled
|
||||
else parallel_dims.get_mesh("dp_shard_mod_head")
|
||||
)
|
||||
parallelize_module(embedding, parallel_dims.get_mesh("head"), EmbeddingParallel())
|
||||
fully_shard(embedding, mesh=dp_mod_head_mesh, **fsdp_config)
|
||||
embedding.set_gradient_divide_factor(parallel_dims.fsdp_gradient_divide_factor)
|
||||
|
||||
block_mlp = getattr(transformer_block, "mlp", None)
|
||||
block_fsdp_config = fsdp_config
|
||||
if expert_mesh_info is not None and isinstance(block_mlp, MoE):
|
||||
@@ -608,6 +624,11 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
|
||||
transformer_block.set_gradient_divide_factor(parallel_dims.fsdp_gradient_divide_factor)
|
||||
|
||||
shard_norm_and_lm_head = hasattr(model, "config") and not model.config.tie_word_embeddings
|
||||
final_module = (
|
||||
getattr(language_model, "norm", None)
|
||||
or getattr(language_model, "norm_f", None)
|
||||
or getattr(language_model, "hyper_connection_mixer", None)
|
||||
)
|
||||
|
||||
if shard_norm_and_lm_head:
|
||||
# This optimization breaks weight tying
|
||||
@@ -617,9 +638,8 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
|
||||
mesh=hsdp_mesh,
|
||||
**fsdp_config,
|
||||
)
|
||||
norm_module = getattr(language_model, "norm", None) or language_model.norm_f
|
||||
fully_shard(
|
||||
[model.lm_head, norm_module],
|
||||
[model.lm_head, final_module],
|
||||
mesh=hsdp_mesh,
|
||||
mp_policy=mp_policy,
|
||||
offload_policy=offload_policy,
|
||||
@@ -659,15 +679,15 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
|
||||
if isinstance(next_mlp, MoE) and isinstance(next_mlp.router, FSDPModule):
|
||||
prefetch_modules.append(next_mlp.router)
|
||||
transformer_block.set_modules_to_forward_prefetch(prefetch_modules)
|
||||
elif language_model.norm is not None and model.lm_head is not None:
|
||||
elif final_module is not None and model.lm_head is not None:
|
||||
if shard_norm_and_lm_head:
|
||||
transformer_block.set_modules_to_forward_prefetch([language_model.norm, model.lm_head])
|
||||
transformer_block.set_modules_to_forward_prefetch([final_module, model.lm_head])
|
||||
|
||||
# backward
|
||||
reversed_transformer_blocks = list(reversed(language_model.layers))
|
||||
prev_transformer_blocks = reversed_transformer_blocks[1:] + [None]
|
||||
|
||||
if language_model.norm is not None and model.lm_head is not None and len(language_model.layers) > 0:
|
||||
if final_module is not None and model.lm_head is not None and len(language_model.layers) > 0:
|
||||
last_transformer_block = reversed_transformer_blocks[0]
|
||||
prefetch_modules = [last_transformer_block]
|
||||
last_mlp = getattr(last_transformer_block, "mlp", None)
|
||||
@@ -1037,7 +1057,7 @@ def setup_model(
|
||||
if config.fusions.enabled and config.lora is not None:
|
||||
logger.warning("Skipping runtime model fusions because LoRA targets the unfused projections")
|
||||
elif config.fusions.enabled:
|
||||
applied = apply_model_fusions(model, config.fusions.enabled, raise_on_fail=config.fusions.raise_on_fail)
|
||||
applied = apply_model_fusions(model, config.fusions.enabled)
|
||||
logger.info(f"Applied runtime model fusions: {applied}")
|
||||
|
||||
lm_head_chunk_size: int | None = None
|
||||
|
||||
@@ -29,6 +29,11 @@ from prime_rl.trainer.models.qwen3_5 import (
|
||||
Qwen3_5TextConfig,
|
||||
Qwen3_5VisionConfig,
|
||||
)
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next import (
|
||||
Qwen3_8FlashNextConfig,
|
||||
Qwen3_8FlashNextForCausalLM,
|
||||
Qwen3_8FlashNextTextConfig,
|
||||
)
|
||||
from prime_rl.trainer.models.qwen3_moe import Qwen3MoeConfig, Qwen3MoeForCausalLM
|
||||
|
||||
# Make custom config discoverable by AutoConfig
|
||||
@@ -46,6 +51,8 @@ AutoConfig.register("qwen3_5_text", Qwen3_5TextConfig, exist_ok=True)
|
||||
AutoConfig.register("qwen3_5_moe", Qwen3_5MoeConfig, exist_ok=True)
|
||||
AutoConfig.register("qwen3_5_moe_text", Qwen3_5MoeTextConfig, exist_ok=True)
|
||||
AutoConfig.register("qwen3_5_vision", Qwen3_5VisionConfig, exist_ok=True)
|
||||
AutoConfig.register("qwen4_exp", Qwen3_8FlashNextConfig, exist_ok=True)
|
||||
AutoConfig.register("qwen4_exp_text", Qwen3_8FlashNextTextConfig, exist_ok=True)
|
||||
|
||||
_CUSTOM_CAUSAL_LM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, OrderedDict())
|
||||
_CUSTOM_CAUSAL_LM_MODELS: tuple[
|
||||
@@ -66,6 +73,8 @@ _CUSTOM_CAUSAL_LM_MODELS: tuple[
|
||||
(Qwen3_5MoeTextConfig, Qwen3_5ForCausalLM),
|
||||
(Qwen3_5Config, Qwen3_5ForCausalLM),
|
||||
(Qwen3_5MoeConfig, Qwen3_5ForCausalLM),
|
||||
(Qwen3_8FlashNextTextConfig, Qwen3_8FlashNextForCausalLM),
|
||||
(Qwen3_8FlashNextConfig, Qwen3_8FlashNextForCausalLM),
|
||||
(GptOssConfig, GptOssForCausalLM),
|
||||
)
|
||||
for config_cls, model_cls in _CUSTOM_CAUSAL_LM_MODELS:
|
||||
@@ -106,6 +115,7 @@ def supports_custom_impl(model_config: PretrainedConfig) -> bool:
|
||||
_CUSTOM_VLM_MAPPING: dict[str, type] = {
|
||||
"qwen3_5": Qwen3_5ForCausalLM,
|
||||
"qwen3_5_moe": Qwen3_5ForCausalLM,
|
||||
"qwen4_exp": Qwen3_8FlashNextForCausalLM,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -118,9 +118,7 @@ def fuse_qkv_projections(module: nn.Module) -> None:
|
||||
projection.bias = None
|
||||
|
||||
|
||||
def apply_model_fusions(
|
||||
model: nn.Module, requested_fusions: Sequence[str], raise_on_fail: bool = True
|
||||
) -> dict[str, int]:
|
||||
def apply_model_fusions(model: nn.Module, requested_fusions: Sequence[str]) -> dict[str, int]:
|
||||
"""Apply each requested fusion to every module that supports it; returns the module count per fusion."""
|
||||
fused_module_counts: dict[str, int] = {}
|
||||
for fusion_name in requested_fusions:
|
||||
@@ -132,10 +130,9 @@ def apply_model_fusions(
|
||||
fusion(module)
|
||||
num_fused_modules += 1
|
||||
if num_fused_modules == 0:
|
||||
message = f"The model does not support the {fusion_name!r} runtime fusion"
|
||||
if raise_on_fail:
|
||||
raise ValueError(message)
|
||||
get_logger().warning(f"{message}; continuing without it")
|
||||
get_logger().warning(
|
||||
f"The model does not support the {fusion_name!r} runtime fusion; continuing without it"
|
||||
)
|
||||
continue
|
||||
fused_module_counts[fusion_name] = num_fused_modules
|
||||
return fused_module_counts
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next.attention import IndexedGatedAttention
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next.configuration_qwen3_8_flash_next import (
|
||||
Qwen3_8FlashNextConfig,
|
||||
Qwen3_8FlashNextTextConfig,
|
||||
)
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next.gated_delta_net import GatedDeltaNet
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next.hyper_connection import ExpandedRMSNorm, HyperConnection
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next.modeling_qwen3_8_flash_next import (
|
||||
Qwen3_8FlashNextDecoderLayer,
|
||||
Qwen3_8FlashNextForCausalLM,
|
||||
Qwen3_8FlashNextModel,
|
||||
Qwen3_8FlashNextTextModel,
|
||||
)
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next.ngram_embedding import NGramEmbedding
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next.position_learning import PositionLearningEnhancement
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next.rotary_embedding import RotaryEmbedding
|
||||
|
||||
__all__ = [
|
||||
"ExpandedRMSNorm",
|
||||
"GatedDeltaNet",
|
||||
"HyperConnection",
|
||||
"IndexedGatedAttention",
|
||||
"NGramEmbedding",
|
||||
"PositionLearningEnhancement",
|
||||
"Qwen3_8FlashNextConfig",
|
||||
"Qwen3_8FlashNextDecoderLayer",
|
||||
"Qwen3_8FlashNextForCausalLM",
|
||||
"Qwen3_8FlashNextModel",
|
||||
"Qwen3_8FlashNextTextConfig",
|
||||
"Qwen3_8FlashNextTextModel",
|
||||
"RotaryEmbedding",
|
||||
]
|
||||
@@ -0,0 +1,110 @@
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next.indexer import SparseAttentionIndexer
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next.norm import RMSNorm
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next.rotary_embedding import apply_rotary_embedding
|
||||
from prime_rl.utils.cp import CPContext, gather_for_cp
|
||||
|
||||
|
||||
class IndexedGatedAttention(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
hidden_size: int,
|
||||
num_attention_heads: int,
|
||||
num_key_value_heads: int,
|
||||
head_dim: int,
|
||||
norm_eps: float,
|
||||
indexer_num_heads: int,
|
||||
indexer_head_dim: int,
|
||||
indexer_token_budget: int,
|
||||
indexer_compression_ratio: int,
|
||||
) -> None:
|
||||
import prime_kernels
|
||||
|
||||
super().__init__()
|
||||
self.num_heads = num_attention_heads
|
||||
self.num_key_value_heads = num_key_value_heads
|
||||
self.head_dim = head_dim
|
||||
self.scale = head_dim**-0.5
|
||||
|
||||
self.q_proj = nn.Linear(hidden_size, num_attention_heads * head_dim * 2, bias=False)
|
||||
self.k_proj = nn.Linear(hidden_size, num_key_value_heads * head_dim, bias=False)
|
||||
self.v_proj = nn.Linear(hidden_size, num_key_value_heads * head_dim, bias=False)
|
||||
self.o_proj = nn.Linear(num_attention_heads * head_dim, hidden_size, bias=False)
|
||||
self.q_norm = RMSNorm(head_dim, norm_eps)
|
||||
self.k_norm = RMSNorm(head_dim, norm_eps)
|
||||
self.indexer = SparseAttentionIndexer(
|
||||
hidden_size=hidden_size,
|
||||
num_query_heads=indexer_num_heads,
|
||||
head_dim=indexer_head_dim,
|
||||
token_budget=indexer_token_budget,
|
||||
compression_ratio=indexer_compression_ratio,
|
||||
norm_eps=norm_eps,
|
||||
)
|
||||
|
||||
self.cp_context = CPContext()
|
||||
# Resolve once before torch.compile traces the layer; the loader caches the module.
|
||||
self.indexed_attention = prime_kernels.load("indexed_attention").indexed_attention
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
cu_seqlens: torch.LongTensor,
|
||||
) -> torch.Tensor:
|
||||
batch_size, sequence_length, _ = hidden_states.shape
|
||||
cos, sin = position_embeddings
|
||||
if not self.cp_context.cp_enabled:
|
||||
full_position_embeddings = position_embeddings
|
||||
else:
|
||||
full_cos_sin = gather_for_cp(torch.cat((cos, sin), dim=-1), self.cp_context.cp_group)
|
||||
full_position_embeddings = full_cos_sin.chunk(2, dim=-1)
|
||||
|
||||
indices = self.indexer(hidden_states, full_position_embeddings, cu_seqlens)
|
||||
query_and_gate = self.q_proj(hidden_states).view(
|
||||
batch_size,
|
||||
sequence_length,
|
||||
self.num_heads,
|
||||
self.head_dim * 2,
|
||||
)
|
||||
query_states, output_gate = query_and_gate.chunk(2, dim=-1)
|
||||
key_states = self.k_proj(hidden_states).view(
|
||||
batch_size,
|
||||
sequence_length,
|
||||
self.num_key_value_heads,
|
||||
self.head_dim,
|
||||
)
|
||||
value_states = self.v_proj(hidden_states).view(
|
||||
batch_size,
|
||||
sequence_length,
|
||||
self.num_key_value_heads,
|
||||
self.head_dim,
|
||||
)
|
||||
|
||||
query_states = self.q_norm(query_states)
|
||||
key_states = self.k_norm(key_states)
|
||||
query_states = apply_rotary_embedding(query_states, cos, sin)
|
||||
|
||||
if self.cp_context.cp_enabled:
|
||||
key_value_states = gather_for_cp(
|
||||
torch.cat((key_states, value_states), dim=-1),
|
||||
self.cp_context.cp_group,
|
||||
)
|
||||
key_states, value_states = key_value_states.chunk(2, dim=-1)
|
||||
full_cos, full_sin = full_position_embeddings
|
||||
key_states = apply_rotary_embedding(key_states, full_cos, full_sin)
|
||||
|
||||
attention_output = self.indexed_attention(
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
indices,
|
||||
self.scale,
|
||||
).reshape(batch_size, sequence_length, -1)
|
||||
attention_output = attention_output * output_gate.reshape(batch_size, sequence_length, -1).sigmoid()
|
||||
return self.o_proj(attention_output)
|
||||
|
||||
|
||||
__all__ = ["IndexedGatedAttention"]
|
||||
@@ -0,0 +1,154 @@
|
||||
from transformers.configuration_utils import PretrainedConfig
|
||||
|
||||
|
||||
class Qwen3_8FlashNextTextConfig(PretrainedConfig):
|
||||
model_type = "qwen4_exp_text"
|
||||
base_config_key = "text_config"
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
ignore_keys_at_rope_validation = {"mrope_section", "mrope_interleaved"}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vocab_size: int = 248320,
|
||||
hidden_size: int = 2560,
|
||||
num_hidden_layers: int = 48,
|
||||
num_attention_heads: int = 24,
|
||||
num_key_value_heads: int = 2,
|
||||
head_dim: int = 256,
|
||||
hidden_act: str = "silu",
|
||||
max_position_embeddings: int = 262144,
|
||||
initializer_range: float = 0.02,
|
||||
rms_norm_eps: float = 1e-6,
|
||||
rope_parameters: dict | None = None,
|
||||
partial_rotary_factor: float = 0.25,
|
||||
attention_bias: bool = False,
|
||||
attention_dropout: float = 0.0,
|
||||
layer_types: list[str] | None = None,
|
||||
full_attention_interval: int = 4,
|
||||
linear_conv_kernel_dim: int = 4,
|
||||
linear_key_head_dim: int = 128,
|
||||
linear_value_head_dim: int = 128,
|
||||
linear_num_key_heads: int = 16,
|
||||
linear_num_value_heads: int = 48,
|
||||
indexer_n_heads: int = 4,
|
||||
indexer_kv_heads: int = 1,
|
||||
indexer_head_dim: int = 128,
|
||||
indexer_budget: int = 2048,
|
||||
indexer_compress_ratio: int = 4,
|
||||
hc_count: int = 4,
|
||||
hc_lowrank: int = 320,
|
||||
ple_layer_ids: list[int] | None = None,
|
||||
ple_embed_dim: int = 2560,
|
||||
ple_conv_kernel_size: int = 4,
|
||||
ngram_size: int = 3,
|
||||
heads_per_ngram: int = 8,
|
||||
ngram_vocab_size_base: int = 20_000_000,
|
||||
make_ngram_vocab_size_divisible_by: int = 128,
|
||||
split_ngram_parts: int = 128,
|
||||
moe_intermediate_size: int = 640,
|
||||
shared_expert_intermediate_size: int = 640,
|
||||
num_experts_per_tok: int = 10,
|
||||
num_experts: int = 512,
|
||||
load_balance_coeff: float | None = None,
|
||||
pad_token_id: int | None = None,
|
||||
bos_token_id: int | None = 248044,
|
||||
eos_token_id: int = 248044,
|
||||
tie_word_embeddings: bool = False,
|
||||
use_cache: bool = False,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
self.vocab_size = vocab_size
|
||||
self.hidden_size = hidden_size
|
||||
self.num_hidden_layers = num_hidden_layers
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.num_key_value_heads = num_key_value_heads
|
||||
self.head_dim = head_dim
|
||||
self.hidden_act = hidden_act
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
self.initializer_range = initializer_range
|
||||
self.rms_norm_eps = rms_norm_eps
|
||||
self.attention_bias = attention_bias
|
||||
self.attention_dropout = attention_dropout
|
||||
|
||||
rope_parameters = dict(rope_parameters or {})
|
||||
self.rope_theta = rope_parameters.get("rope_theta", 10_000_000.0)
|
||||
self.partial_rotary_factor = rope_parameters.get("partial_rotary_factor", partial_rotary_factor)
|
||||
self.mrope_section = tuple(rope_parameters.get("mrope_section", (11, 11, 10)))
|
||||
self.rope_parameters = rope_parameters
|
||||
|
||||
self.layer_types = layer_types or [
|
||||
"linear_attention" if (layer_index + 1) % full_attention_interval else "full_attention"
|
||||
for layer_index in range(num_hidden_layers)
|
||||
]
|
||||
self.linear_conv_kernel_dim = linear_conv_kernel_dim
|
||||
self.linear_key_head_dim = linear_key_head_dim
|
||||
self.linear_value_head_dim = linear_value_head_dim
|
||||
self.linear_num_key_heads = linear_num_key_heads
|
||||
self.linear_num_value_heads = linear_num_value_heads
|
||||
self.indexer_n_heads = indexer_n_heads
|
||||
self.indexer_kv_heads = indexer_kv_heads
|
||||
self.indexer_head_dim = indexer_head_dim
|
||||
self.indexer_budget = indexer_budget
|
||||
self.indexer_compress_ratio = indexer_compress_ratio
|
||||
|
||||
self.hc_count = hc_count
|
||||
self.hc_lowrank = hc_lowrank
|
||||
self.ple_layer_ids = [2] if ple_layer_ids is None else ple_layer_ids
|
||||
self.ple_embed_dim = ple_embed_dim
|
||||
self.ple_conv_kernel_size = ple_conv_kernel_size
|
||||
self.ngram_size = ngram_size
|
||||
self.heads_per_ngram = heads_per_ngram
|
||||
self.ngram_vocab_size_base = ngram_vocab_size_base
|
||||
self.make_ngram_vocab_size_divisible_by = make_ngram_vocab_size_divisible_by
|
||||
self.split_ngram_parts = split_ngram_parts
|
||||
|
||||
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.load_balance_coeff = load_balance_coeff
|
||||
self.use_cache = use_cache
|
||||
|
||||
kwargs.pop("mamba_ssm_dtype", None)
|
||||
kwargs.pop("mtp", None)
|
||||
kwargs.pop("mtp_num_hidden_layers", None)
|
||||
kwargs.pop("mtp_use_dedicated_embeddings", None)
|
||||
kwargs.pop("output_gate_type", None)
|
||||
kwargs.pop("output_router_logits", None)
|
||||
kwargs.pop("router_aux_loss_coef", None)
|
||||
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,
|
||||
)
|
||||
|
||||
|
||||
class Qwen3_8FlashNextConfig(PretrainedConfig):
|
||||
model_type = "qwen4_exp"
|
||||
sub_configs = {"text_config": Qwen3_8FlashNextTextConfig}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
text_config: Qwen3_8FlashNextTextConfig | dict | None = None,
|
||||
tie_word_embeddings: bool = False,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
if isinstance(text_config, dict):
|
||||
text_config = Qwen3_8FlashNextTextConfig(**text_config)
|
||||
self.text_config = text_config or Qwen3_8FlashNextTextConfig()
|
||||
|
||||
kwargs.pop("vision_config", None)
|
||||
kwargs.pop("image_token_id", None)
|
||||
kwargs.pop("video_token_id", None)
|
||||
kwargs.pop("vision_start_token_id", None)
|
||||
kwargs.pop("vision_end_token_id", None)
|
||||
kwargs.pop("language_model_only", None)
|
||||
kwargs.setdefault("pad_token_id", self.text_config.pad_token_id)
|
||||
kwargs.setdefault("bos_token_id", self.text_config.bos_token_id)
|
||||
kwargs.setdefault("eos_token_id", self.text_config.eos_token_id)
|
||||
super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
|
||||
|
||||
|
||||
__all__ = ["Qwen3_8FlashNextConfig", "Qwen3_8FlashNextTextConfig"]
|
||||
@@ -0,0 +1,92 @@
|
||||
from dataclasses import dataclass
|
||||
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.trainer.models.conversion_ops import ConvOp, Drop, Rename, SplitConcat
|
||||
|
||||
|
||||
@dataclass
|
||||
class NGramEmbeddingWeights(ConvOp):
|
||||
checkpoint_prefix: str
|
||||
runtime_weight: str
|
||||
shard_count: int
|
||||
|
||||
def hf_to_prime(self, state_dict: dict[str, Tensor]) -> None:
|
||||
first_shard = f"{self.checkpoint_prefix}.shard_0.weight"
|
||||
if first_shard not in state_dict:
|
||||
return
|
||||
|
||||
state_dict[self.runtime_weight] = torch.cat(
|
||||
[
|
||||
state_dict.pop(f"{self.checkpoint_prefix}.shard_{shard_index}.weight")
|
||||
for shard_index in range(self.shard_count)
|
||||
],
|
||||
dim=0,
|
||||
)
|
||||
|
||||
def prime_to_hf(self, state_dict: dict[str, Tensor]) -> None:
|
||||
if self.runtime_weight not in state_dict:
|
||||
return
|
||||
|
||||
weight = state_dict.pop(self.runtime_weight)
|
||||
shard_size = (weight.shape[0] + self.shard_count - 1) // self.shard_count
|
||||
for index in range(self.shard_count):
|
||||
start = index * shard_size
|
||||
state_dict[f"{self.checkpoint_prefix}.shard_{index}.weight"] = weight[start : start + shard_size]
|
||||
|
||||
|
||||
def is_hf_state_dict(state_dict: dict[str, Tensor]) -> bool:
|
||||
return any(
|
||||
name.endswith("mlp.experts.gate_up_proj") or ".ngram_embedding.shard_0.weight" in name for name in state_dict
|
||||
)
|
||||
|
||||
|
||||
def is_prime_state_dict(state_dict: dict[str, Tensor]) -> bool:
|
||||
return any(
|
||||
name.endswith("mlp.experts.gate_proj") or name.endswith("ple_embedding.ngram_embedding.weight")
|
||||
for name in state_dict
|
||||
)
|
||||
|
||||
|
||||
def conversion_chain(config) -> list[ConvOp]:
|
||||
text_config = getattr(config, "text_config", config)
|
||||
model_prefix = "model.language_model" if hasattr(config, "text_config") else "model"
|
||||
operations: list[ConvOp] = [
|
||||
Drop("model.visual.", is_prefix=True),
|
||||
Drop("mtp.", is_prefix=True),
|
||||
]
|
||||
|
||||
for layer_index in range(text_config.num_hidden_layers):
|
||||
prefix = f"{model_prefix}.layers.{layer_index}.mlp"
|
||||
operations.extend(
|
||||
[
|
||||
Rename(f"{prefix}.gate.weight", f"{prefix}.router.gate.weight"),
|
||||
Rename(
|
||||
f"{prefix}.shared_expert_gate.weight",
|
||||
f"{prefix}.shared_expert.output_gate.weight",
|
||||
),
|
||||
SplitConcat(
|
||||
combined=f"{prefix}.experts.gate_up_proj",
|
||||
parts=[
|
||||
(f"{prefix}.experts.gate_proj", None),
|
||||
(f"{prefix}.experts.up_proj", None),
|
||||
],
|
||||
dim=1,
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
for layer_index in (layer_id - 1 for layer_id in sorted(text_config.ple_layer_ids)):
|
||||
prefix = f"{model_prefix}.layers.{layer_index}.ple.ple_embedding.ngram_embedding"
|
||||
operations.append(
|
||||
NGramEmbeddingWeights(
|
||||
checkpoint_prefix=prefix,
|
||||
runtime_weight=f"{prefix}.weight",
|
||||
shard_count=text_config.split_ngram_parts,
|
||||
)
|
||||
)
|
||||
return operations
|
||||
|
||||
|
||||
__all__ = ["conversion_chain", "is_hf_state_dict", "is_prime_state_dict"]
|
||||
@@ -0,0 +1,130 @@
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from fla.modules import FusedRMSNormGated
|
||||
from fla.modules.conv import causal_conv1d
|
||||
from fla.ops.cp import build_cp_context
|
||||
from fla.ops.gated_delta_rule import chunk_gated_delta_rule
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.utils.cp import CPContext
|
||||
|
||||
# FLA's context carries a process group that Dynamo cannot trace through the convolution.
|
||||
causal_conv1d_with_context_parallelism = torch.compiler.disable(causal_conv1d)
|
||||
|
||||
|
||||
class GatedDeltaNet(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
hidden_size: int,
|
||||
num_key_heads: int,
|
||||
num_value_heads: int,
|
||||
key_head_dim: int,
|
||||
value_head_dim: int,
|
||||
conv_kernel_size: int,
|
||||
norm_eps: float,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.num_key_heads = num_key_heads
|
||||
self.num_value_heads = num_value_heads
|
||||
self.key_head_dim = key_head_dim
|
||||
self.value_head_dim = value_head_dim
|
||||
self.key_dim = num_key_heads * key_head_dim
|
||||
self.value_dim = num_value_heads * value_head_dim
|
||||
self.conv_kernel_size = conv_kernel_size
|
||||
|
||||
self.in_proj_qkv = nn.Linear(hidden_size, 2 * self.key_dim + self.value_dim, bias=False)
|
||||
self.in_proj_z = nn.Linear(hidden_size, self.value_dim, bias=False)
|
||||
self.in_proj_b = nn.Linear(hidden_size, num_value_heads, bias=False)
|
||||
self.in_proj_a = nn.Linear(hidden_size, num_value_heads, bias=False)
|
||||
|
||||
conv_dim = 2 * self.key_dim + self.value_dim
|
||||
self.conv1d = nn.Conv1d(
|
||||
conv_dim,
|
||||
conv_dim,
|
||||
kernel_size=conv_kernel_size,
|
||||
groups=conv_dim,
|
||||
padding=conv_kernel_size - 1,
|
||||
bias=False,
|
||||
)
|
||||
self.dt_bias = nn.Parameter(torch.ones(num_value_heads))
|
||||
A = torch.empty(num_value_heads).uniform_(0, 16)
|
||||
self.A_log = nn.Parameter(torch.log(A))
|
||||
|
||||
self.norm = FusedRMSNormGated(value_head_dim, eps=norm_eps, activation="sigmoid")
|
||||
self.out_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
|
||||
|
||||
self.cp_context = CPContext()
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
cu_seqlens: torch.LongTensor,
|
||||
) -> torch.Tensor:
|
||||
batch_size, sequence_length, _ = hidden_states.shape
|
||||
|
||||
mixed_qkv = self.in_proj_qkv(hidden_states)
|
||||
output_gate = self.in_proj_z(hidden_states).reshape(
|
||||
batch_size,
|
||||
sequence_length,
|
||||
self.num_value_heads,
|
||||
self.value_head_dim,
|
||||
)
|
||||
beta = self.in_proj_b(hidden_states).sigmoid()
|
||||
decay = -self.A_log.float().exp() * F.softplus(self.in_proj_a(hidden_states).float() + self.dt_bias)
|
||||
|
||||
context = None
|
||||
if self.cp_context.cp_enabled:
|
||||
context = build_cp_context(
|
||||
cu_seqlens=cu_seqlens.to(device=hidden_states.device, dtype=torch.int32),
|
||||
group=self.cp_context.cp_group,
|
||||
conv1d_kernel_size=self.conv_kernel_size,
|
||||
)
|
||||
|
||||
convolution = {
|
||||
"x": mixed_qkv,
|
||||
"weight": self.conv1d.weight.squeeze(1),
|
||||
"bias": self.conv1d.bias,
|
||||
"activation": "silu",
|
||||
}
|
||||
if context is None:
|
||||
mixed_qkv, _ = causal_conv1d(**convolution, cu_seqlens=cu_seqlens)
|
||||
else:
|
||||
mixed_qkv, _ = causal_conv1d_with_context_parallelism(**convolution, cp_context=context)
|
||||
|
||||
query, key, value = mixed_qkv.split((self.key_dim, self.key_dim, self.value_dim), dim=-1)
|
||||
query = query.reshape(batch_size, sequence_length, self.num_key_heads, self.key_head_dim)
|
||||
key = key.reshape(batch_size, sequence_length, self.num_key_heads, self.key_head_dim)
|
||||
value = value.reshape(batch_size, sequence_length, self.num_value_heads, self.value_head_dim)
|
||||
|
||||
heads_per_key = self.num_value_heads // self.num_key_heads
|
||||
if heads_per_key > 1:
|
||||
query = query.repeat_interleave(heads_per_key, dim=2)
|
||||
key = key.repeat_interleave(heads_per_key, dim=2)
|
||||
|
||||
delta_rule = {
|
||||
"q": query,
|
||||
"k": key,
|
||||
"v": value,
|
||||
"g": decay,
|
||||
"beta": beta,
|
||||
"use_qk_l2norm_in_kernel": True,
|
||||
"cu_seqlens": context.cu_seqlens if context is not None else cu_seqlens,
|
||||
}
|
||||
if context is None:
|
||||
core_output, _ = chunk_gated_delta_rule(
|
||||
**delta_rule,
|
||||
initial_state=None,
|
||||
output_final_state=False,
|
||||
)
|
||||
else:
|
||||
core_output, _ = chunk_gated_delta_rule(**delta_rule, cp_context=context)
|
||||
|
||||
core_output = self.norm(
|
||||
core_output.reshape(-1, self.value_head_dim),
|
||||
output_gate.reshape(-1, self.value_head_dim),
|
||||
)
|
||||
return self.out_proj(core_output.reshape(batch_size, sequence_length, self.value_dim))
|
||||
|
||||
|
||||
__all__ = ["GatedDeltaNet"]
|
||||
@@ -0,0 +1,74 @@
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import nn
|
||||
|
||||
|
||||
class ExpandedRMSNorm(nn.Module):
|
||||
"""RMS-normalize each residual stream with an independent affine weight."""
|
||||
|
||||
def __init__(self, hidden_size: int, stream_count: int, eps: float) -> None:
|
||||
super().__init__()
|
||||
self.hidden_size = hidden_size
|
||||
self.stream_count = stream_count
|
||||
self.eps = eps
|
||||
self.weight = nn.Parameter(torch.zeros(stream_count * hidden_size))
|
||||
|
||||
def reset_parameters(self) -> None:
|
||||
nn.init.zeros_(self.weight)
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
input_dtype = hidden_states.dtype
|
||||
streams = hidden_states.float().unflatten(-1, (self.stream_count, self.hidden_size))
|
||||
variance = streams.square().mean(dim=-1, keepdim=True)
|
||||
normalized = streams * torch.rsqrt(variance + self.eps)
|
||||
return (normalized.flatten(-2) * (1.0 + self.weight.float())).to(input_dtype)
|
||||
|
||||
|
||||
class HyperConnection(nn.Module):
|
||||
"""Learned mixing and residual injection across expanded residual streams."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
hidden_size: int,
|
||||
stream_count: int,
|
||||
low_rank: int,
|
||||
norm_eps: float,
|
||||
with_residual_injection: bool = True,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.hidden_size = hidden_size
|
||||
self.stream_count = stream_count
|
||||
expanded_size = stream_count * hidden_size
|
||||
|
||||
self.hc_norm = ExpandedRMSNorm(hidden_size, stream_count, norm_eps)
|
||||
self.input_mix_weight_down = nn.Linear(expanded_size, low_rank, bias=False)
|
||||
self.input_mix_weight_up = nn.Linear(low_rank, expanded_size, bias=False)
|
||||
self.block_inject_weight = (
|
||||
nn.Linear(expanded_size, stream_count, bias=False) if with_residual_injection else None
|
||||
)
|
||||
|
||||
def mix(self, expanded_states: torch.Tensor) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]:
|
||||
normalized_states = self.hc_norm(expanded_states)
|
||||
mixing_weights = F.silu(self.input_mix_weight_down(normalized_states) / self.stream_count)
|
||||
mixing_weights = torch.sigmoid(self.input_mix_weight_up(mixing_weights))
|
||||
mixing_weights = mixing_weights.unflatten(-1, (self.stream_count, self.hidden_size))
|
||||
normalized_streams = normalized_states.unflatten(-1, (self.stream_count, self.hidden_size))
|
||||
block_input = (mixing_weights * normalized_streams).mean(dim=-2)
|
||||
return block_input.to(expanded_states.dtype), (expanded_states, normalized_states)
|
||||
|
||||
def forward(self, expanded_states: torch.Tensor) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]:
|
||||
return self.mix(expanded_states)
|
||||
|
||||
def combine(
|
||||
self,
|
||||
block_output: torch.Tensor,
|
||||
residual_state: tuple[torch.Tensor, torch.Tensor],
|
||||
) -> torch.Tensor:
|
||||
expanded_states, normalized_states = residual_state
|
||||
injection_weights = 2.0 * torch.sigmoid(self.block_inject_weight(normalized_states) / self.stream_count)
|
||||
residual_streams = expanded_states.unflatten(-1, (self.stream_count, self.hidden_size))
|
||||
return (residual_streams + block_output.unsqueeze(-2) * injection_weights.unsqueeze(-1)).flatten(-2)
|
||||
|
||||
|
||||
__all__ = ["ExpandedRMSNorm", "HyperConnection"]
|
||||
@@ -0,0 +1,150 @@
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next.norm import RMSNorm
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next.rotary_embedding import apply_rotary_embedding
|
||||
from prime_rl.utils.cp import CPContext, gather_for_cp
|
||||
|
||||
|
||||
class SparseAttentionIndexer(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
hidden_size: int,
|
||||
num_query_heads: int,
|
||||
head_dim: int,
|
||||
token_budget: int,
|
||||
compression_ratio: int,
|
||||
norm_eps: float,
|
||||
) -> None:
|
||||
import prime_kernels
|
||||
|
||||
super().__init__()
|
||||
self.select_indexed_blocks = prime_kernels.load("indexed_attention").select_indexed_blocks
|
||||
self.num_query_heads = num_query_heads
|
||||
self.head_dim = head_dim
|
||||
self.token_budget = token_budget
|
||||
self.compression_ratio = compression_ratio
|
||||
self.block_budget = token_budget // compression_ratio
|
||||
|
||||
self.index_qk_proj = nn.Linear(
|
||||
hidden_size,
|
||||
(num_query_heads + 1) * head_dim,
|
||||
bias=False,
|
||||
)
|
||||
self.q_layernorm = RMSNorm(head_dim, norm_eps)
|
||||
self.k_layernorm = RMSNorm(head_dim, norm_eps)
|
||||
self.requires_grad_(False)
|
||||
|
||||
self.cp_context = CPContext()
|
||||
|
||||
@property
|
||||
def output_width(self) -> int:
|
||||
return self.token_budget + self.compression_ratio - 1
|
||||
|
||||
@torch.no_grad()
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
full_position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
cu_seqlens: torch.LongTensor,
|
||||
) -> torch.Tensor:
|
||||
local_tokens = hidden_states.shape[1]
|
||||
projected_query_key = self.index_qk_proj(hidden_states[0])
|
||||
query, local_raw_key = projected_query_key.split(
|
||||
(self.num_query_heads * self.head_dim, self.head_dim),
|
||||
dim=-1,
|
||||
)
|
||||
query = self.q_layernorm(query.view(local_tokens, self.num_query_heads, self.head_dim))
|
||||
|
||||
if not self.cp_context.cp_enabled:
|
||||
raw_key = local_raw_key
|
||||
else:
|
||||
raw_key = gather_for_cp(local_raw_key.unsqueeze(0), self.cp_context.cp_group)[0]
|
||||
total_tokens = raw_key.shape[0]
|
||||
|
||||
token_indices = torch.arange(total_tokens, dtype=cu_seqlens.dtype, device=hidden_states.device)
|
||||
query_start = self.cp_context.cp_rank * local_tokens
|
||||
query_token_indices = token_indices[query_start : query_start + local_tokens]
|
||||
sequence_indices = torch.searchsorted(cu_seqlens[1:], query_token_indices, right=True)
|
||||
sequence_starts = cu_seqlens[:-1][sequence_indices]
|
||||
sequence_positions = query_token_indices - sequence_starts
|
||||
|
||||
all_sequence_indices = torch.searchsorted(cu_seqlens[1:], token_indices, right=True)
|
||||
all_sequence_ends = cu_seqlens[1:][all_sequence_indices]
|
||||
all_sequence_positions = token_indices - cu_seqlens[:-1][all_sequence_indices]
|
||||
is_block_start = (all_sequence_positions.remainder(self.compression_ratio) == 0) & (
|
||||
token_indices + self.compression_ratio <= all_sequence_ends
|
||||
)
|
||||
max_blocks = total_tokens // self.compression_ratio
|
||||
block_slots = is_block_start.cumsum(0) - 1
|
||||
block_slots = block_slots.masked_fill(~is_block_start, max_blocks)
|
||||
block_start_tokens = torch.zeros(
|
||||
max_blocks + 1,
|
||||
dtype=torch.long,
|
||||
device=hidden_states.device,
|
||||
)
|
||||
block_start_tokens.scatter_(0, block_slots.long(), token_indices.long())
|
||||
block_start_tokens = block_start_tokens[:-1]
|
||||
offsets = torch.arange(self.compression_ratio, device=hidden_states.device)
|
||||
compressed_key = raw_key[block_start_tokens[:, None] + offsets].float().mean(dim=1).to(raw_key.dtype)
|
||||
compressed_key = self.k_layernorm(compressed_key).unsqueeze(1)
|
||||
|
||||
cos, sin = full_position_embeddings
|
||||
query = apply_rotary_embedding(
|
||||
query.unsqueeze(0),
|
||||
cos.index_select(1, query_token_indices.long()),
|
||||
sin.index_select(1, query_token_indices.long()),
|
||||
)[0]
|
||||
compressed_key = apply_rotary_embedding(
|
||||
compressed_key.unsqueeze(0),
|
||||
cos.index_select(1, block_start_tokens),
|
||||
sin.index_select(1, block_start_tokens),
|
||||
)[0, :, 0]
|
||||
|
||||
blocks_per_sequence = (cu_seqlens[1:] - cu_seqlens[:-1]).div(
|
||||
self.compression_ratio,
|
||||
rounding_mode="floor",
|
||||
)
|
||||
cumulative_blocks = F.pad(blocks_per_sequence.cumsum(0), (1, 0))
|
||||
sequence_block_start = cumulative_blocks[sequence_indices]
|
||||
causal_block_end = sequence_block_start + (sequence_positions + 1).div(
|
||||
self.compression_ratio,
|
||||
rounding_mode="floor",
|
||||
)
|
||||
selected_blocks = self.select_indexed_blocks(
|
||||
query,
|
||||
compressed_key,
|
||||
sequence_block_start.to(torch.int32),
|
||||
causal_block_end.to(torch.int32),
|
||||
self.block_budget,
|
||||
)
|
||||
|
||||
num_blocks = block_start_tokens.shape[0]
|
||||
sentinel = total_tokens
|
||||
block_start_tokens = F.pad(block_start_tokens, (0, 1), value=sentinel)
|
||||
selected_block_starts = block_start_tokens[selected_blocks.long()]
|
||||
selected_tokens = selected_block_starts[:, :, None] + offsets
|
||||
selected_tokens = selected_tokens.masked_fill(selected_blocks[:, :, None] == num_blocks, sentinel)
|
||||
|
||||
indices = torch.full(
|
||||
(local_tokens, self.output_width),
|
||||
sentinel,
|
||||
dtype=torch.int32,
|
||||
device=hidden_states.device,
|
||||
)
|
||||
indices[:, : self.token_budget] = selected_tokens.flatten(1).to(torch.int32)
|
||||
|
||||
visible_blocks = (causal_block_end - sequence_block_start).clamp(max=self.block_budget)
|
||||
tail_length = (sequence_positions + 1).remainder(self.compression_ratio)
|
||||
tail_start = query_token_indices - tail_length + 1
|
||||
tail_offsets = offsets[:-1]
|
||||
tail_tokens = tail_start[:, None] + tail_offsets
|
||||
tail_tokens = tail_tokens.masked_fill(tail_offsets >= tail_length[:, None], sentinel)
|
||||
tail_columns = visible_blocks[:, None] * self.compression_ratio + tail_offsets
|
||||
indices.scatter_(1, tail_columns.long(), tail_tokens.to(torch.int32))
|
||||
return indices.unsqueeze(0)
|
||||
|
||||
|
||||
__all__ = ["SparseAttentionIndexer"]
|
||||
@@ -0,0 +1,316 @@
|
||||
import torch
|
||||
from torch import Tensor, nn
|
||||
from transformers.modeling_outputs import BaseModelOutput
|
||||
|
||||
from prime_rl.trainer.models.base import CPSupport, PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput, VanillaOutputLinear
|
||||
from prime_rl.trainer.models.layers.moe import MoE
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next.attention import IndexedGatedAttention
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next.configuration_qwen3_8_flash_next import (
|
||||
Qwen3_8FlashNextConfig,
|
||||
Qwen3_8FlashNextTextConfig,
|
||||
)
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next.converting_qwen3_8_flash_next import (
|
||||
conversion_chain,
|
||||
is_hf_state_dict,
|
||||
is_prime_state_dict,
|
||||
)
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next.gated_delta_net import GatedDeltaNet
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next.hyper_connection import ExpandedRMSNorm, HyperConnection
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next.moe import SigmoidOutputGatedMoE
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next.ngram_embedding import NGramEmbedding
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next.norm import RMSNorm
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next.position_learning import PositionLearningEnhancement
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next.rotary_embedding import RotaryEmbedding
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
|
||||
|
||||
|
||||
class Qwen3_8FlashNextDecoderLayer(nn.Module):
|
||||
def __init__(self, config: Qwen3_8FlashNextTextConfig, layer_index: int) -> None:
|
||||
super().__init__()
|
||||
self.layer_type = config.layer_types[layer_index]
|
||||
if self.layer_type == "linear_attention":
|
||||
self.linear_attn = GatedDeltaNet(
|
||||
hidden_size=config.hidden_size,
|
||||
num_key_heads=config.linear_num_key_heads,
|
||||
num_value_heads=config.linear_num_value_heads,
|
||||
key_head_dim=config.linear_key_head_dim,
|
||||
value_head_dim=config.linear_value_head_dim,
|
||||
conv_kernel_size=config.linear_conv_kernel_dim,
|
||||
norm_eps=config.rms_norm_eps,
|
||||
)
|
||||
else:
|
||||
self.self_attn = IndexedGatedAttention(
|
||||
hidden_size=config.hidden_size,
|
||||
num_attention_heads=config.num_attention_heads,
|
||||
num_key_value_heads=config.num_key_value_heads,
|
||||
head_dim=config.head_dim,
|
||||
norm_eps=config.rms_norm_eps,
|
||||
indexer_num_heads=config.indexer_n_heads,
|
||||
indexer_head_dim=config.indexer_head_dim,
|
||||
indexer_token_budget=config.indexer_budget,
|
||||
indexer_compression_ratio=config.indexer_compress_ratio,
|
||||
)
|
||||
|
||||
ple_layer_ids = sorted(set(config.ple_layer_ids))
|
||||
if layer_index + 1 in ple_layer_ids:
|
||||
self.ple = PositionLearningEnhancement(
|
||||
hidden_size=config.hidden_size,
|
||||
stream_count=config.hc_count,
|
||||
embedding_dim=config.ple_embed_dim,
|
||||
ngram_size=config.ngram_size,
|
||||
heads_per_ngram=config.heads_per_ngram,
|
||||
ngram_vocab_size=config.ngram_vocab_size_base,
|
||||
token_vocab_size=config.vocab_size,
|
||||
eos_token_id=config.eos_token_id,
|
||||
vocab_size_divisor=config.make_ngram_vocab_size_divisible_by,
|
||||
ngram_layer_index=ple_layer_ids.index(layer_index + 1),
|
||||
conv_kernel_size=config.ple_conv_kernel_size,
|
||||
norm_eps=config.rms_norm_eps,
|
||||
)
|
||||
else:
|
||||
self.ple = None
|
||||
|
||||
self.mlp = SigmoidOutputGatedMoE(
|
||||
dim=config.hidden_size,
|
||||
expert_hidden_dim=config.moe_intermediate_size,
|
||||
shared_expert_hidden_dim=config.shared_expert_intermediate_size,
|
||||
num_experts=config.num_experts,
|
||||
top_k=config.num_experts_per_tok,
|
||||
activation=config.hidden_act,
|
||||
init_std=config.initializer_range,
|
||||
load_balance_coeff=config.load_balance_coeff,
|
||||
)
|
||||
connection_args = {
|
||||
"hidden_size": config.hidden_size,
|
||||
"stream_count": config.hc_count,
|
||||
"low_rank": config.hc_lowrank,
|
||||
"norm_eps": config.rms_norm_eps,
|
||||
}
|
||||
self.attn_hyper_connection = HyperConnection(**connection_args)
|
||||
self.mlp_hyper_connection = HyperConnection(**connection_args)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
input_ids: torch.LongTensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
cu_seqlens: torch.LongTensor,
|
||||
routed_experts: torch.LongTensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
if self.ple is not None:
|
||||
hidden_states = hidden_states + self.ple(hidden_states, input_ids, cu_seqlens)
|
||||
|
||||
block_input, residual_state = self.attn_hyper_connection.mix(hidden_states)
|
||||
if self.layer_type == "linear_attention":
|
||||
block_output = self.linear_attn(block_input, cu_seqlens)
|
||||
else:
|
||||
block_output = self.self_attn(block_input, position_embeddings, cu_seqlens)
|
||||
hidden_states = self.attn_hyper_connection.combine(block_output, residual_state)
|
||||
|
||||
block_input, residual_state = self.mlp_hyper_connection.mix(hidden_states)
|
||||
block_output = self.mlp(block_input, routed_experts=routed_experts)
|
||||
return self.mlp_hyper_connection.combine(block_output, residual_state)
|
||||
|
||||
|
||||
class Qwen3_8FlashNextPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
config_class = Qwen3_8FlashNextConfig
|
||||
base_model_prefix = "model"
|
||||
supports_gradient_checkpointing = True
|
||||
_no_split_modules = ["Qwen3_8FlashNextDecoderLayer"]
|
||||
_can_compile_fullgraph = False
|
||||
|
||||
@classmethod
|
||||
def cp_support(cls, config) -> CPSupport:
|
||||
return CPSupport(
|
||||
frozenset({"ulysses"}),
|
||||
"DeltaNet, indexed attention, and PLE require contiguous sequence shards",
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return is_hf_state_dict(state_dict)
|
||||
|
||||
@classmethod
|
||||
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return is_prime_state_dict(state_dict)
|
||||
|
||||
@classmethod
|
||||
def conversion_chain(cls, config):
|
||||
return conversion_chain(config)
|
||||
|
||||
|
||||
class Qwen3_8FlashNextTextModel(Qwen3_8FlashNextPreTrainedModel):
|
||||
config_class = Qwen3_8FlashNextTextConfig
|
||||
|
||||
def __init__(self, config: Qwen3_8FlashNextTextConfig) -> None:
|
||||
super().__init__(config)
|
||||
self.vocab_size = config.vocab_size
|
||||
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, config.pad_token_id)
|
||||
self.layers = nn.ModuleList(
|
||||
Qwen3_8FlashNextDecoderLayer(config, layer_index) for layer_index in range(config.num_hidden_layers)
|
||||
)
|
||||
self.hyper_connection_mixer = HyperConnection(
|
||||
hidden_size=config.hidden_size,
|
||||
stream_count=config.hc_count,
|
||||
low_rank=config.hc_lowrank,
|
||||
norm_eps=config.rms_norm_eps,
|
||||
with_residual_injection=False,
|
||||
)
|
||||
self.rotary_emb = RotaryEmbedding(
|
||||
head_dim=config.head_dim,
|
||||
theta=config.rope_theta,
|
||||
partial_rotary_factor=config.partial_rotary_factor,
|
||||
mrope_section=config.mrope_section,
|
||||
)
|
||||
self.gradient_checkpointing = False
|
||||
self.post_init()
|
||||
for module in self.modules():
|
||||
if isinstance(module, (RMSNorm, ExpandedRMSNorm)):
|
||||
module.reset_parameters()
|
||||
elif isinstance(module, PositionLearningEnhancement):
|
||||
module.reset_parameters()
|
||||
|
||||
def get_input_embeddings(self) -> nn.Embedding:
|
||||
return self.embed_tokens
|
||||
|
||||
def set_input_embeddings(self, embeddings: nn.Embedding) -> None:
|
||||
self.embed_tokens = embeddings
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.LongTensor,
|
||||
position_ids: torch.LongTensor | None = None,
|
||||
routed_experts: torch.LongTensor | None = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
) -> BaseModelOutput:
|
||||
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)
|
||||
|
||||
cu_seqlens, _ = get_cu_seqlens_from_seq_lens(
|
||||
seq_lens.to(inputs_embeds.device),
|
||||
total_tokens=None if seq_lens_are_pre_shard else inputs_embeds.shape[1],
|
||||
)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
position_embeddings = self.rotary_emb(inputs_embeds, position_ids)
|
||||
|
||||
hidden_states = inputs_embeds.repeat(1, 1, self.config.hc_count)
|
||||
for layer_index, decoder_layer in enumerate(self.layers):
|
||||
layer_routed_experts = routed_experts[:, :, layer_index] if routed_experts is not None else None
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
input_ids,
|
||||
position_embeddings,
|
||||
cu_seqlens,
|
||||
routed_experts=layer_routed_experts,
|
||||
)
|
||||
hidden_states, _ = self.hyper_connection_mixer(hidden_states)
|
||||
return BaseModelOutput(last_hidden_state=hidden_states)
|
||||
|
||||
|
||||
class Qwen3_8FlashNextModel(nn.Module):
|
||||
def __init__(self, config: Qwen3_8FlashNextConfig) -> None:
|
||||
super().__init__()
|
||||
self.language_model = Qwen3_8FlashNextTextModel(config.text_config)
|
||||
|
||||
def get_input_embeddings(self) -> nn.Embedding:
|
||||
return self.language_model.get_input_embeddings()
|
||||
|
||||
def set_input_embeddings(self, embeddings: nn.Embedding) -> None:
|
||||
self.language_model.set_input_embeddings(embeddings)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.LongTensor,
|
||||
position_ids: torch.LongTensor | None = None,
|
||||
routed_experts: torch.LongTensor | None = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
) -> BaseModelOutput:
|
||||
return self.language_model(
|
||||
input_ids=input_ids,
|
||||
position_ids=position_ids,
|
||||
routed_experts=routed_experts,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
)
|
||||
|
||||
|
||||
class Qwen3_8FlashNextForCausalLM(Qwen3_8FlashNextPreTrainedModel):
|
||||
_tp_plan = {"lm_head": "colwise_gather_output"}
|
||||
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
||||
|
||||
def __init__(self, config: Qwen3_8FlashNextConfig) -> None:
|
||||
super().__init__(config)
|
||||
text_config = getattr(config, "text_config", config)
|
||||
self.model = (
|
||||
Qwen3_8FlashNextModel(config) if hasattr(config, "text_config") else Qwen3_8FlashNextTextModel(config)
|
||||
)
|
||||
self.vocab_size = text_config.vocab_size
|
||||
self.num_experts = text_config.num_experts
|
||||
self.num_experts_per_tok = text_config.num_experts_per_tok
|
||||
self.lm_head = VanillaOutputLinear(text_config.hidden_size, text_config.vocab_size)
|
||||
self.post_init()
|
||||
|
||||
def get_input_embeddings(self) -> nn.Embedding:
|
||||
return self.model.get_input_embeddings()
|
||||
|
||||
def set_input_embeddings(self, embeddings: nn.Embedding) -> None:
|
||||
self.model.set_input_embeddings(embeddings)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.LongTensor,
|
||||
position_ids: torch.LongTensor | None = None,
|
||||
labels: torch.LongTensor | None = None,
|
||||
logits_to_keep: int | torch.Tensor = 0,
|
||||
temperature: torch.Tensor | None = None,
|
||||
sampling_mask: torch.Tensor | None = None,
|
||||
routed_experts: torch.LongTensor | None = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
**kwargs,
|
||||
) -> PrimeLmOutput:
|
||||
outputs = self.model(
|
||||
input_ids=input_ids,
|
||||
position_ids=position_ids,
|
||||
routed_experts=routed_experts,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
)
|
||||
if isinstance(logits_to_keep, int):
|
||||
slice_indices = slice(-logits_to_keep, None) if logits_to_keep > 0 else slice(None)
|
||||
else:
|
||||
slice_indices = logits_to_keep
|
||||
return self.lm_head(
|
||||
outputs.last_hidden_state[:, slice_indices],
|
||||
labels[:, slice_indices] if labels is not None else None,
|
||||
temperature=temperature[:, slice_indices] if temperature is not None else None,
|
||||
sampling_mask=sampling_mask[:, slice_indices] if sampling_mask is not None else None,
|
||||
)
|
||||
|
||||
def init_buffers_post_meta(self) -> None:
|
||||
language_model = getattr(self.model, "language_model", self.model)
|
||||
language_model.rotary_emb.reset_parameters()
|
||||
for module in self.modules():
|
||||
if isinstance(module, NGramEmbedding):
|
||||
module.reset_parameters()
|
||||
elif isinstance(module, MoE):
|
||||
module.tokens_per_expert.zero_()
|
||||
module.routing_confidence_sum.zero_()
|
||||
if module.router.selection_bias is not None:
|
||||
module.router.selection_bias.zero_()
|
||||
|
||||
|
||||
__all__ = [
|
||||
"Qwen3_8FlashNextDecoderLayer",
|
||||
"Qwen3_8FlashNextForCausalLM",
|
||||
"Qwen3_8FlashNextModel",
|
||||
"Qwen3_8FlashNextPreTrainedModel",
|
||||
"Qwen3_8FlashNextTextModel",
|
||||
]
|
||||
@@ -0,0 +1,75 @@
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.trainer.models.layers.activations import ActivationType
|
||||
from prime_rl.trainer.models.layers.mlp import FeedForward
|
||||
from prime_rl.trainer.models.layers.moe import GroupedExperts, MoE, TokenChoiceTopKRouter
|
||||
|
||||
|
||||
class SigmoidOutputGatedFeedForward(FeedForward):
|
||||
"""Gated feed-forward layer with a sigmoid output gate."""
|
||||
|
||||
def __init__(self, dim: int, hidden_dim: int, activation: ActivationType) -> None:
|
||||
super().__init__(
|
||||
dim=dim,
|
||||
hidden_dim=hidden_dim,
|
||||
expert_type="gated",
|
||||
activation=activation,
|
||||
)
|
||||
self.output_gate = nn.Linear(dim, 1, bias=False)
|
||||
|
||||
def forward(self, x: torch.Tensor, routed_experts: torch.Tensor | None = None) -> torch.Tensor:
|
||||
return torch.sigmoid(self.output_gate(x)) * super().forward(x, routed_experts)
|
||||
|
||||
def init_weights(self, init_std: float = 0.02) -> None:
|
||||
super().init_weights(init_std)
|
||||
nn.init.trunc_normal_(self.output_gate.weight, mean=0.0, std=init_std)
|
||||
|
||||
|
||||
class SigmoidOutputGatedMoE(MoE):
|
||||
"""Top-k MoE with renormalized softmax scores and one sigmoid-gated shared expert."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
dim: int,
|
||||
expert_hidden_dim: int,
|
||||
shared_expert_hidden_dim: int,
|
||||
num_experts: int,
|
||||
top_k: int,
|
||||
activation: ActivationType,
|
||||
init_std: float,
|
||||
load_balance_coeff: float | None = None,
|
||||
) -> None:
|
||||
experts = GroupedExperts(
|
||||
dim=dim,
|
||||
hidden_dim=expert_hidden_dim,
|
||||
num_experts=num_experts,
|
||||
expert_type="gated",
|
||||
activation=activation,
|
||||
)
|
||||
experts.init_weights(init_std)
|
||||
router = TokenChoiceTopKRouter(
|
||||
dim=dim,
|
||||
num_experts=num_experts,
|
||||
top_k=top_k,
|
||||
score_func="softmax",
|
||||
route_norm=True,
|
||||
route_scale=1.0,
|
||||
selection_bias=load_balance_coeff is not None,
|
||||
)
|
||||
shared_expert = SigmoidOutputGatedFeedForward(
|
||||
dim=dim,
|
||||
hidden_dim=shared_expert_hidden_dim,
|
||||
activation=activation,
|
||||
)
|
||||
super().__init__(
|
||||
router=router,
|
||||
experts=experts,
|
||||
shared_expert=shared_expert,
|
||||
score_before_experts=False,
|
||||
load_balance_coeff=load_balance_coeff,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["SigmoidOutputGatedFeedForward", "SigmoidOutputGatedMoE"]
|
||||
@@ -0,0 +1,200 @@
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.utils.cp import CPContext, gather_for_cp
|
||||
|
||||
MASK64 = (1 << 64) - 1
|
||||
SPLITMIX_GAMMA = 0x9E3779B97F4A7C15
|
||||
SPLITMIX_MULTIPLIER_1 = 0xBF58476D1CE4E5B9
|
||||
SPLITMIX_MULTIPLIER_2 = 0x94D049BB133111EB
|
||||
NGRAM_LAYER_PRIME = 10007
|
||||
|
||||
|
||||
def splitmix64(value: int) -> int:
|
||||
value = (value + SPLITMIX_GAMMA) & MASK64
|
||||
value = ((value ^ (value >> 30)) * SPLITMIX_MULTIPLIER_1) & MASK64
|
||||
value = ((value ^ (value >> 27)) * SPLITMIX_MULTIPLIER_2) & MASK64
|
||||
return (value ^ (value >> 31)) & MASK64
|
||||
|
||||
|
||||
def is_prime(value: int) -> bool:
|
||||
if value < 2:
|
||||
return False
|
||||
for prime in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37):
|
||||
if value % prime == 0:
|
||||
return value == prime
|
||||
|
||||
exponent = value - 1
|
||||
shifts = 0
|
||||
while exponent % 2 == 0:
|
||||
exponent //= 2
|
||||
shifts += 1
|
||||
for base in (2, 325, 9375, 28178, 450775, 9780504, 1795265022):
|
||||
if base % value == 0:
|
||||
continue
|
||||
witness = pow(base, exponent, value)
|
||||
if witness in (1, value - 1):
|
||||
continue
|
||||
for _ in range(shifts - 1):
|
||||
witness = pow(witness, 2, value)
|
||||
if witness == value - 1:
|
||||
break
|
||||
else:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def nth_prime_after(start: int, count: int) -> int:
|
||||
prime = start
|
||||
for _ in range(count):
|
||||
candidate = prime + 1
|
||||
if candidate <= 2:
|
||||
prime = 2
|
||||
continue
|
||||
if candidate % 2 == 0:
|
||||
candidate += 1
|
||||
while not is_prime(candidate):
|
||||
candidate += 2
|
||||
prime = candidate
|
||||
return prime
|
||||
|
||||
|
||||
def build_hash_layout(
|
||||
*,
|
||||
ngram_size: int,
|
||||
heads_per_ngram: int,
|
||||
ngram_vocab_size: int,
|
||||
token_vocab_size: int,
|
||||
ngram_layer_index: int,
|
||||
seed: int,
|
||||
) -> tuple[list[int], list[int], list[int]]:
|
||||
max_multiplier = ((1 << 63) - 1) // token_vocab_size
|
||||
multiplier_bound = max(1, max_multiplier // 2)
|
||||
layer_seed = seed + NGRAM_LAYER_PRIME * ngram_layer_index
|
||||
multipliers = [
|
||||
2 * (splitmix64(layer_seed + SPLITMIX_GAMMA * (index + 1)) % multiplier_bound) + 1
|
||||
for index in range(ngram_size)
|
||||
]
|
||||
|
||||
num_heads = (ngram_size - 1) * heads_per_ngram
|
||||
sizes = [
|
||||
nth_prime_after(ngram_vocab_size - 1, ngram_layer_index * num_heads + head + 1) for head in range(num_heads)
|
||||
]
|
||||
offsets = []
|
||||
offset = 0
|
||||
for size in sizes:
|
||||
offsets.append(offset)
|
||||
offset += size
|
||||
return multipliers, sizes, offsets
|
||||
|
||||
|
||||
class NGramEmbedding(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
embedding_dim: int,
|
||||
ngram_size: int,
|
||||
heads_per_ngram: int,
|
||||
ngram_vocab_size: int,
|
||||
token_vocab_size: int,
|
||||
eos_token_id: int,
|
||||
vocab_size_divisor: int,
|
||||
ngram_layer_index: int,
|
||||
seed: int = 1234,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.embedding_dim = embedding_dim
|
||||
self.ngram_size = ngram_size
|
||||
self.heads_per_ngram = heads_per_ngram
|
||||
self.num_heads = (ngram_size - 1) * heads_per_ngram
|
||||
self.head_dim = embedding_dim // self.num_heads
|
||||
self.ngram_vocab_size = ngram_vocab_size
|
||||
self.token_vocab_size = token_vocab_size
|
||||
self.eos_token_id = eos_token_id
|
||||
self.ngram_layer_index = ngram_layer_index
|
||||
self.seed = seed
|
||||
|
||||
multipliers, sizes, offsets = build_hash_layout(
|
||||
ngram_size=ngram_size,
|
||||
heads_per_ngram=heads_per_ngram,
|
||||
ngram_vocab_size=ngram_vocab_size,
|
||||
token_vocab_size=token_vocab_size,
|
||||
ngram_layer_index=ngram_layer_index,
|
||||
seed=seed,
|
||||
)
|
||||
self.register_buffer("layer_multipliers", torch.tensor(multipliers, dtype=torch.long))
|
||||
self.register_buffer("ngram_heads_vocab_sizes", torch.tensor(sizes, dtype=torch.long))
|
||||
self.register_buffer("ngram_heads_offsets", torch.tensor(offsets, dtype=torch.long))
|
||||
|
||||
total_vocab_size = offsets[-1] + sizes[-1]
|
||||
padded_vocab_size = (total_vocab_size + vocab_size_divisor - 1) // vocab_size_divisor * vocab_size_divisor
|
||||
self.ngram_embedding = nn.Embedding(padded_vocab_size, self.head_dim)
|
||||
|
||||
self.cp_context = CPContext()
|
||||
|
||||
def reset_parameters(self) -> None:
|
||||
multipliers, sizes, offsets = build_hash_layout(
|
||||
ngram_size=self.ngram_size,
|
||||
heads_per_ngram=self.heads_per_ngram,
|
||||
ngram_vocab_size=self.ngram_vocab_size,
|
||||
token_vocab_size=self.token_vocab_size,
|
||||
ngram_layer_index=self.ngram_layer_index,
|
||||
seed=self.seed,
|
||||
)
|
||||
self.layer_multipliers.copy_(self.layer_multipliers.new_tensor(multipliers))
|
||||
self.ngram_heads_vocab_sizes.copy_(self.ngram_heads_vocab_sizes.new_tensor(sizes))
|
||||
self.ngram_heads_offsets.copy_(self.ngram_heads_offsets.new_tensor(offsets))
|
||||
|
||||
def compute_ngram_ids(self, input_ids: torch.Tensor, cu_seqlens: torch.Tensor) -> torch.Tensor:
|
||||
tokens = input_ids.reshape(-1).long()
|
||||
positions = torch.arange(tokens.shape[0], device=tokens.device)
|
||||
sequence_indices = torch.searchsorted(cu_seqlens[1:], positions, right=True)
|
||||
sequence_starts = cu_seqlens[:-1][sequence_indices].long()
|
||||
|
||||
eos_positions = torch.where(tokens == self.eos_token_id, positions, -1)
|
||||
latest_eos = torch.cummax(eos_positions, dim=0).values
|
||||
previous_eos = torch.cat((latest_eos.new_full((1,), -1), latest_eos[:-1]))
|
||||
segment_starts = torch.maximum(sequence_starts, previous_eos + 1)
|
||||
|
||||
shifted_tokens = [tokens]
|
||||
for shift in range(1, self.ngram_size):
|
||||
source_positions = positions - shift
|
||||
source_tokens = tokens[source_positions.clamp_min(0)]
|
||||
shifted_tokens.append(
|
||||
torch.where(
|
||||
source_positions >= segment_starts,
|
||||
source_tokens,
|
||||
source_tokens.new_full((), self.eos_token_id),
|
||||
)
|
||||
)
|
||||
|
||||
id_blocks = []
|
||||
for ngram in range(2, self.ngram_size + 1):
|
||||
mixed = shifted_tokens[0] * self.layer_multipliers[0]
|
||||
for index in range(1, ngram):
|
||||
mixed = torch.bitwise_xor(mixed, shifted_tokens[index] * self.layer_multipliers[index])
|
||||
|
||||
start = (ngram - 2) * self.heads_per_ngram
|
||||
end = start + self.heads_per_ngram
|
||||
sizes = self.ngram_heads_vocab_sizes[start:end]
|
||||
offsets = self.ngram_heads_offsets[start:end]
|
||||
id_blocks.append(torch.remainder(mixed.unsqueeze(-1), sizes) + offsets)
|
||||
return torch.cat(id_blocks, dim=-1)
|
||||
|
||||
def forward(self, input_ids: torch.Tensor, cu_seqlens: torch.Tensor) -> torch.Tensor:
|
||||
local_tokens = input_ids.numel()
|
||||
if not self.cp_context.cp_enabled:
|
||||
full_input_ids = input_ids
|
||||
else:
|
||||
full_input_ids = gather_for_cp(input_ids, self.cp_context.cp_group)
|
||||
|
||||
ngram_ids = self.compute_ngram_ids(full_input_ids, cu_seqlens)
|
||||
if self.cp_context.cp_enabled:
|
||||
local_start = self.cp_context.cp_rank * local_tokens
|
||||
ngram_ids = ngram_ids[local_start : local_start + local_tokens]
|
||||
|
||||
embeddings = self.ngram_embedding(ngram_ids).flatten(-2)
|
||||
return embeddings.reshape(*input_ids.shape, self.embedding_dim)
|
||||
|
||||
|
||||
__all__ = ["NGramEmbedding"]
|
||||
@@ -0,0 +1,25 @@
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
|
||||
class RMSNorm(nn.Module):
|
||||
"""Zero-centered RMSNorm whose effective scale is ``1 + weight``."""
|
||||
|
||||
def __init__(self, hidden_size: int, eps: float) -> None:
|
||||
super().__init__()
|
||||
self.weight = nn.Parameter(torch.empty(hidden_size))
|
||||
self.eps = eps
|
||||
self.reset_parameters()
|
||||
|
||||
def reset_parameters(self) -> None:
|
||||
nn.init.zeros_(self.weight)
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
input_dtype = hidden_states.dtype
|
||||
normalized = hidden_states.float()
|
||||
variance = normalized.square().mean(dim=-1, keepdim=True)
|
||||
normalized = normalized * torch.rsqrt(variance + self.eps)
|
||||
return ((1.0 + self.weight.float()) * normalized).to(input_dtype)
|
||||
|
||||
|
||||
__all__ = ["RMSNorm"]
|
||||
@@ -0,0 +1,114 @@
|
||||
import math
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next.hyper_connection import ExpandedRMSNorm
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next.ngram_embedding import NGramEmbedding
|
||||
from prime_rl.utils.cp import CPContext, gather_for_cp
|
||||
|
||||
|
||||
class PositionLearningEnhancement(nn.Module):
|
||||
"""Inject hashed N-gram features into the expanded residual streams."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
hidden_size: int,
|
||||
stream_count: int,
|
||||
embedding_dim: int,
|
||||
ngram_size: int,
|
||||
heads_per_ngram: int,
|
||||
ngram_vocab_size: int,
|
||||
token_vocab_size: int,
|
||||
eos_token_id: int,
|
||||
vocab_size_divisor: int,
|
||||
ngram_layer_index: int,
|
||||
conv_kernel_size: int,
|
||||
norm_eps: float,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
expanded_size = stream_count * hidden_size
|
||||
self.hidden_size = hidden_size
|
||||
self.stream_count = stream_count
|
||||
self.conv_dilation = ngram_size
|
||||
|
||||
self.ple_embedding = NGramEmbedding(
|
||||
embedding_dim=embedding_dim,
|
||||
ngram_size=ngram_size,
|
||||
heads_per_ngram=heads_per_ngram,
|
||||
ngram_vocab_size=ngram_vocab_size,
|
||||
token_vocab_size=token_vocab_size,
|
||||
eos_token_id=eos_token_id,
|
||||
vocab_size_divisor=vocab_size_divisor,
|
||||
ngram_layer_index=ngram_layer_index,
|
||||
)
|
||||
self.key_proj = nn.Linear(embedding_dim, expanded_size, bias=False)
|
||||
self.value_proj = nn.Linear(embedding_dim, hidden_size, bias=False)
|
||||
self.norm_key = ExpandedRMSNorm(hidden_size, stream_count, norm_eps)
|
||||
self.norm_query = ExpandedRMSNorm(hidden_size, stream_count, norm_eps)
|
||||
self.norm_conv = ExpandedRMSNorm(hidden_size, stream_count, norm_eps)
|
||||
self.conv1d = nn.Conv1d(
|
||||
expanded_size,
|
||||
expanded_size,
|
||||
conv_kernel_size,
|
||||
groups=expanded_size,
|
||||
dilation=ngram_size,
|
||||
bias=False,
|
||||
)
|
||||
nn.init.zeros_(self.conv1d.weight)
|
||||
|
||||
self.cp_context = CPContext()
|
||||
|
||||
def reset_parameters(self) -> None:
|
||||
nn.init.zeros_(self.conv1d.weight)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
expanded_states: torch.Tensor,
|
||||
input_ids: torch.LongTensor,
|
||||
cu_seqlens: torch.LongTensor,
|
||||
) -> torch.Tensor:
|
||||
embeddings = self.ple_embedding(input_ids, cu_seqlens).to(expanded_states.dtype)
|
||||
keys = self.norm_key(self.key_proj(embeddings))
|
||||
queries = self.norm_query(expanded_states)
|
||||
keys = keys.unflatten(-1, (self.stream_count, self.hidden_size))
|
||||
queries = queries.unflatten(-1, (self.stream_count, self.hidden_size))
|
||||
|
||||
gate = (keys * queries).sum(dim=-1, keepdim=True) / math.sqrt(self.hidden_size)
|
||||
gate = torch.sigmoid(gate.sign() * gate.abs().clamp_min(1e-6).sqrt())
|
||||
values = self.value_proj(embeddings).unsqueeze(-2)
|
||||
gated_values = gate * values
|
||||
convolution_input = self.norm_conv(gated_values.flatten(-2))
|
||||
|
||||
local_token_count = convolution_input.shape[1]
|
||||
if self.cp_context.cp_enabled:
|
||||
convolution_input = gather_for_cp(convolution_input, self.cp_context.cp_group)
|
||||
|
||||
packed_input = convolution_input.flatten(0, 1)
|
||||
positions = torch.arange(packed_input.shape[0], device=packed_input.device)
|
||||
sequence_indices = torch.searchsorted(cu_seqlens[1:], positions, right=True)
|
||||
sequence_starts = cu_seqlens[:-1][sequence_indices].long()
|
||||
convolution_output = torch.zeros_like(packed_input, dtype=torch.float32)
|
||||
weights = self.conv1d.weight[:, 0].float()
|
||||
kernel_size = weights.shape[-1]
|
||||
for kernel_index in range(kernel_size):
|
||||
delay = (kernel_size - kernel_index - 1) * self.conv_dilation
|
||||
source_positions = positions - delay
|
||||
source = packed_input[source_positions.clamp_min(0)]
|
||||
source = torch.where(
|
||||
(source_positions >= sequence_starts).unsqueeze(-1),
|
||||
source,
|
||||
torch.zeros_like(source),
|
||||
)
|
||||
convolution_output.add_(source.float() * weights[:, kernel_index])
|
||||
|
||||
convolution_output = F.silu(convolution_output.to(packed_input.dtype)).reshape_as(convolution_input)
|
||||
if self.cp_context.cp_enabled:
|
||||
local_start = self.cp_context.cp_rank * local_token_count
|
||||
convolution_output = convolution_output[:, local_start : local_start + local_token_count]
|
||||
return gated_values.flatten(-2) + convolution_output
|
||||
|
||||
|
||||
__all__ = ["PositionLearningEnhancement"]
|
||||
@@ -0,0 +1,58 @@
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.trainer.models.layers.rotary_emb import rotate_half
|
||||
|
||||
|
||||
def apply_rotary_embedding(
|
||||
hidden_states: torch.Tensor,
|
||||
cos: torch.Tensor,
|
||||
sin: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
cos = cos.unsqueeze(2)
|
||||
sin = sin.unsqueeze(2)
|
||||
rotary_dim = cos.shape[-1]
|
||||
rotated = hidden_states[..., :rotary_dim]
|
||||
rotated = (rotated * cos) + (rotate_half(rotated) * sin)
|
||||
return torch.cat((rotated, hidden_states[..., rotary_dim:]), dim=-1)
|
||||
|
||||
|
||||
class RotaryEmbedding(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
head_dim: int,
|
||||
theta: float,
|
||||
partial_rotary_factor: float,
|
||||
mrope_section: tuple[int, int, int],
|
||||
device: torch.device | None = None,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
rotary_dim = int(head_dim * partial_rotary_factor)
|
||||
self.rotary_dim = rotary_dim
|
||||
self.theta = theta
|
||||
self.mrope_section = mrope_section
|
||||
self.register_buffer("inv_freq", torch.empty(rotary_dim // 2, device=device), persistent=False)
|
||||
self.reset_parameters()
|
||||
|
||||
def reset_parameters(self) -> None:
|
||||
dimensions = torch.arange(0, self.rotary_dim, 2, dtype=torch.float32, device=self.inv_freq.device)
|
||||
self.inv_freq.copy_(1.0 / (self.theta ** (dimensions / self.rotary_dim)))
|
||||
|
||||
@torch.no_grad()
|
||||
def forward(self, hidden_states: torch.Tensor, position_ids: torch.LongTensor) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
if position_ids.ndim == 2:
|
||||
position_ids = position_ids.unsqueeze(0).expand(3, -1, -1)
|
||||
|
||||
positions = position_ids.to(device=hidden_states.device, dtype=torch.float32)
|
||||
frequencies = (self.inv_freq[None, None, :, None].float() * positions[:, :, None, :]).transpose(2, 3)
|
||||
interleaved = frequencies[0].clone()
|
||||
for dimension in (1, 2):
|
||||
indices = slice(dimension, self.mrope_section[dimension] * 3, 3)
|
||||
interleaved[..., indices] = frequencies[dimension, ..., indices]
|
||||
|
||||
embeddings = torch.cat((interleaved, interleaved), dim=-1)
|
||||
return embeddings.cos().to(hidden_states.dtype), embeddings.sin().to(hidden_states.dtype)
|
||||
|
||||
|
||||
__all__ = ["RotaryEmbedding", "apply_rotary_embedding"]
|
||||
@@ -71,12 +71,7 @@ def setup_optimizer(
|
||||
if full_offload_dtype_policy is None:
|
||||
raise ValueError("CPU optimizer offload requires an explicit per-parameter dtype policy")
|
||||
optimizer_named_params, master_weights = _create_cpu_master_weights(
|
||||
model,
|
||||
named_params,
|
||||
pin_memory=not (
|
||||
config.type in ("adamw", "sign_sgd") and full_offload_config.cpu_optimizer_backend == "native"
|
||||
),
|
||||
dtype_policy=full_offload_dtype_policy,
|
||||
model, named_params, dtype_policy=full_offload_dtype_policy
|
||||
)
|
||||
|
||||
optimizer = _create_optimizer(
|
||||
|
||||
@@ -17,7 +17,6 @@ from torch.optim import AdamW, Optimizer
|
||||
from prime_rl.configs.trainer import OptimizerInBackwardOffloadConfig
|
||||
from prime_rl.trainer.optim.base import OffloadOptimizer
|
||||
from prime_rl.trainer.optim.cpu_adam import adamw_step as native_cpu_adamw_step
|
||||
from prime_rl.trainer.optim.cpu_adam import add_bfloat16_ as native_add_bfloat16_
|
||||
from prime_rl.trainer.optim.cpu_adam import copy_or_add_bfloat16_multi_ as native_copy_or_add_bfloat16_multi_
|
||||
from prime_rl.trainer.optim.cpu_adam import load_cpu_adamw_kernel
|
||||
from prime_rl.trainer.optim.cpu_adam import sign_sgd_step as native_cpu_sign_sgd_step
|
||||
@@ -29,28 +28,14 @@ from prime_rl.utils.logger import get_logger
|
||||
class _CPUGradientBuffer:
|
||||
template: DTensor
|
||||
accumulator: torch.Tensor
|
||||
staging: torch.Tensor | None = None
|
||||
initialized: bool = False
|
||||
pending: bool = False
|
||||
staging_holds_final: bool = False
|
||||
pending_step: int = -1
|
||||
pending_backward: int = -1
|
||||
last_enqueued_backward: int = -1
|
||||
pending_generations: set[tuple[int, int]] = field(default_factory=set)
|
||||
|
||||
|
||||
@dataclass
|
||||
class _GradientCopyTask:
|
||||
event: torch.cuda.Event
|
||||
buffers: list[tuple[int, _CPUGradientBuffer, bool, bool]]
|
||||
final_backward: bool
|
||||
|
||||
|
||||
@dataclass
|
||||
class _OptimizerChunkTask:
|
||||
chunk_idx: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class _PinnedTransferSlot:
|
||||
index: int
|
||||
@@ -69,7 +54,7 @@ class _GradientTransferRequest:
|
||||
|
||||
|
||||
@dataclass
|
||||
class _BoundedGradientCopyTask:
|
||||
class _GradientCopyTask:
|
||||
request: _GradientTransferRequest
|
||||
slot: _PinnedTransferSlot
|
||||
|
||||
@@ -91,388 +76,7 @@ class _MasterWeight:
|
||||
|
||||
|
||||
class GradientOffloadManager:
|
||||
"""Offloads finalized FSDP2 sharded gradients from post-accumulate hooks."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
chunks: list[list[nn.Parameter]],
|
||||
dp_replicate: int,
|
||||
cpu_dtype: torch.dtype | None = None,
|
||||
preserve_staging_dtype: bool = False,
|
||||
chunk_ready_callback: Callable[[int], None] | None = None,
|
||||
):
|
||||
self._chunks = chunks
|
||||
self._dp_replicate = dp_replicate
|
||||
self._cpu_dtype = cpu_dtype
|
||||
self._preserve_staging_dtype = preserve_staging_dtype
|
||||
self._optimizer_param_ids = {id(param) for chunk in chunks for param in chunk}
|
||||
self._chunk_param_ids = [{id(param) for param in chunk} for chunk in chunks]
|
||||
self._chunk_by_param_id = {
|
||||
param_id: chunk_idx for chunk_idx, param_ids in enumerate(self._chunk_param_ids) for param_id in param_ids
|
||||
}
|
||||
self._buffers: dict[int, _CPUGradientBuffer] = {}
|
||||
self._chunk_ready_callback = chunk_ready_callback
|
||||
|
||||
self._d2h_stream = torch.cuda.Stream()
|
||||
self._tasks: queue.SimpleQueue[_GradientCopyTask | _OptimizerChunkTask | None] = queue.SimpleQueue()
|
||||
self._condition = threading.Condition()
|
||||
self._gradient_scale = 1.0
|
||||
self._final_backward = False
|
||||
self._overlap_optimizer = False
|
||||
self._final_enqueued_param_ids: set[int] = set()
|
||||
self._pending_chunk_param_ids: list[set[int]] = []
|
||||
self._scheduled_chunks: set[int] = set()
|
||||
self._completed_chunks = 0
|
||||
self._worker_error: BaseException | None = None
|
||||
self._logged_cpu_allocation = 0
|
||||
self._closed = False
|
||||
|
||||
params = {id(param): param for chunk in chunks for param in chunk}
|
||||
# Pin every buffer NOW, before the first collective of the job. The
|
||||
# post-accumulate hook runs inside FSDP's foreach_reduce on the autograd
|
||||
# thread; a lazy cudaHostAlloc there stalls against the device while
|
||||
# peer ranks' NCCL kernels spin waiting for this rank's next collective
|
||||
# — a distributed deadlock (deterministic at 78 layers, seen from 30k to
|
||||
# 131k tokens). Init-time pinning is the only safe window.
|
||||
#
|
||||
# Slab-allocate: one pinned block per dtype for accumulators and one for
|
||||
# staging, carved into per-param views. ~800 per-param cudaHostAllocs
|
||||
# (~1.4 TiB/node) took 10-20 min with large node skew; a handful of huge
|
||||
# allocations pins the same bytes in well under a minute.
|
||||
dtensor_params = [p for p in params.values() if isinstance(p.data, DTensor)]
|
||||
ALIGN = 256 # bytes; keeps carved views DMA-friendly
|
||||
acc_slab_numel: dict[torch.dtype, int] = {}
|
||||
stage_slab_numel: dict[torch.dtype, int] = {}
|
||||
offsets: dict[int, tuple[torch.dtype, int, torch.dtype, int, int]] = {}
|
||||
for param in dtensor_params:
|
||||
local = param.data.to_local()
|
||||
acc_dtype = self._cpu_dtype or local.dtype
|
||||
stage_dtype = local.dtype if preserve_staging_dtype else acc_dtype
|
||||
acc_align = max(1, ALIGN // torch.empty((), dtype=acc_dtype).element_size())
|
||||
stage_align = max(1, ALIGN // torch.empty((), dtype=stage_dtype).element_size())
|
||||
acc_start = acc_slab_numel.get(acc_dtype, 0)
|
||||
stage_start = stage_slab_numel.get(stage_dtype, 0)
|
||||
offsets[id(param)] = (acc_dtype, acc_start, stage_dtype, stage_start, local.numel())
|
||||
acc_slab_numel[acc_dtype] = acc_start + ((local.numel() + acc_align - 1) // acc_align * acc_align)
|
||||
stage_slab_numel[stage_dtype] = stage_start + (
|
||||
(local.numel() + stage_align - 1) // stage_align * stage_align
|
||||
)
|
||||
acc_slabs = {
|
||||
dtype: torch.empty(numel, dtype=dtype, device="cpu", pin_memory=True)
|
||||
for dtype, numel in acc_slab_numel.items()
|
||||
}
|
||||
stage_slabs = {
|
||||
dtype: torch.empty(numel, dtype=dtype, device="cpu", pin_memory=True)
|
||||
for dtype, numel in stage_slab_numel.items()
|
||||
}
|
||||
for param in dtensor_params:
|
||||
data = param.data
|
||||
local = data.to_local()
|
||||
acc_dtype, acc_start, stage_dtype, stage_start, numel = offsets[id(param)]
|
||||
accumulator = acc_slabs[acc_dtype].narrow(0, acc_start, numel).view(local.shape)
|
||||
staging = stage_slabs[stage_dtype].narrow(0, stage_start, numel).view(local.shape)
|
||||
template = copy.copy(data.detach())
|
||||
template._local_tensor = accumulator
|
||||
self._buffers[id(param)] = _CPUGradientBuffer(template, accumulator, staging=staging)
|
||||
preallocated = sum(s.nbytes for s in acc_slabs.values()) + sum(s.nbytes for s in stage_slabs.values())
|
||||
self._hook_handles = [param.register_post_accumulate_grad_hook(self._offload_hook) for param in params.values()]
|
||||
self._worker = threading.Thread(target=self._copy_worker, name="grad-offload", daemon=True)
|
||||
self._worker.start()
|
||||
get_logger().info(
|
||||
"Gradient CPU offload uses FSDP sharded-parameter post-accumulate hooks "
|
||||
f"({preallocated / 1024**3:.2f} GiB pinned accumulator+staging preallocated)"
|
||||
)
|
||||
|
||||
def _copy_worker(self) -> None:
|
||||
try:
|
||||
self._copy_worker_loop()
|
||||
except BaseException as error:
|
||||
with self._condition:
|
||||
self._worker_error = error
|
||||
self._condition.notify_all()
|
||||
|
||||
def _copy_worker_loop(self) -> None:
|
||||
while True:
|
||||
task = self._tasks.get()
|
||||
if task is None:
|
||||
return
|
||||
if isinstance(task, _OptimizerChunkTask):
|
||||
self._run_optimizer_chunk(task.chunk_idx)
|
||||
continue
|
||||
task.event.synchronize()
|
||||
for param_id, buffer, accumulate, copied_to_staging in task.buffers:
|
||||
assert buffer.staging is not None
|
||||
if task.final_backward and not accumulate and copied_to_staging:
|
||||
buffer.staging_holds_final = True
|
||||
elif accumulate:
|
||||
if buffer.accumulator.dtype == torch.float32 and buffer.staging.dtype == torch.bfloat16:
|
||||
native_add_bfloat16_(buffer.accumulator, buffer.staging)
|
||||
else:
|
||||
buffer.accumulator.add_(buffer.staging)
|
||||
buffer.staging_holds_final = False
|
||||
elif copied_to_staging:
|
||||
buffer.accumulator.copy_(buffer.staging)
|
||||
buffer.staging_holds_final = False
|
||||
with self._condition:
|
||||
buffer.initialized = True
|
||||
buffer.pending = False
|
||||
self._condition.notify_all()
|
||||
if task.final_backward:
|
||||
self._mark_final_param_ready(param_id)
|
||||
|
||||
def _raise_worker_error(self) -> None:
|
||||
if self._worker_error is not None:
|
||||
raise RuntimeError("Gradient offload worker failed") from self._worker_error
|
||||
|
||||
def _mark_final_param_ready(self, param_id: int) -> None:
|
||||
chunk_idx = self._chunk_by_param_id[param_id]
|
||||
should_run = False
|
||||
with self._condition:
|
||||
pending = self._pending_chunk_param_ids[chunk_idx]
|
||||
pending.discard(param_id)
|
||||
if not pending and chunk_idx not in self._scheduled_chunks:
|
||||
self._scheduled_chunks.add(chunk_idx)
|
||||
should_run = True
|
||||
if should_run:
|
||||
self._run_optimizer_chunk(chunk_idx)
|
||||
|
||||
def _run_optimizer_chunk(self, chunk_idx: int) -> None:
|
||||
if self._chunk_ready_callback is None:
|
||||
return
|
||||
self._chunk_ready_callback(chunk_idx)
|
||||
with self._condition:
|
||||
self._completed_chunks += 1
|
||||
self._condition.notify_all()
|
||||
|
||||
def begin_step(self, gradient_scale: float, *, overlap_optimizer: bool) -> None:
|
||||
self.wait()
|
||||
with self._condition:
|
||||
self._raise_worker_error()
|
||||
self._gradient_scale = gradient_scale
|
||||
self._overlap_optimizer = overlap_optimizer and self._chunk_ready_callback is not None
|
||||
self._final_backward = False
|
||||
self._final_enqueued_param_ids.clear()
|
||||
self._pending_chunk_param_ids = []
|
||||
self._scheduled_chunks.clear()
|
||||
self._completed_chunks = 0
|
||||
|
||||
def begin_backward(self, *, final_backward: bool) -> None:
|
||||
self._final_backward = final_backward
|
||||
if final_backward and self._overlap_optimizer:
|
||||
with self._condition:
|
||||
self._final_enqueued_param_ids.clear()
|
||||
self._pending_chunk_param_ids = [set(param_ids) for param_ids in self._chunk_param_ids]
|
||||
self._scheduled_chunks.clear()
|
||||
self._completed_chunks = 0
|
||||
|
||||
def _get_buffer(self, param: nn.Parameter, grad: DTensor) -> _CPUGradientBuffer:
|
||||
param_id = id(param)
|
||||
if param_id not in self._buffers:
|
||||
local_grad = grad.to_local()
|
||||
accumulator = torch.empty_like(
|
||||
local_grad,
|
||||
dtype=self._cpu_dtype or local_grad.dtype,
|
||||
device="cpu",
|
||||
pin_memory=True,
|
||||
)
|
||||
template = copy.copy(grad)
|
||||
template._local_tensor = accumulator
|
||||
staging = torch.empty_like(
|
||||
local_grad,
|
||||
dtype=local_grad.dtype if self._preserve_staging_dtype else accumulator.dtype,
|
||||
device="cpu",
|
||||
pin_memory=True,
|
||||
)
|
||||
self._buffers[param_id] = _CPUGradientBuffer(template, accumulator, staging)
|
||||
return self._buffers[param_id]
|
||||
|
||||
def _wait_buffer(self, buffer: _CPUGradientBuffer) -> None:
|
||||
with self._condition:
|
||||
self._condition.wait_for(lambda: self._worker_error is not None or not buffer.pending)
|
||||
self._raise_worker_error()
|
||||
|
||||
@torch.no_grad()
|
||||
def _offload_params(
|
||||
self,
|
||||
params: list[nn.Parameter],
|
||||
) -> None:
|
||||
copies: list[tuple[int, _CPUGradientBuffer, bool, bool]] = []
|
||||
current_stream = torch.cuda.current_stream()
|
||||
self._d2h_stream.wait_stream(current_stream)
|
||||
with torch.cuda.stream(self._d2h_stream):
|
||||
for param in params:
|
||||
if id(param) not in self._optimizer_param_ids or param.grad is None:
|
||||
continue
|
||||
if not isinstance(param.grad, DTensor):
|
||||
raise TypeError(f"Expected FSDP2 DTensor gradient, got {type(param.grad)}")
|
||||
buffer = self._get_buffer(param, param.grad)
|
||||
self._wait_buffer(buffer)
|
||||
local_grad = param.grad.to_local()
|
||||
accumulate = buffer.initialized
|
||||
if buffer.staging is None:
|
||||
buffer.staging = torch.empty_like(buffer.accumulator, pin_memory=True)
|
||||
copied_to_staging = accumulate or (
|
||||
self._preserve_staging_dtype
|
||||
and self._final_backward
|
||||
and self._overlap_optimizer
|
||||
and buffer.staging.dtype != buffer.accumulator.dtype
|
||||
)
|
||||
destination = buffer.staging if copied_to_staging else buffer.accumulator
|
||||
assert destination is not None
|
||||
destination.copy_(local_grad, non_blocking=True)
|
||||
local_grad.record_stream(self._d2h_stream)
|
||||
buffer.pending = True
|
||||
param_id = id(param)
|
||||
copies.append((param_id, buffer, accumulate, copied_to_staging))
|
||||
if self._final_backward and self._overlap_optimizer:
|
||||
self._final_enqueued_param_ids.add(param_id)
|
||||
param.grad = None
|
||||
if copies:
|
||||
event = self._d2h_stream.record_event()
|
||||
self._tasks.put(_GradientCopyTask(event, copies, self._final_backward and self._overlap_optimizer))
|
||||
|
||||
def _offload_hook(self, param: torch.Tensor) -> None:
|
||||
if not isinstance(param, nn.Parameter):
|
||||
raise TypeError(f"Expected parameter in post-accumulate hook, got {type(param)}")
|
||||
self._offload_params([param])
|
||||
|
||||
def finish_backward(self, *, wait_for_copies: bool = True) -> None:
|
||||
remaining = [param for chunk in self._chunks for param in chunk if param.grad is not None]
|
||||
self._offload_params(remaining)
|
||||
if self._final_backward and self._overlap_optimizer:
|
||||
missing_param_ids = self._optimizer_param_ids - self._final_enqueued_param_ids
|
||||
ready_chunks = []
|
||||
with self._condition:
|
||||
for param_id in missing_param_ids:
|
||||
chunk_idx = self._chunk_by_param_id[param_id]
|
||||
pending = self._pending_chunk_param_ids[chunk_idx]
|
||||
pending.discard(param_id)
|
||||
if not pending and chunk_idx not in self._scheduled_chunks:
|
||||
self._scheduled_chunks.add(chunk_idx)
|
||||
ready_chunks.append(chunk_idx)
|
||||
for chunk_idx in ready_chunks:
|
||||
self._tasks.put(_OptimizerChunkTask(chunk_idx))
|
||||
if wait_for_copies:
|
||||
self.wait()
|
||||
if wait_for_copies:
|
||||
allocated = sum(
|
||||
buffer.accumulator.nbytes + (buffer.staging.nbytes if buffer.staging is not None else 0)
|
||||
for buffer in self._buffers.values()
|
||||
)
|
||||
if allocated != self._logged_cpu_allocation:
|
||||
get_logger().info(f"Gradient CPU offload allocated {allocated / 1024**3:.2f} GiB pinned RAM")
|
||||
self._logged_cpu_allocation = allocated
|
||||
|
||||
def wait(self) -> None:
|
||||
with self._condition:
|
||||
self._condition.wait_for(
|
||||
lambda: self._worker_error is not None or not any(buffer.pending for buffer in self._buffers.values())
|
||||
)
|
||||
self._raise_worker_error()
|
||||
|
||||
def wait_for_optimizer(self) -> None:
|
||||
if not self._overlap_optimizer:
|
||||
return
|
||||
with self._condition:
|
||||
self._condition.wait_for(
|
||||
lambda: self._worker_error is not None or self._completed_chunks == len(self._chunks)
|
||||
)
|
||||
self._raise_worker_error()
|
||||
|
||||
@property
|
||||
def optimizer_overlapped(self) -> bool:
|
||||
return self._overlap_optimizer
|
||||
|
||||
@property
|
||||
def gradient_scale(self) -> float:
|
||||
return self._gradient_scale
|
||||
|
||||
@torch.no_grad()
|
||||
def scale_(self, factor: float) -> None:
|
||||
self.wait()
|
||||
self._gradient_scale *= factor
|
||||
|
||||
@torch.no_grad()
|
||||
def clip_grad_norm_(self, max_norm: float) -> torch.Tensor:
|
||||
if self._overlap_optimizer:
|
||||
raise RuntimeError("Gradient clipping cannot run after optimizer-in-backward has started")
|
||||
self.wait()
|
||||
local_squared_norm = sum(
|
||||
torch.linalg.vector_norm(buffer.accumulator, dtype=torch.float32).square().item()
|
||||
for buffer in self._buffers.values()
|
||||
if buffer.initialized
|
||||
)
|
||||
local_squared_norm *= self._gradient_scale**2
|
||||
total_norm = torch.tensor(local_squared_norm, dtype=torch.float32, device="cuda")
|
||||
dist.all_reduce(total_norm, op=dist.ReduceOp.SUM)
|
||||
total_norm.div_(self._dp_replicate).sqrt_()
|
||||
clip_coefficient = torch.clamp(max_norm / (total_norm + 1e-6), max=1.0).item()
|
||||
self._gradient_scale *= clip_coefficient
|
||||
return total_norm
|
||||
|
||||
def load_cpu_chunk(
|
||||
self,
|
||||
chunk_idx: int,
|
||||
target_params: list[nn.Parameter],
|
||||
*,
|
||||
wait: bool = True,
|
||||
apply_scale: bool = True,
|
||||
allow_staging_gradient: bool = False,
|
||||
assign_grad: bool = True,
|
||||
) -> list[torch.Tensor | None]:
|
||||
if wait:
|
||||
self.wait()
|
||||
source_params = self._chunks[chunk_idx]
|
||||
if len(source_params) != len(target_params):
|
||||
raise ValueError("Gradient source and target chunks must have the same size")
|
||||
gradients: list[torch.Tensor | None] = []
|
||||
for source_param, target_param in zip(source_params, target_params):
|
||||
buffer = self._buffers.get(id(source_param))
|
||||
if buffer is None or not buffer.initialized:
|
||||
gradients.append(None)
|
||||
if assign_grad:
|
||||
target_param.grad = None
|
||||
continue
|
||||
grad = (
|
||||
buffer.staging
|
||||
if allow_staging_gradient and buffer.staging_holds_final and buffer.staging is not None
|
||||
else buffer.accumulator.float()
|
||||
)
|
||||
if apply_scale and self._gradient_scale != 1.0:
|
||||
grad.mul_(self._gradient_scale)
|
||||
gradients.append(grad)
|
||||
if assign_grad:
|
||||
target_param.grad = grad
|
||||
return gradients
|
||||
|
||||
def release_chunk(self, chunk_idx: int, target_params: list[nn.Parameter] | None = None) -> None:
|
||||
for param in self._chunks[chunk_idx]:
|
||||
param.grad = None
|
||||
if target_params is not None:
|
||||
for param in target_params:
|
||||
param.grad = None
|
||||
|
||||
def zero_grad(self) -> None:
|
||||
self.wait()
|
||||
for buffer in self._buffers.values():
|
||||
buffer.initialized = False
|
||||
buffer.staging_holds_final = False
|
||||
self._gradient_scale = 1.0
|
||||
|
||||
def close(self) -> None:
|
||||
if self._closed:
|
||||
return
|
||||
self.wait_for_optimizer()
|
||||
self.wait()
|
||||
for handle in self._hook_handles:
|
||||
handle.remove()
|
||||
self._tasks.put(None)
|
||||
self._worker.join()
|
||||
self._closed = True
|
||||
|
||||
|
||||
class BoundedGradientOffloadManager(GradientOffloadManager):
|
||||
"""Native full-offload pipeline with pageable state and bounded pinned transfer buffers."""
|
||||
"""Full-offload gradient pipeline with pageable FP32 accumulators and bounded pinned transfer buffers."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -488,8 +92,6 @@ class BoundedGradientOffloadManager(GradientOffloadManager):
|
||||
):
|
||||
self._chunks = chunks
|
||||
self._dp_replicate = dp_replicate
|
||||
self._cpu_dtype = torch.float32
|
||||
self._preserve_staging_dtype = False
|
||||
self._chunk_ready_callback = chunk_ready_callback
|
||||
self._timeout_seconds = timeout_seconds
|
||||
# Per-step wall-time accumulators; each key is written by exactly one pipeline thread.
|
||||
@@ -512,7 +114,7 @@ class BoundedGradientOffloadManager(GradientOffloadManager):
|
||||
self._compute_dtypes = compute_dtypes
|
||||
dtensor_params = [param for param in params.values() if isinstance(param.data, DTensor)]
|
||||
if len(dtensor_params) != len(params):
|
||||
raise TypeError("Bounded gradient offload requires FSDP2 DTensor parameters")
|
||||
raise TypeError("Gradient offload requires FSDP2 DTensor parameters")
|
||||
|
||||
alignment = 256 // torch.empty((), dtype=torch.float32).element_size()
|
||||
offsets: dict[int, int] = {}
|
||||
@@ -566,7 +168,7 @@ class BoundedGradientOffloadManager(GradientOffloadManager):
|
||||
self._transfer_requests: queue.SimpleQueue[_GradientTransferRequest | _BackwardBoundaryTask | None] = (
|
||||
queue.SimpleQueue()
|
||||
)
|
||||
self._tasks: queue.SimpleQueue[_BoundedGradientCopyTask | _BackwardBoundaryTask | None] = queue.SimpleQueue()
|
||||
self._tasks: queue.SimpleQueue[_GradientCopyTask | _BackwardBoundaryTask | None] = queue.SimpleQueue()
|
||||
self._release_tasks: queue.SimpleQueue[_PinnedTransferSlot | None] = queue.SimpleQueue()
|
||||
self._condition = threading.Condition()
|
||||
self._gradient_scale = 1.0
|
||||
@@ -651,7 +253,7 @@ class BoundedGradientOffloadManager(GradientOffloadManager):
|
||||
def _total_free_slot_count(
|
||||
slots_by_dtype: dict[torch.dtype, dict[str, queue.Queue[_PinnedTransferSlot]]],
|
||||
) -> int:
|
||||
return sum(BoundedGradientOffloadManager._free_slot_count(slots) for slots in slots_by_dtype.values())
|
||||
return sum(GradientOffloadManager._free_slot_count(slots) for slots in slots_by_dtype.values())
|
||||
|
||||
@staticmethod
|
||||
def _total_slot_count(slots_by_dtype: dict[torch.dtype, list[_PinnedTransferSlot]]) -> int:
|
||||
@@ -750,10 +352,10 @@ class BoundedGradientOffloadManager(GradientOffloadManager):
|
||||
destination.copy_(task.local_grad, non_blocking=True)
|
||||
task.local_grad.record_stream(self._d2h_stream)
|
||||
slot.event.record(self._d2h_stream)
|
||||
self._tasks.put(_BoundedGradientCopyTask(task, slot))
|
||||
self._tasks.put(_GradientCopyTask(task, slot))
|
||||
|
||||
def _copy_worker_loop(self) -> None:
|
||||
deferred: _BoundedGradientCopyTask | _BackwardBoundaryTask | None = None
|
||||
deferred: _GradientCopyTask | _BackwardBoundaryTask | None = None
|
||||
stop_after_batch = False
|
||||
while True:
|
||||
task = deferred if deferred is not None else self._tasks.get()
|
||||
@@ -995,6 +597,46 @@ class BoundedGradientOffloadManager(GradientOffloadManager):
|
||||
if self._overlap_optimizer:
|
||||
self._wait_for(lambda: self._completed_chunks == len(self._chunks), "CPU optimizer chunks")
|
||||
|
||||
@property
|
||||
def optimizer_overlapped(self) -> bool:
|
||||
return self._overlap_optimizer
|
||||
|
||||
@property
|
||||
def gradient_scale(self) -> float:
|
||||
return self._gradient_scale
|
||||
|
||||
@torch.no_grad()
|
||||
def scale_(self, factor: float) -> None:
|
||||
self.wait()
|
||||
self._gradient_scale *= factor
|
||||
|
||||
@torch.no_grad()
|
||||
def clip_grad_norm_(self, max_norm: float) -> torch.Tensor:
|
||||
if self._overlap_optimizer:
|
||||
raise RuntimeError("Gradient clipping cannot run after optimizer-in-backward has started")
|
||||
self.wait()
|
||||
local_squared_norm = sum(
|
||||
torch.linalg.vector_norm(buffer.accumulator, dtype=torch.float32).square().item()
|
||||
for buffer in self._buffers.values()
|
||||
if buffer.initialized
|
||||
)
|
||||
local_squared_norm *= self._gradient_scale**2
|
||||
total_norm = torch.tensor(local_squared_norm, dtype=torch.float32, device="cuda")
|
||||
dist.all_reduce(total_norm, op=dist.ReduceOp.SUM)
|
||||
total_norm.div_(self._dp_replicate).sqrt_()
|
||||
clip_coefficient = torch.clamp(max_norm / (total_norm + 1e-6), max=1.0).item()
|
||||
self._gradient_scale *= clip_coefficient
|
||||
return total_norm
|
||||
|
||||
def load_cpu_chunk(self, chunk_idx: int, *, wait: bool = True) -> list[torch.Tensor | None]:
|
||||
if wait:
|
||||
self.wait()
|
||||
gradients: list[torch.Tensor | None] = []
|
||||
for param in self._chunks[chunk_idx]:
|
||||
buffer = self._buffers[id(param)]
|
||||
gradients.append(buffer.accumulator if buffer.initialized else None)
|
||||
return gradients
|
||||
|
||||
def acquire_output_chunk(self, chunk_idx: int) -> tuple[list[_PinnedTransferSlot], list[torch.Tensor]]:
|
||||
chunk_numel: dict[torch.dtype, int] = defaultdict(int)
|
||||
for param in self._chunks[chunk_idx]:
|
||||
@@ -1032,7 +674,6 @@ class BoundedGradientOffloadManager(GradientOffloadManager):
|
||||
self.wait()
|
||||
for buffer in self._buffers.values():
|
||||
buffer.initialized = False
|
||||
buffer.staging_holds_final = False
|
||||
buffer.pending_generations.clear()
|
||||
self._gradient_scale = 1.0
|
||||
|
||||
@@ -1088,44 +729,23 @@ class FullCPUOffloadOptimizer(OffloadOptimizer):
|
||||
self._h2d_stream = torch.cuda.Stream()
|
||||
self._d2h_stream = torch.cuda.Stream()
|
||||
self._cuda_device = torch.cuda.current_device()
|
||||
self._all_param_groups = self.optimizer.param_groups
|
||||
self._chunk_groups = self._build_chunk_groups()
|
||||
self._native_cpu_adamw = isinstance(optimizer, AdamW) and offload_config.cpu_optimizer_backend == "native"
|
||||
self._native_cpu_sign_sgd = isinstance(optimizer, SignSGD) and offload_config.cpu_optimizer_backend == "native"
|
||||
self._native_cpu_optimizer = self._native_cpu_adamw or self._native_cpu_sign_sgd
|
||||
self._fused_cpu_adamw = (
|
||||
isinstance(optimizer, AdamW)
|
||||
and all(group["fused"] for group in optimizer.param_groups)
|
||||
and not self._native_cpu_adamw
|
||||
self._adamw = isinstance(optimizer, AdamW)
|
||||
get_logger().info(
|
||||
f"Loading native read-only-gradient multi-tensor CPU {'AdamW' if self._adamw else 'SignSGD'} kernel"
|
||||
)
|
||||
load_cpu_adamw_kernel()
|
||||
self._gradient_manager = GradientOffloadManager(
|
||||
[[master_weights[id(param)].model_param for param in chunk] for chunk in self._chunks],
|
||||
dp_replicate,
|
||||
buffer_count=self._TRANSFER_BUFFER_COUNT,
|
||||
max_inflight_backwards=self._MAX_INFLIGHT_BACKWARDS,
|
||||
timeout_seconds=self._TIMEOUT_SECONDS,
|
||||
target_chunk_numel=self._TARGET_CPU_CHUNK_NUMEL,
|
||||
chunk_ready_callback=self._step_cpu_chunk,
|
||||
gradient_dtypes={id(master.model_param): master.gradient_dtype for master in master_weights.values()},
|
||||
compute_dtypes={id(master.model_param): master.compute_dtype for master in master_weights.values()},
|
||||
)
|
||||
self._adamw_grad_scale = torch.ones((), dtype=torch.float32) if self._fused_cpu_adamw else None
|
||||
self._adamw_found_inf = torch.zeros((), dtype=torch.float32) if self._fused_cpu_adamw else None
|
||||
if self._native_cpu_optimizer:
|
||||
kernel_name = "AdamW" if self._native_cpu_adamw else "SignSGD"
|
||||
get_logger().info(f"Loading native read-only-gradient multi-tensor CPU {kernel_name} kernel")
|
||||
load_cpu_adamw_kernel()
|
||||
gradient_chunks = [[master_weights[id(param)].model_param for param in chunk] for chunk in self._chunks]
|
||||
if self._native_cpu_optimizer:
|
||||
gradient_dtypes = {id(master.model_param): master.gradient_dtype for master in master_weights.values()}
|
||||
compute_dtypes = {id(master.model_param): master.compute_dtype for master in master_weights.values()}
|
||||
self._gradient_manager = BoundedGradientOffloadManager(
|
||||
gradient_chunks,
|
||||
dp_replicate,
|
||||
buffer_count=self._TRANSFER_BUFFER_COUNT,
|
||||
max_inflight_backwards=self._MAX_INFLIGHT_BACKWARDS,
|
||||
timeout_seconds=self._TIMEOUT_SECONDS,
|
||||
target_chunk_numel=self._TARGET_CPU_CHUNK_NUMEL,
|
||||
chunk_ready_callback=self._step_cpu_chunk,
|
||||
gradient_dtypes=gradient_dtypes,
|
||||
compute_dtypes=compute_dtypes,
|
||||
)
|
||||
else:
|
||||
self._gradient_manager = GradientOffloadManager(
|
||||
gradient_chunks,
|
||||
dp_replicate,
|
||||
cpu_dtype=torch.float32,
|
||||
chunk_ready_callback=self._step_cpu_chunk,
|
||||
)
|
||||
self._initialize_cpu_optimizer_state()
|
||||
|
||||
def _build_chunks(self) -> list[list[nn.Parameter]]:
|
||||
@@ -1162,41 +782,26 @@ class FullCPUOffloadOptimizer(OffloadOptimizer):
|
||||
self,
|
||||
chunk_idx: int,
|
||||
stream: torch.cuda.Stream,
|
||||
sources: list[torch.Tensor] | None = None,
|
||||
sources: list[torch.Tensor],
|
||||
) -> None:
|
||||
assert self._master_weights is not None
|
||||
if sources is not None and len(sources) != len(self._chunks[chunk_idx]):
|
||||
raise ValueError("Compute-weight sources must match the optimizer chunk")
|
||||
with torch.cuda.stream(stream):
|
||||
for param_idx, param in enumerate(self._chunks[chunk_idx]):
|
||||
master = self._master_weights[id(param)]
|
||||
if not isinstance(master.model_param, DTensor):
|
||||
raise TypeError(f"Expected FSDP2 DTensor parameter, got {type(master.model_param)}")
|
||||
source = sources[param_idx] if sources is not None else master.cpu_tensor
|
||||
source = sources[param_idx]
|
||||
local_param = master.model_param.to_local()
|
||||
if local_param.dtype != master.compute_dtype:
|
||||
raise TypeError(
|
||||
f"Full-offload compute dtype changed: expected {master.compute_dtype}, got {local_param.dtype}"
|
||||
)
|
||||
if sources is not None and source.dtype != master.compute_dtype:
|
||||
if source.dtype != master.compute_dtype:
|
||||
raise TypeError(
|
||||
f"Full-offload H2D source dtype mismatch: expected {master.compute_dtype}, got {source.dtype}"
|
||||
)
|
||||
local_param.copy_(source, non_blocking=True)
|
||||
|
||||
@torch.no_grad()
|
||||
def _step_chunk(self, chunk_idx: int):
|
||||
"""Run optimizer.step() for a single chunk by temporarily swapping param_groups."""
|
||||
chunk_groups = []
|
||||
for group, params in self._chunk_groups[chunk_idx]:
|
||||
new_group = {k: v for k, v in group.items() if k != "params"}
|
||||
new_group["params"] = params
|
||||
chunk_groups.append(new_group)
|
||||
self.optimizer.param_groups = chunk_groups
|
||||
result = self.optimizer.step()
|
||||
self.optimizer.param_groups = self._all_param_groups
|
||||
return result
|
||||
|
||||
def _step_native_cpu_adamw_chunk(
|
||||
self,
|
||||
chunk_idx: int,
|
||||
@@ -1274,57 +879,23 @@ class FullCPUOffloadOptimizer(OffloadOptimizer):
|
||||
gradients: list[torch.Tensor | None],
|
||||
compute_params: list[torch.Tensor],
|
||||
) -> None:
|
||||
if self._native_cpu_adamw:
|
||||
if self._adamw:
|
||||
self._step_native_cpu_adamw_chunk(chunk_idx, gradients, compute_params)
|
||||
else:
|
||||
self._step_native_cpu_sign_sgd_chunk(chunk_idx, gradients, compute_params)
|
||||
|
||||
def _step_cpu_chunk(self, chunk_idx: int) -> None:
|
||||
assert self._gradient_manager is not None
|
||||
self._prepare_fused_cpu_adamw()
|
||||
gradients = self._gradient_manager.load_cpu_chunk(
|
||||
chunk_idx,
|
||||
self._chunks[chunk_idx],
|
||||
wait=False,
|
||||
apply_scale=not (self._native_cpu_optimizer or self._fused_cpu_adamw),
|
||||
assign_grad=not self._native_cpu_optimizer,
|
||||
)
|
||||
if self._native_cpu_optimizer:
|
||||
if not isinstance(self._gradient_manager, BoundedGradientOffloadManager):
|
||||
raise TypeError("Native CPU optimizers require bounded gradient offload")
|
||||
timings = self._gradient_manager._timings
|
||||
acquire_start = time.perf_counter()
|
||||
output_slots, compute_params = self._gradient_manager.acquire_output_chunk(chunk_idx)
|
||||
kernel_start = time.perf_counter()
|
||||
timings["output_slot_wait"] = timings.get("output_slot_wait", 0.0) + kernel_start - acquire_start
|
||||
self._step_native_cpu_chunk(chunk_idx, gradients, compute_params)
|
||||
timings["optimizer_kernel"] = timings.get("optimizer_kernel", 0.0) + time.perf_counter() - kernel_start
|
||||
else:
|
||||
self._step_chunk(chunk_idx)
|
||||
self._gradient_manager.release_chunk(chunk_idx, self._chunks[chunk_idx])
|
||||
gradients = self._gradient_manager.load_cpu_chunk(chunk_idx, wait=False)
|
||||
timings = self._gradient_manager._timings
|
||||
acquire_start = time.perf_counter()
|
||||
output_slots, compute_params = self._gradient_manager.acquire_output_chunk(chunk_idx)
|
||||
kernel_start = time.perf_counter()
|
||||
timings["output_slot_wait"] = timings.get("output_slot_wait", 0.0) + kernel_start - acquire_start
|
||||
self._step_native_cpu_chunk(chunk_idx, gradients, compute_params)
|
||||
timings["optimizer_kernel"] = timings.get("optimizer_kernel", 0.0) + time.perf_counter() - kernel_start
|
||||
with torch.cuda.device(self._cuda_device):
|
||||
self._update_compute_weights(
|
||||
chunk_idx,
|
||||
self._h2d_stream,
|
||||
compute_params if self._native_cpu_optimizer else None,
|
||||
)
|
||||
if self._native_cpu_optimizer:
|
||||
self._gradient_manager.release_output_chunk(output_slots, self._h2d_stream)
|
||||
|
||||
def _prepare_fused_cpu_adamw(self) -> None:
|
||||
if not self._fused_cpu_adamw:
|
||||
return
|
||||
assert self._gradient_manager is not None
|
||||
assert self._adamw_grad_scale is not None
|
||||
assert self._adamw_found_inf is not None
|
||||
self._adamw_grad_scale.fill_(1.0 / self._gradient_manager.gradient_scale)
|
||||
self.optimizer.grad_scale = self._adamw_grad_scale
|
||||
self.optimizer.found_inf = self._adamw_found_inf
|
||||
|
||||
def _record_native_optimizer_step(self) -> None:
|
||||
if self._native_cpu_optimizer:
|
||||
# LRScheduler normally sets this marker through its optimizer.step wrapper.
|
||||
self.optimizer._opt_called = True
|
||||
self._update_compute_weights(chunk_idx, self._h2d_stream, compute_params)
|
||||
self._gradient_manager.release_output_chunk(output_slots, self._h2d_stream)
|
||||
|
||||
def step(self, closure=None):
|
||||
if closure is not None:
|
||||
@@ -1333,44 +904,25 @@ class FullCPUOffloadOptimizer(OffloadOptimizer):
|
||||
drain_start = time.perf_counter()
|
||||
self._gradient_manager.wait_for_optimizer()
|
||||
torch.cuda.current_stream().wait_stream(self._h2d_stream)
|
||||
if isinstance(self._gradient_manager, BoundedGradientOffloadManager):
|
||||
timings = self._gradient_manager.consume_timings()
|
||||
timings["drain"] = time.perf_counter() - drain_start
|
||||
get_logger().debug(
|
||||
"Offload pipeline: " + " ".join(f"{key}={value:.3f}s" for key, value in sorted(timings.items()))
|
||||
)
|
||||
self._record_native_optimizer_step()
|
||||
timings = self._gradient_manager.consume_timings()
|
||||
timings["drain"] = time.perf_counter() - drain_start
|
||||
get_logger().debug(
|
||||
"Offload pipeline: " + " ".join(f"{key}={value:.3f}s" for key, value in sorted(timings.items()))
|
||||
)
|
||||
# LRScheduler normally sets this marker through its optimizer.step wrapper.
|
||||
self.optimizer._opt_called = True
|
||||
self._initialized = True
|
||||
return
|
||||
# Synchronous path (validation steps and checkpoint boundaries).
|
||||
self._prepare_fused_cpu_adamw()
|
||||
gradients_by_chunk = []
|
||||
gradients_by_chunk = [self._gradient_manager.load_cpu_chunk(i) for i in range(len(self._chunks))]
|
||||
for i in range(len(self._chunks)):
|
||||
gradients_by_chunk.append(
|
||||
self._gradient_manager.load_cpu_chunk(
|
||||
i,
|
||||
self._chunks[i],
|
||||
apply_scale=not (self._native_cpu_optimizer or self._fused_cpu_adamw),
|
||||
assign_grad=not self._native_cpu_optimizer,
|
||||
)
|
||||
)
|
||||
if self._native_cpu_optimizer:
|
||||
if not isinstance(self._gradient_manager, BoundedGradientOffloadManager):
|
||||
raise TypeError("Native CPU optimizers require bounded gradient offload")
|
||||
for i in range(len(self._chunks)):
|
||||
output_slots, compute_params = self._gradient_manager.acquire_output_chunk(i)
|
||||
self._step_native_cpu_chunk(i, gradients_by_chunk[i], compute_params)
|
||||
self._gradient_manager.release_chunk(i, self._chunks[i])
|
||||
self._update_compute_weights(i, self._h2d_stream, compute_params)
|
||||
self._gradient_manager.release_output_chunk(output_slots, self._h2d_stream)
|
||||
else:
|
||||
self.optimizer.step()
|
||||
for i in range(len(self._chunks)):
|
||||
self._gradient_manager.release_chunk(i, self._chunks[i])
|
||||
self._update_compute_weights(i, self._h2d_stream)
|
||||
output_slots, compute_params = self._gradient_manager.acquire_output_chunk(i)
|
||||
self._step_native_cpu_chunk(i, gradients_by_chunk[i], compute_params)
|
||||
self._update_compute_weights(i, self._h2d_stream, compute_params)
|
||||
self._gradient_manager.release_output_chunk(output_slots, self._h2d_stream)
|
||||
torch.cuda.current_stream().wait_stream(self._h2d_stream)
|
||||
torch.cuda.synchronize()
|
||||
self._record_native_optimizer_step()
|
||||
self.optimizer._opt_called = True
|
||||
self._initialized = True
|
||||
|
||||
def zero_grad(self, set_to_none: bool = True):
|
||||
@@ -1407,30 +959,6 @@ class FullCPUOffloadOptimizer(OffloadOptimizer):
|
||||
return
|
||||
if self.optimizer.state:
|
||||
return
|
||||
if self._native_cpu_adamw:
|
||||
self._initialize_native_cpu_adamw_state()
|
||||
return
|
||||
lrs = []
|
||||
for group in self.optimizer.param_groups:
|
||||
lrs.append(group["lr"])
|
||||
group["lr"] = 0.0
|
||||
for param in group["params"]:
|
||||
if param.requires_grad:
|
||||
param.grad = torch.zeros_like(param)
|
||||
self.optimizer.step()
|
||||
self.optimizer.zero_grad(set_to_none=True)
|
||||
for state in self.optimizer.state.values():
|
||||
step = state.get("step")
|
||||
if isinstance(step, torch.Tensor):
|
||||
step.zero_()
|
||||
elif step is not None:
|
||||
state["step"] = 0
|
||||
for group, lr in zip(self.optimizer.param_groups, lrs):
|
||||
group["lr"] = lr
|
||||
if "step" in group:
|
||||
group["step"] = 0
|
||||
|
||||
def _initialize_native_cpu_adamw_state(self) -> None:
|
||||
alignment = 256 // torch.empty((), dtype=torch.float32).element_size()
|
||||
offsets = {}
|
||||
slab_numel = 0
|
||||
@@ -1490,22 +1018,15 @@ class FullCPUOffloadOptimizer(OffloadOptimizer):
|
||||
@torch.no_grad()
|
||||
def finish_checkpoint_load(self) -> None:
|
||||
if self._master_weights is not None:
|
||||
if self._native_cpu_optimizer:
|
||||
if not isinstance(self._gradient_manager, BoundedGradientOffloadManager):
|
||||
raise TypeError("Native CPU optimizers require bounded gradient offload")
|
||||
for i in range(len(self._chunks)):
|
||||
output_slots, compute_params = self._gradient_manager.acquire_output_chunk(i)
|
||||
for param, compute_param in zip(self._chunks[i], compute_params):
|
||||
compute_param.copy_(self._master_weights[id(param)].cpu_tensor)
|
||||
self._update_compute_weights(i, self._h2d_stream, compute_params)
|
||||
self._gradient_manager.release_output_chunk(output_slots, self._h2d_stream)
|
||||
else:
|
||||
for i in range(len(self._chunks)):
|
||||
self._update_compute_weights(i, self._h2d_stream)
|
||||
for i in range(len(self._chunks)):
|
||||
output_slots, compute_params = self._gradient_manager.acquire_output_chunk(i)
|
||||
for param, compute_param in zip(self._chunks[i], compute_params):
|
||||
compute_param.copy_(self._master_weights[id(param)].cpu_tensor)
|
||||
self._update_compute_weights(i, self._h2d_stream, compute_params)
|
||||
self._gradient_manager.release_output_chunk(output_slots, self._h2d_stream)
|
||||
torch.cuda.current_stream().wait_stream(self._h2d_stream)
|
||||
torch.cuda.synchronize()
|
||||
if isinstance(self._gradient_manager, BoundedGradientOffloadManager):
|
||||
self._gradient_manager.wait_for_output_slots()
|
||||
self._gradient_manager.wait_for_output_slots()
|
||||
self._initialized = True
|
||||
|
||||
@torch.no_grad()
|
||||
@@ -1570,7 +1091,6 @@ def _create_cpu_master_weights(
|
||||
model: nn.Module,
|
||||
named_params: list[tuple[str, nn.Parameter]],
|
||||
*,
|
||||
pin_memory: bool = True,
|
||||
dtype_policy: dict[int, tuple[torch.dtype, torch.dtype]] | None = None,
|
||||
) -> tuple[list[tuple[str, nn.Parameter]], dict[int, _MasterWeight]]:
|
||||
trainable_params = [(name, model_param) for name, model_param in named_params if model_param.requires_grad]
|
||||
@@ -1585,7 +1105,7 @@ def _create_cpu_master_weights(
|
||||
offsets[name] = slab_numel
|
||||
local_numel = model_param.to_local().numel()
|
||||
slab_numel += (local_numel + alignment - 1) // alignment * alignment
|
||||
master_slab = torch.empty(slab_numel, dtype=torch.float32, device="cpu", pin_memory=pin_memory)
|
||||
master_slab = torch.empty(slab_numel, dtype=torch.float32, device="cpu")
|
||||
master_named_params = []
|
||||
master_weights = {}
|
||||
for name, model_param in trainable_params:
|
||||
@@ -1611,6 +1131,6 @@ def _create_cpu_master_weights(
|
||||
master_allocation = sum(master.cpu_tensor.nbytes for master in master_weights.values())
|
||||
get_logger().info(
|
||||
f"CPU optimizer step allocated {master_allocation / 1024**3:.2f} GiB of "
|
||||
f"{'pinned' if pin_memory else 'pageable'} FP32 masters; persistent GPU parameters use configured compute dtypes"
|
||||
"pageable FP32 masters; persistent GPU parameters use configured compute dtypes"
|
||||
)
|
||||
return master_named_params, master_weights
|
||||
|
||||
@@ -75,10 +75,9 @@ class ParallelDims:
|
||||
assert ep % cp == 0 and (dp_shard * cp) % ep == 0
|
||||
|
||||
def build_mesh(self) -> DeviceMesh:
|
||||
if self.ep > 1:
|
||||
return self._build_mesh_with_ep()
|
||||
else:
|
||||
return self._build_mesh_without_ep()
|
||||
mesh = self._build_mesh_with_ep() if self.ep > 1 else self._build_mesh_without_ep()
|
||||
self._submeshes["head"] = self._submeshes["dp_shard_cp"]
|
||||
return mesh
|
||||
|
||||
def _build_mesh_with_ep(self) -> DeviceMesh:
|
||||
# With ep, dp_shard and ep are derived submeshes:
|
||||
@@ -96,12 +95,13 @@ class ParallelDims:
|
||||
dp_shard_mod_ep,
|
||||
dp_shard_in_ep,
|
||||
self.cp,
|
||||
1,
|
||||
],
|
||||
["pp", "dp_replicate", "dp_shard_mod_ep", "dp_shard_in_ep", "cp"],
|
||||
["pp", "dp_replicate", "dp_shard_mod_ep", "dp_shard_in_ep", "cp", "dp_shard_mod_head"],
|
||||
):
|
||||
# dp_shard_mod_ep is needed even if it's 1, whose FSDP wrapping
|
||||
# helps the MoE layers do mixed precision training
|
||||
if d > 1 or name == "dp_shard_mod_ep":
|
||||
if d > 1 or name in ("dp_shard_mod_ep", "dp_shard_mod_head"):
|
||||
dims.append(d)
|
||||
names.append(name)
|
||||
|
||||
@@ -158,10 +158,10 @@ class ParallelDims:
|
||||
dims = []
|
||||
names = []
|
||||
for d, name in zip(
|
||||
[self.pp, self.dp_replicate, self.dp_shard, self.cp],
|
||||
["pp", "dp_replicate", "dp_shard", "cp"],
|
||||
[self.pp, self.dp_replicate, self.dp_shard, self.cp, 1],
|
||||
["pp", "dp_replicate", "dp_shard", "cp", "dp_shard_mod_head"],
|
||||
):
|
||||
if d > 1 or name == "dp_shard":
|
||||
if d > 1 or name == "dp_shard" or (name == "dp_shard_mod_head" and self.dp_shard * self.cp > 1):
|
||||
dims.append(d)
|
||||
names.append(name)
|
||||
|
||||
|
||||
@@ -179,19 +179,27 @@ class PerfCounter:
|
||||
if hasattr(model_config, "text_config"):
|
||||
model_config = model_config.text_config
|
||||
|
||||
l, h, q, t = ( # noqa: E741
|
||||
l, h, t = ( # noqa: E741
|
||||
model_config.num_hidden_layers,
|
||||
model_config.num_attention_heads,
|
||||
model_config.hidden_size // model_config.num_attention_heads,
|
||||
seq_len,
|
||||
)
|
||||
# Reasoning behind the factor of 12 for the self-attention part of the formula:
|
||||
# Head dims as torchtitan's quadratic_attention_flops_per_token: the real head_dim (e.g. 128 for
|
||||
# Qwen3-235B, whose hidden_size / num_attention_heads is 64), or the MLA qk / v head dims.
|
||||
if hasattr(model_config, "qk_head_dim") and hasattr(model_config, "v_head_dim"):
|
||||
qk_head_dim, v_head_dim = model_config.qk_head_dim, model_config.v_head_dim
|
||||
else:
|
||||
qk_head_dim = v_head_dim = (
|
||||
getattr(model_config, "head_dim", None) or model_config.hidden_size // model_config.num_attention_heads
|
||||
)
|
||||
# Reasoning behind the factor of 6 for the self-attention part of the formula:
|
||||
# 1. each self-attention has 2 matmul in the forward and 4 in the backward (6)
|
||||
# (q @ K^T over qk_head_dim, then scores @ V over v_head_dim, per head and attended token)
|
||||
# 2. the flash attention does 1 more matmul recomputation in the backward
|
||||
# but recomputation should not be counted in calculating MFU (+0)
|
||||
# 3. each matmul performs 1 multiplication and 1 addition (*2)
|
||||
# 4. we follow the convention and do not account for sparsity in causal attention
|
||||
attention_flops = 12 * l * h * q * t
|
||||
attention_flops = 6 * l * h * (qk_head_dim + v_head_dim) * t
|
||||
|
||||
if has_lora_layers(self.model):
|
||||
# LoRA case:
|
||||
|
||||
@@ -582,7 +582,7 @@ def train(config: TrainerConfig):
|
||||
# Optionally, clip the gradients
|
||||
grad_norm: torch.Tensor | None = None
|
||||
if config.optim.max_norm is not None:
|
||||
grad_norm = clip_grad_norm_(gradient_manager, model, config.optim.max_norm, parallel_dims.ep_enabled)
|
||||
grad_norm = clip_grad_norm_(gradient_manager, model, config.optim.max_norm)
|
||||
|
||||
# Update the model parameters
|
||||
optimizer.step()
|
||||
|
||||
@@ -512,7 +512,7 @@ def train(config: SFTConfig):
|
||||
grad_norm: torch.Tensor | None = None
|
||||
if config.optim.max_norm is not None:
|
||||
logger.debug(f"Clipping gradients with max norm {config.optim.max_norm}")
|
||||
grad_norm = clip_grad_norm_(gradient_manager, model, config.optim.max_norm, parallel_dims.ep_enabled)
|
||||
grad_norm = clip_grad_norm_(gradient_manager, model, config.optim.max_norm)
|
||||
logger.debug("Optimizer step")
|
||||
optimizer.step()
|
||||
optimizer.zero_grad()
|
||||
@@ -556,15 +556,17 @@ def train(config: SFTConfig):
|
||||
progress.total_tokens += num_tokens
|
||||
dataset_progress = get_dataset_progress(dataloader)
|
||||
progress.total_samples = dataset_progress["step"]
|
||||
# Throughput / MFU per step over the full step wall time, as torchtitan reports them with
|
||||
# log_freq=1 (tokens since last log / elapsed time), instead of a smoothed sliding window.
|
||||
step_time = time.perf_counter() - step_start_time
|
||||
perf_counter = get_perf_counter(model, config.data.seq_len)
|
||||
perf_counter.count_tokens(num_tokens)
|
||||
throughput = perf_counter.get_tokens_per_second() or 0
|
||||
mfu = perf_counter.get_mfu() or 0
|
||||
throughput = perf_counter.get_step_tokens_per_second(num_tokens, step_time)
|
||||
mfu = perf_counter.get_step_mfu(num_tokens, step_time)
|
||||
peak_memory = torch.cuda.max_memory_reserved() / 1024**3 # GiB
|
||||
max_peak_memory = max(max_peak_memory, peak_memory)
|
||||
|
||||
# Log step metrics
|
||||
step_time = time.perf_counter() - step_start_time
|
||||
step_message = f"Step {progress.step} | {format_time(step_time):>7} | Loss {batch_loss:.4f}"
|
||||
if grad_norm is not None:
|
||||
step_message += f" | Grad. Norm {grad_norm:.4f}"
|
||||
|
||||
@@ -13,7 +13,7 @@ import torch.distributed as dist
|
||||
from rich import print as rich_print
|
||||
from rich.text import Text
|
||||
from torch import Tensor, nn
|
||||
from torchtitan.distributed.utils import clip_grad_norm_ as torch_clip_grad_norm_
|
||||
from torch.distributed.tensor import DTensor
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from prime_rl.trainer.world import get_world
|
||||
@@ -88,12 +88,24 @@ def clip_grad_norm_(
|
||||
manager: "GradientOffloadManager | None",
|
||||
model: nn.Module,
|
||||
max_norm: float,
|
||||
ep_enabled: bool,
|
||||
) -> Tensor:
|
||||
if manager is not None:
|
||||
grad_norm = manager.clip_grad_norm_(max_norm)
|
||||
else:
|
||||
grad_norm = torch_clip_grad_norm_(model.parameters(), max_norm=max_norm, ep_enabled=ep_enabled)
|
||||
# Norm reductions must complete on each parameter mesh before combining
|
||||
# dense, expert-parallel, and other model-parallel gradients.
|
||||
mesh_parameters = defaultdict(list)
|
||||
for param in model.parameters():
|
||||
if param.grad is not None:
|
||||
mesh = param.grad.device_mesh if isinstance(param.grad, DTensor) else None
|
||||
mesh_parameters[mesh].append(param)
|
||||
norms = []
|
||||
for parameters in mesh_parameters.values():
|
||||
norm = torch.nn.utils.get_total_norm([param.grad for param in parameters])
|
||||
norms.append(norm.full_tensor() if isinstance(norm, DTensor) else norm)
|
||||
grad_norm = torch.linalg.vector_norm(torch.stack(norms)) if norms else torch.tensor(0.0)
|
||||
for parameters in mesh_parameters.values():
|
||||
torch.nn.utils.clip_grads_with_norm_(parameters, max_norm, grad_norm)
|
||||
return grad_norm.cuda() if grad_norm.device.type == "cpu" else grad_norm
|
||||
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ from prime_rl.trainer.models import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.utils import get_world
|
||||
from prime_rl.transports.weights.base import WeightReceiver, WeightSender
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.nccl import disable_nccl_p2p_if_unavailable
|
||||
from prime_rl.utils.nccl import disable_nccl_p2p_if_unavailable, iter_tensor_buckets
|
||||
from prime_rl.utils.vlm import get_layer_prefix
|
||||
from prime_rl.utils.weights import resolve_wire_dtype
|
||||
|
||||
@@ -53,15 +53,13 @@ def broadcast_state_dict(state_dict: dict[str, Tensor], communicator: PyNcclComm
|
||||
communicator.broadcast(state_tensor, src=0)
|
||||
|
||||
# Concatenate and broadcast tensors grouped by dtype
|
||||
for dtype, items in dtype_groups.items():
|
||||
# Flatten all tensors and concatenate
|
||||
flat_tensors = [value.flatten() for _, value in items]
|
||||
concatenated = torch.cat(flat_tensors)
|
||||
communicator.broadcast(concatenated, src=0)
|
||||
del concatenated
|
||||
# Clean up individual tensors
|
||||
for _, value in items:
|
||||
del value
|
||||
for dtype, tensor_info in metadata.items():
|
||||
for bucket in iter_tensor_buckets(tensor_info, dtype):
|
||||
flat_tensors = [state_dict[key].flatten() for key, _, _ in bucket]
|
||||
concatenated = flat_tensors[0].contiguous() if len(flat_tensors) == 1 else torch.cat(flat_tensors)
|
||||
if concatenated.numel():
|
||||
communicator.broadcast(concatenated, src=0)
|
||||
del concatenated, flat_tensors
|
||||
|
||||
|
||||
def filter_state_dict_by_layers(
|
||||
|
||||
@@ -3,7 +3,6 @@ import logging
|
||||
import sys
|
||||
import traceback
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
# Global logger instance
|
||||
_LOGGER = None
|
||||
@@ -17,21 +16,6 @@ def build_log_entry(record) -> dict:
|
||||
"""Build a flat JSON log entry from a loguru record."""
|
||||
extra = record["extra"]
|
||||
|
||||
# Handle progress events specially - emit structured progress format
|
||||
if extra.get("_progress"):
|
||||
return {
|
||||
"timestamp": record["time"].isoformat(),
|
||||
"level": record["level"].name,
|
||||
"type": "progress",
|
||||
"desc": extra["desc"],
|
||||
"current": extra["current"],
|
||||
"total": extra["total"],
|
||||
"percent": extra["percent"],
|
||||
**({"step": extra["step"]} if extra.get("step") is not None else {}),
|
||||
**({"extra": extra["postfix"]} if extra.get("postfix") else {}),
|
||||
}
|
||||
|
||||
# Standard log entry
|
||||
log_entry = {
|
||||
"timestamp": record["time"].isoformat(),
|
||||
"level": record["level"].name,
|
||||
@@ -198,73 +182,6 @@ def reset_logger():
|
||||
_JSON_LOGGING = False
|
||||
|
||||
|
||||
class ProgressTracker:
|
||||
"""Progress tracker that uses tqdm or logs progress when JSON logging is enabled."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
total: int,
|
||||
desc: str,
|
||||
json_logging: bool | None = None,
|
||||
log_every_percent: int = 10,
|
||||
step: int | None = None,
|
||||
):
|
||||
self.total = total
|
||||
self.desc = desc
|
||||
self.step = step
|
||||
self.json_logging = json_logging if json_logging is not None else _JSON_LOGGING
|
||||
self.log_every_percent = log_every_percent
|
||||
self.current = 0
|
||||
self._last_logged_percent = -log_every_percent
|
||||
self._postfix: dict[str, Any] = {}
|
||||
|
||||
if self.json_logging:
|
||||
self._pbar = None
|
||||
# Don't log 0% on init - only log on actual progress
|
||||
else:
|
||||
from tqdm import tqdm
|
||||
|
||||
self._pbar = tqdm(total=total, desc=desc)
|
||||
|
||||
def update(self, n: int = 1):
|
||||
self.current += n
|
||||
if self._pbar is not None:
|
||||
self._pbar.update(n)
|
||||
else:
|
||||
self._log_progress()
|
||||
|
||||
def set_postfix(self, postfix: dict[str, Any]):
|
||||
self._postfix = postfix
|
||||
if self._pbar is not None:
|
||||
self._pbar.set_postfix(postfix)
|
||||
|
||||
def _log_progress(self):
|
||||
percent = int(100 * self.current / self.total) if self.total > 0 else 0
|
||||
if percent >= self._last_logged_percent + self.log_every_percent or self.current >= self.total:
|
||||
self._emit_progress(percent)
|
||||
self._last_logged_percent = percent
|
||||
|
||||
def _emit_progress(self, percent: int):
|
||||
"""Emit progress as structured JSON through loguru (only called in JSON logging mode)."""
|
||||
get_logger().bind(
|
||||
_progress=True,
|
||||
desc=self.desc,
|
||||
current=self.current,
|
||||
total=self.total,
|
||||
percent=percent,
|
||||
step=self.step,
|
||||
postfix=self._postfix if self._postfix else None,
|
||||
).info("progress")
|
||||
|
||||
def close(self):
|
||||
if self._pbar is not None:
|
||||
self._pbar.close()
|
||||
elif self.current > 0 and self.current < self.total:
|
||||
percent = int(100 * self.current / self.total)
|
||||
if percent > self._last_logged_percent:
|
||||
self._emit_progress(percent)
|
||||
|
||||
|
||||
def format_time(seconds: float) -> str:
|
||||
"""
|
||||
Format a time in seconds to a human-readable format:
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import os
|
||||
from collections.abc import Iterator
|
||||
|
||||
import pynvml
|
||||
import torch
|
||||
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
@@ -40,3 +42,24 @@ def disable_nccl_p2p_if_unavailable() -> None:
|
||||
)
|
||||
finally:
|
||||
pynvml.nvmlShutdown()
|
||||
|
||||
|
||||
def iter_tensor_buckets(
|
||||
tensor_info: list[tuple[str, torch.Size, int]],
|
||||
dtype: torch.dtype,
|
||||
max_bytes: int = 512 * 1024**2,
|
||||
) -> Iterator[list[tuple[str, torch.Size, int]]]:
|
||||
"""Group whole tensors without exceeding the budget, except for a single oversized tensor."""
|
||||
itemsize = dtype.itemsize
|
||||
bucket = []
|
||||
bucket_bytes = 0
|
||||
for info in tensor_info:
|
||||
size = info[2] * itemsize
|
||||
if bucket and bucket_bytes + size > max_bytes:
|
||||
yield bucket
|
||||
bucket = []
|
||||
bucket_bytes = 0
|
||||
bucket.append(info)
|
||||
bucket_bytes += size
|
||||
if bucket:
|
||||
yield bucket
|
||||
|
||||
@@ -28,6 +28,7 @@ VLM_REGISTRY: dict[str, VLMModelInfo] = {
|
||||
"qwen3_vl": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
|
||||
"qwen3_5": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
|
||||
"qwen3_5_moe": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
|
||||
"qwen4_exp": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
|
||||
"qwen3_vl_moe": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
|
||||
"gemma4": VLMModelInfo(vision_encoder_attr="model.vision_tower", language_model_attr="model.language_model"),
|
||||
}
|
||||
|
||||
@@ -356,24 +356,6 @@ def test_full_optimizer_offload_disables_gradient_clipping(config_cls):
|
||||
assert config.optim.max_norm is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("config_cls", [TrainerConfig, SFTConfig])
|
||||
def test_full_optimizer_offload_accepts_debug_backend(config_cls):
|
||||
config = config_cls.model_validate(
|
||||
{
|
||||
"model": {
|
||||
"optim_cpu_offload": False,
|
||||
"full_offload": {
|
||||
"cpu_optimizer_backend": "torch",
|
||||
},
|
||||
},
|
||||
"optim": {"max_norm": None},
|
||||
}
|
||||
)
|
||||
|
||||
assert config.model.full_offload is not None
|
||||
assert config.model.full_offload.cpu_optimizer_backend == "torch"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("config_cls", [TrainerConfig, SFTConfig])
|
||||
@pytest.mark.parametrize("optimizer_type", ["sgd", "muon"])
|
||||
def test_full_optimizer_offload_requires_supported_optimizer(config_cls, optimizer_type):
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import copy
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
@@ -98,12 +97,6 @@ def test_qkv_projections_match_the_unpacked_ones():
|
||||
assert torch.equal(fused_projection, unfused_projection)
|
||||
|
||||
|
||||
def test_unsupported_fusion_fails_loudly():
|
||||
with pytest.raises(ValueError, match="does not support"):
|
||||
apply_model_fusions(build_experts(), ["qkv"])
|
||||
assert apply_model_fusions(build_experts(), ["qkv"], raise_on_fail=False) == {}
|
||||
|
||||
|
||||
def test_non_gated_experts_have_nothing_to_pack():
|
||||
with pytest.raises(ValueError, match="does not support"):
|
||||
apply_model_fusions(build_experts(expert_type="non_gated"), ["gate_up"])
|
||||
def test_unsupported_fusions_are_skipped():
|
||||
assert apply_model_fusions(build_experts(), ["qkv"]) == {}
|
||||
assert apply_model_fusions(build_experts(expert_type="non_gated"), ["gate_up"]) == {}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from prime_rl.trainer.models.conversion_ops import apply_hf_to_prime, apply_prime_to_hf
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next import (
|
||||
Qwen3_8FlashNextConfig,
|
||||
Qwen3_8FlashNextForCausalLM,
|
||||
Qwen3_8FlashNextTextConfig,
|
||||
)
|
||||
from prime_rl.utils.vlm import get_language_model
|
||||
|
||||
|
||||
@pytest.fixture(params=[False, True], ids=["text", "composite"])
|
||||
def config(request):
|
||||
text = Qwen3_8FlashNextTextConfig(
|
||||
vocab_size=32,
|
||||
bos_token_id=31,
|
||||
eos_token_id=31,
|
||||
hidden_size=16,
|
||||
num_hidden_layers=1,
|
||||
layer_types=["linear_attention"],
|
||||
linear_num_key_heads=1,
|
||||
linear_num_value_heads=1,
|
||||
linear_key_head_dim=16,
|
||||
linear_value_head_dim=16,
|
||||
hc_count=2,
|
||||
hc_lowrank=4,
|
||||
num_experts=2,
|
||||
num_experts_per_tok=1,
|
||||
moe_intermediate_size=16,
|
||||
shared_expert_intermediate_size=16,
|
||||
ple_layer_ids=[1],
|
||||
ple_embed_dim=16,
|
||||
heads_per_ngram=2,
|
||||
ngram_vocab_size_base=17,
|
||||
make_ngram_vocab_size_divisible_by=8,
|
||||
split_ngram_parts=3,
|
||||
)
|
||||
return Qwen3_8FlashNextConfig(text_config=text) if request.param else text
|
||||
|
||||
|
||||
@pytest.mark.parametrize("shard_count", [3, 128])
|
||||
def test_config_and_checkpoint_roundtrip(config, shard_count):
|
||||
getattr(config, "text_config", config).split_ngram_parts = shard_count
|
||||
restored = type(config).from_dict(config.to_dict())
|
||||
model = Qwen3_8FlashNextForCausalLM(restored)
|
||||
model.init_buffers_post_meta()
|
||||
assert len(get_language_model(model).layers) == 1
|
||||
assert model.cp_support(restored).styles == frozenset({"ulysses"})
|
||||
original = {
|
||||
name: torch.randn_like(value) if value.is_floating_point() else value.clone()
|
||||
for name, value in model.state_dict().items()
|
||||
}
|
||||
converted = dict(original)
|
||||
operations = model.conversion_chain(restored)
|
||||
apply_prime_to_hf(converted, operations)
|
||||
assert model.is_hf_state_dict(converted)
|
||||
apply_hf_to_prime(converted, operations)
|
||||
assert converted.keys() == original.keys()
|
||||
for name, value in original.items():
|
||||
torch.testing.assert_close(converted[name], value, rtol=0, atol=0)
|
||||
@@ -7,7 +7,7 @@ from prime_rl.trainer.perf import PerfCounter
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"model_name, active_params, flops_per_token",
|
||||
[("Qwen/Qwen3-0.6B", 595_984_384, 3_928_227_840), ("Jackmin108/debug-moe-0.5B", 256_442_368, 1_689_649_152)],
|
||||
[("Qwen/Qwen3-0.6B", 595_984_384, 4_280_549_376), ("Jackmin108/debug-moe-0.5B", 256_442_368, 1_840_644_096)],
|
||||
)
|
||||
def test_perf_counter(model_name: str, active_params: int, flops_per_token: int):
|
||||
# This speeds up the model loading as its a fake device
|
||||
|
||||
@@ -4876,7 +4876,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "prime-kernels"
|
||||
version = "0.1.0+cu130torch2.13.0"
|
||||
source = { url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl" }
|
||||
source = { url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.0-6f48176/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl" }
|
||||
resolution-markers = [
|
||||
"platform_machine == 'aarch64' and sys_platform == 'linux'",
|
||||
]
|
||||
@@ -4884,7 +4884,7 @@ dependencies = [
|
||||
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" } },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl", hash = "sha256:3c13ff9079854e63b6464d839ab563ce44d04013834055b6b95efef0866c7212" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.0-6f48176/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl", hash = "sha256:cf54e247e161e22a91e654db32f34320cf26bfb7b4124ed6afd76d95d5eae034" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
@@ -4893,7 +4893,7 @@ requires-dist = [{ name = "torch", specifier = ">=2.9.0" }]
|
||||
[[package]]
|
||||
name = "prime-kernels"
|
||||
version = "0.1.0+cu130torch2.13.0"
|
||||
source = { url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_x86_64.whl" }
|
||||
source = { url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.0-6f48176/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_x86_64.whl" }
|
||||
resolution-markers = [
|
||||
"platform_machine == 'x86_64' and sys_platform == 'linux'",
|
||||
]
|
||||
@@ -4901,7 +4901,7 @@ dependencies = [
|
||||
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" } },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_x86_64.whl", hash = "sha256:29962d9ca4e699620588788ce797d485cd06be651026befdb66af275fe27ab39" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.0-6f48176/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_x86_64.whl", hash = "sha256:e2deffdc3b1b7c4e848e44171eaf4d742da602ad4cbaaf8a3cbe9f3811b0b7f2" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
@@ -5057,8 +5057,8 @@ gpu = [
|
||||
{ name = "vllm", version = "0.30.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
]
|
||||
kernels = [
|
||||
{ name = "prime-kernels", version = "0.1.0+cu130torch2.13.0", source = { url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "prime-kernels", version = "0.1.0+cu130torch2.13.0", source = { url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "prime-kernels", version = "0.1.0+cu130torch2.13.0", source = { url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.0-6f48176/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "prime-kernels", version = "0.1.0+cu130torch2.13.0", source = { url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.0-6f48176/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
]
|
||||
quack = [
|
||||
{ name = "quack-kernels", marker = "sys_platform == 'linux'" },
|
||||
@@ -5116,9 +5116,9 @@ requires-dist = [
|
||||
{ name = "orjson", specifier = ">=3.11.0" },
|
||||
{ name = "pandas", specifier = ">=2.0" },
|
||||
{ name = "prime", specifier = ">=0.8.0" },
|
||||
{ name = "prime-kernels", marker = "platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'kernels'", url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl" },
|
||||
{ name = "prime-kernels", marker = "platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'kernels'", url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.0-6f48176/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl" },
|
||||
{ name = "prime-kernels", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64' and sys_platform == 'linux' and extra == 'kernels'" },
|
||||
{ name = "prime-kernels", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'kernels'", url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_x86_64.whl" },
|
||||
{ name = "prime-kernels", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'kernels'", url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.0-6f48176/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_x86_64.whl" },
|
||||
{ name = "prime-pydantic-config", editable = "deps/pydantic-config" },
|
||||
{ name = "prime-rl", extras = ["disagg"], marker = "extra == 'all'" },
|
||||
{ name = "prime-rl", extras = ["flash-attn"], marker = "extra == 'all'" },
|
||||
|
||||
Reference in New Issue
Block a user