Compare commits
28
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9f4eef81a3 | ||
|
|
1d9ab255eb | ||
|
|
eff12f2483 | ||
|
|
e0886c152d | ||
|
|
9ef21a64f1 | ||
|
|
1e7c6888b6 | ||
|
|
815d1c0cad | ||
|
|
28bb83bea7 | ||
|
|
534888b77d | ||
|
|
43b4e2bd13 | ||
|
|
550beb6f43 | ||
|
|
bad80b1a30 | ||
|
|
aa3a6522b4 | ||
|
|
3f0c2e3b5a | ||
|
|
6b0d9e504b | ||
|
|
751a235af8 | ||
|
|
daa72a91d8 | ||
|
|
dad79d1ce8 | ||
|
|
dd2dd5461b | ||
|
|
cea63f9ef3 | ||
|
|
6a360c3029 | ||
|
|
04a61d3b75 | ||
|
|
26b3131d27 | ||
|
|
ef9dea1781 | ||
|
|
6c7b1ef375 | ||
|
|
608c75c0af | ||
|
|
b28714289a | ||
|
|
903baaaa01 |
@@ -5,6 +5,7 @@
|
||||
- **Minimal try/except**: let errors propagate — silent failures hide bugs. Only catch exceptions for intentional fault tolerance (retries, robustness).
|
||||
- **Don't touch `optimization_dtype` / `reduce_dtype`**: never change these model config fields (or their defaults in `trainer.py`) unless the user explicitly asks. They're load-bearing numerical knobs — flipping bfloat16/float32 silently changes training dynamics.
|
||||
- **Targeted comments**: don't explain your work process or reference old code. Use targeted comments sparingly to clarify ambiguous logic.
|
||||
- **Context parallelism**: a module that needs CP state holds a `CPContext` (`models/base.py`) as `self.cp_context`, defaulting to `CPContext()`, which is the non-CP case; `PreTrainedModelPrimeRL` supplies that default. `setup_context_parallel` in `utils/cp.py` builds one `CPContext` and assigns it to every module that has the field, so each module holds the same frozen object.
|
||||
- **Zen of Python**: remember the Zen of Python when writing code.
|
||||
```
|
||||
Beautiful is better than ugly.
|
||||
|
||||
+2
-2
@@ -96,7 +96,7 @@ ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
|
||||
# mount here: .git would bust the cache every commit.
|
||||
COPY --from=manifests /manifests /app
|
||||
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
|
||||
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
|
||||
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
|
||||
--no-install-workspace \
|
||||
--no-install-package prime-rl-configs \
|
||||
--no-install-package verifiers \
|
||||
@@ -132,7 +132,7 @@ RUN --mount=type=cache,target=/usr/local/share/uv/cache \
|
||||
&& \
|
||||
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" /app/deps/renderers/pyproject.toml \
|
||||
&& \
|
||||
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
|
||||
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
|
||||
&& \
|
||||
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]'
|
||||
|
||||
|
||||
@@ -59,7 +59,7 @@ With `[model] impl = "auto"` (the default), the trainer selects that custom stac
|
||||
| Nemotron H (`nemotron_h`) | `nvidia/Nemotron-3-Nano-30B-A3B`, `nvidia/Nemotron-3-Super-120B-A12B`, … | yes | ✅ | ✅ |
|
||||
| Trinity (`afmoe`) | `arcee-ai/Trinity-Mini`, … | yes | ✅ | ✅ |
|
||||
| GLM-4 · GLM-4.5 MoE · INTELLECT-3 (`glm4_moe`) | `THUDM/GLM-4-9B-0414`, `zai-org/GLM-4.5-Air`, `zai-org/GLM-4.5`, `PrimeIntellect/INTELLECT-3`, … | yes | ✅ | ✅ |
|
||||
| GPT-OSS (HF, MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | yes | ✅ | ✅ |
|
||||
| GPT-OSS (`gpt_oss`) | `unsloth/gpt-oss-20b-BF16`, … | yes | ✅ | ✅ |
|
||||
| Other HF causal LMs | Qwen3 dense, Mistral, … (`impl = "hf"`) | varies | ❌ | ✅ |
|
||||
|
||||
|
||||
@@ -204,10 +204,7 @@ These guides are designed to be run from a Slurm cluster but can also be adapted
|
||||
|
||||
1. [**Qwen3-30B-A3B**](examples/advanced/qwen3-30b-a3b/): Train `Qwen3-30B-A3B` on math, SWE, and agentic tool use.
|
||||
2. [**GLM-4.5-Air**](examples/advanced/glm-4.5-air/): Train `GLM-4.5-Air` on search, SWE, and terminal tasks.
|
||||
3. [**Nemotron-3-Super**](examples/advanced/nemotron-3-super/): Train the `Nemotron-3-Super-120B` hybrid-Mamba MoE on SWE at 131k context.
|
||||
4. [**MiniMax-M2.5 SWE**](examples/advanced/minimax-m2.5/): Train `MiniMax-M2.5` on agentic SWE tasks.
|
||||
5. [**INTELLECT-3.1**](examples/advanced/intellect-3.1/): Reproduce our `INTELLECT-3.1` training run.
|
||||
6. [**High-throughput GLM-5**](examples/advanced/glm-5.2/): Large-scale `GLM-5`/`GLM-5.2` inference with P/D disaggregation, the `llm-d` router, and FP8.
|
||||
3. [**GLM-5**](examples/advanced/glm-5.2/): Large-scale `GLM-5`/`GLM-5.2` training with P/D disaggregation, the `llm-d` router, and FP8.
|
||||
|
||||
## Docs
|
||||
|
||||
|
||||
@@ -6,6 +6,11 @@ Configurations for running prime-rl.
|
||||
environments, sized to run on a single dev machine. Each mirrors the matching
|
||||
[`examples/basic/`](../examples/basic) tutorial and is smoke-tested for one step.
|
||||
Envs: `reverse-text`, `alphabet-sort`, `wiki-search`, `wordle`, `hendrycks-sanity`.
|
||||
- **[`advanced/`](advanced)** — frontier-model training configs without launch walkthroughs:
|
||||
`minimax-m2.5` (swe), `nemotron-3-super` (swe), `deepseek-v4-flash` (sft + a standalone
|
||||
vLLM serving pre-flight). For the tutorialized equivalents, see
|
||||
[`examples/advanced/`](../examples/advanced).
|
||||
- **`evals/`** — standalone eval configs, run with `uv run evals @ configs/evals/swe.toml`.
|
||||
- **`ci/`** — integration and nightly configs used by CI.
|
||||
- **`debug/`** — throwaway configs for developing the framework itself: `algo/`
|
||||
(per-algorithm smokes), `fake/` (fake-data trainer/SFT smokes), and `multi-env/`
|
||||
|
||||
-2
@@ -22,8 +22,6 @@ num_infer_replicas = 4
|
||||
project = "nemotron-3-super"
|
||||
name = "nemotron-3-super-swe"
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
@@ -2,7 +2,7 @@
|
||||
# against DeepSeek V4 Flash on Prime Inference.
|
||||
#
|
||||
# export PRIME_API_KEY=<your Prime Inference key>
|
||||
# uv run evals @ examples/evals/swe.toml
|
||||
# uv run evals @ configs/evals/swe.toml
|
||||
#
|
||||
# The tasksets run in prime sandboxes (the default runtime), so the key also
|
||||
# authenticates sandbox creation. External API endpoints expose no vLLM
|
||||
Vendored
+1
-1
Submodule deps/verifiers updated: c1547418f6...392d596de8
+44
-1
@@ -6,6 +6,7 @@ This page covers the specialized features layered on top of the core training st
|
||||
|
||||
- [Custom Modeling](#custom-modeling)
|
||||
- [Expert Parallelism Backends](#expert-parallelism-backends)
|
||||
- [Runtime Fusions](#runtime-fusions)
|
||||
- [Multimodal Training](#multimodal-training)
|
||||
- [Supported Families](#supported-families)
|
||||
- [Enabling VLM Mode](#enabling-vlm-mode)
|
||||
@@ -33,10 +34,14 @@ impl = "custom" # or "hf" to force the HF path
|
||||
| Nemotron H | `nvidia/Nemotron-3-Nano-30B-A3B`, … | ✅ | ❌ |
|
||||
| Trinity (AFMoE) | `arcee-ai/Trinity-Mini`, … | ✅ | ✅ |
|
||||
| GLM-4 / GLM-4.5 / INTELLECT-3 | `THUDM/GLM-4-9B-0414`, `zai-org/GLM-4.5`, `PrimeIntellect/INTELLECT-3`, … | ✅ | ✅ |
|
||||
| GPT-OSS (HF MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | ❌ | ✅ |
|
||||
| GPT-OSS | `unsloth/gpt-oss-20b-BF16`, … | ✅ | ✅ |
|
||||
| DeepSeek V4 | `deepseek-ai/DeepSeek-V4-Flash-0731` | ✅ | ✅ |
|
||||
|
||||
Selective activation checkpointing works with either implementation. The custom path additionally enables EP, CP, low-precision training, and grouped MoE kernels. Forcing `impl = "hf"` is mostly useful when debugging and disables those model-specific runtime features.
|
||||
|
||||
GPT-OSS uses FlashAttention 4 with learned attention sinks. Training requires SM90 or SM100/SM110 GPUs
|
||||
and a BF16 checkpoint such as `unsloth/gpt-oss-20b-BF16`; the original MXFP4 checkpoints are not supported.
|
||||
|
||||
### Low-precision training
|
||||
|
||||
Dense linear precision and routed-expert precision are configured independently. `[trainer.model.quantization]` applies only to dense `Linear` modules:
|
||||
@@ -64,6 +69,26 @@ type = "torch"
|
||||
transport = "mxfp8"
|
||||
```
|
||||
|
||||
All MoE compute backends accept `apply_to`:
|
||||
|
||||
- `"all"` (default) applies the backend to all expert groups.
|
||||
- `"85%"` applies it to the first 85% of model layers, rounded down. For a 48-layer model, this selects layers 0–39.
|
||||
- `[0, 1, 2, 3]` selects explicit zero-based model layer indices; `[]` selects none.
|
||||
|
||||
Percentages must be between 0% and 100%; explicit indices must be within the model's layer count. Non-MoE blocks in hybrid models count toward layer indices and percentages. Each selected layer uses the backend for all its routed experts. Other expert groups use BF16 compute and BF16 token transport while retaining the configured dispatch backend and expert parallelism. Dense linear quantization is configured separately.
|
||||
|
||||
For example, this selects routed experts in Qwen3's first four model layers:
|
||||
|
||||
```toml
|
||||
[trainer.model.moe.compute]
|
||||
type = "mxfp8"
|
||||
apply_to = [0, 1, 2, 3]
|
||||
```
|
||||
|
||||
Backend shape checks and token alignment apply only to the selected compute path.
|
||||
|
||||
In RL runs, configure the same precision selection for rollouts. Inference module names can differ from the trainer's names, and inference precision is configured explicitly, not inferred from `apply_to`. Check the selected modules on both sides before comparing trainer and rollout logprobs.
|
||||
|
||||
GLM-5.2 adds IndexShare: the DSA sparse-attention indexer runs only on a subset of layers and the remaining layers reuse the cached top-k indices. The trainer reads this schedule from the model's `indexer_types` config field and enables the index cache automatically, so no extra config is needed. To override the schedule manually, set `[trainer.model.index_cache]` (`topk_freq` or `topk_pattern`).
|
||||
|
||||
### Expert Parallelism Backends
|
||||
@@ -82,6 +107,24 @@ token_chunk_size = 4096
|
||||
|
||||
With DeepEP, gradient clipping is currently not supported. (`optim.max_norm` is set to `None` automatically.)
|
||||
|
||||
### Runtime Fusions
|
||||
|
||||
`model.fusions` packs parameters that are always computed together into one tensor, turning several GEMMs into one. Both fusions are on by default:
|
||||
|
||||
- `gate_up` — each gated MoE expert's `gate_proj` and `up_proj` become one `[num_experts, 2 * intermediate_size, hidden_size]` weight, halving the routed-expert grouped GEMMs.
|
||||
- `qkv` — an attention layer's `q_proj`, `k_proj` and `v_proj` (and their biases) become one linear layer.
|
||||
|
||||
```toml
|
||||
[trainer.model.fusions]
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
The experimental `shard_fused_on_dim1 = true` shards fused 2-D weights along dim 1 under FSDP, which makes weight loading and checkpointing zero-copy: fused weights and their optimizer state are read and written in place rather than assembled into a full copy on each rank first. It requires `hidden_size` to be divisible by the FSDP shard mesh size.
|
||||
|
||||
## Multimodal Training
|
||||
|
||||
### Supported Families
|
||||
|
||||
+31
-1
@@ -184,7 +184,7 @@ $$
|
||||
\mathcal{L} = \frac{\sum \mathcal{L}_{rl}}{N_{rl}} + \frac{\sum \mathcal{L}_{ce}}{N_{ce}} + \frac{\sum \mathcal{L}_{ref\_kl}}{N_{ref\_kl}}
|
||||
$$
|
||||
|
||||
- `rl` — the configured RL loss (`[trainer.loss]`): IPO by default, or a [custom loss](#custom-loss). Fed by the advantage-assigning algorithms (`grpo`, `max_rl`, `rae`, `hierarchical_grpo`, and `echo`'s action tokens).
|
||||
- `rl` — the configured RL loss (`[trainer.loss]`): IPO by default, or optionally [IcePop](#icepop-loss) or a [custom loss](#custom-loss). Fed by the advantage-assigning algorithms (`grpo`, `max_rl`, `rae`, `hierarchical_grpo`, and `echo`'s action tokens).
|
||||
- `ce` — masked NLL. Used for frozen-model tokens (`sft`) and env-observation tokens (`echo`).
|
||||
- `ref_kl` — the per-token reverse KL to a reference model ($\log \pi_{\text{ref}} - \log \pi$) as the policy-gradient signal, importance-ratio corrected with a one-sided trust region (`opd`, `opsd`). Requires `ref_logprobs` from a [reference scoring](#reference-scoring); the scoring model must be a vLLM server (it's the only one that exposes `prompt_logprobs`).
|
||||
|
||||
@@ -215,6 +215,36 @@ The knobs under `[trainer.loss]` are:
|
||||
|
||||
Omit `[trainer.loss]` to use these defaults. Set `type = "ipo"` when you specify the section. The `ce` and `ref_kl` components are fixed and unaffected by `[trainer.loss]`.
|
||||
|
||||
### IcePop Loss
|
||||
|
||||
IcePop is an opt-in RL loss that drops tokens whose trainer-to-inference
|
||||
importance ratio falls outside a fixed acceptance band, introduced to stabilize
|
||||
MoE RL in [Every Step Evolves: Scaling Reinforcement Learning for Trillion-Scale
|
||||
Mixture-of-Experts Reasoning Models](https://arxiv.org/abs/2510.18855). Accepted
|
||||
tokens retain the importance-weighted policy-gradient term, and there is no
|
||||
separate KL penalty:
|
||||
|
||||
$$
|
||||
\mathcal{L}(\theta) = -\frac{1}{N}\sum_t
|
||||
\mathbb{1}\!\left(\alpha \le \frac{\pi(y_t)}{\mu(y_t)} \le \beta\right)
|
||||
\tau_A \hat{A}_t \frac{\pi(y_t)}{\mu(y_t)}.
|
||||
$$
|
||||
|
||||
Enable it explicitly:
|
||||
|
||||
```toml
|
||||
[trainer.loss]
|
||||
type = "icepop"
|
||||
ratio_low = 0.2
|
||||
ratio_high = 5.0
|
||||
```
|
||||
|
||||
| Knob | Default | What it does |
|
||||
|---|---|---|
|
||||
| `ratio_low` | 0.2 | Lower accepted trainer-to-inference probability ratio. |
|
||||
| `ratio_high` | 5.0 | Upper accepted trainer-to-inference probability ratio. |
|
||||
| `adv_tau` | 1.0 | Temperature on the advantage term. |
|
||||
|
||||
### Custom Loss
|
||||
|
||||
`[trainer.loss] type = "custom"` replaces the `rl` component. The loss is computed **per sequence**: you write a function that takes one sequence's tensors and returns a scalar loss. The trainer iterates and aggregates. `inputs.loss_mask` selects exactly the rl member tokens (for a plain GRPO run, all trainable tokens).
|
||||
|
||||
@@ -226,8 +226,8 @@ The shipped end-to-end examples in [`examples/`](https://github.com/PrimeIntelle
|
||||
|
||||
- [**Qwen3-30B-A3B**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/qwen3-30b-a3b) — `Qwen3-30B-A3B` on math, SWE, and tool use.
|
||||
- [**GLM-4.5-Air**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-4.5-air) — `GLM-4.5-Air` on search, SWE, and terminal.
|
||||
- [**Nemotron-3-Super**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/nemotron-3-super) — `Nemotron-3-Super-120B` hybrid-Mamba MoE on SWE at 131k context.
|
||||
- [**MiniMax-M2.5 SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/minimax-m2.5) — `MiniMax-M2.5` on agentic SWE.
|
||||
- [**Nemotron-3-Super**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/configs/advanced/nemotron-3-super) — `Nemotron-3-Super-120B` hybrid-Mamba MoE on SWE at 131k context.
|
||||
- [**MiniMax-M2.5 SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/configs/advanced/minimax-m2.5) — `MiniMax-M2.5` on agentic SWE.
|
||||
- [**INTELLECT-3.1**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/intellect-3.1) — reproduces our INTELLECT-3.1 training run.
|
||||
- [**High-throughput GLM-5**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2) — large-scale `GLM-5`/`GLM-5.2` inference with P/D disaggregation and FP8.
|
||||
|
||||
|
||||
+3
-3
@@ -141,12 +141,12 @@ In the PR that adds the new model, you also need to provide a table covering the
|
||||
|
||||
## Adding a Custom VLM Implementation
|
||||
|
||||
VLM training (any run with `[model.vlm]` set, SFT or RL) is custom-implementation-only: `get_model` rejects models without a custom PrimeRL VLM class at load time. To make a new VLM family trainable, extend a custom text model with a composite VLM body — the Qwen3.5 dense (`models/qwen3_5/`) and MoE (`models/qwen3_5_moe/`) implementations are the reference. The pieces, in dependency order:
|
||||
VLM training (any run with `[model.vlm]` set, SFT or RL) is custom-implementation-only: `get_model` rejects models without a custom PrimeRL VLM class at load time. To make a new VLM family trainable, extend a custom text model with a composite VLM body. The unified dense/MoE Qwen3.5 implementation in `models/qwen3_5/` is the reference. The pieces, in dependency order:
|
||||
|
||||
1. **Custom text model first.** The VLM body wraps a custom `*ForCausalLM` (see [Adding a New Model](#adding-a-new-model)), so the text side — including its state-dict conversion and KL-mismatch table — comes first.
|
||||
2. **Composite VLM body.** A `*VLMModel` that holds the HF vision encoder and the custom text model, with a `prepare_inputs_embeds_and_position_ids` step: embed tokens, run the vision encoder, scatter image embeddings over placeholder tokens, and build MRoPE 3D positions from `mm_token_type_ids` (the renderer owns the token→modality mapping). The unified `*ForCausalLM` dispatches on the config: composite config → VLM path, text config → text path.
|
||||
2. **Composite VLM body.** A `*VLMModel` that holds the vision encoder and custom text model, embeds tokens, runs vision, scatters image embeddings over placeholder tokens, and builds MRoPE 3D positions from `mm_token_type_ids` (the renderer owns the token→modality mapping). The unified `*ForCausalLM` dispatches on the config: composite config → VLM path, text config → text path.
|
||||
3. **Always run the vision encoder.** Text-only micro-batches must feed the encoder dummy pixels and graft the result into the graph with zero contribution (`inputs_embeds + image_embeds.sum() * 0.0`) so FSDP/EP collectives stay symmetric across ranks when the encoder is trainable.
|
||||
4. **Packed-boundary consumption.** Samples pack into shared rows with per-document boundaries in `seq_lens`; every custom model's `forward()` declares the typed `seq_lens`/`seq_lens_are_pre_shard` parameters (the trainer passes them unconditionally) and must honor the boundaries — varlen flash `cu_seqlens`, linear-attention state resets per document, and a loud rejection on attention paths that can't (see the packed-batch guard in any modeling file). Set `supports_packed_multimodal_training` on the VLM model once packed rows are handled — RL fails loudly at startup for VLM models without it.
|
||||
5. **Registration.** Register the composite `model_type` in `_CUSTOM_VLM_MAPPING` (`models/__init__.py`) so `get_model` dispatches to the custom class, and describe the family in `VLM_REGISTRY` (`utils/vlm.py`).
|
||||
6. **Context parallelism (optional).** CP-capable VLMs implement `set_context_parallel_attributes` and shard embeds/positions inside the model after the vision merge; the trainers defer sharding to the model for MRoPE batches under ulysses.
|
||||
6. **Context parallelism (optional).** CP-capable VLMs hold a `CPContext` on all modules which need to be CP-aware and shard embeds/positions inside the model after the vision merge; the trainers defer sharding to the model for MRoPE batches under ulysses.
|
||||
7. **Validation.** Same bar as text models: the KL-mismatch table for the text path, plus an SFT run and an RL run on a real multimodal dataset (the `color-codeword` environment is the reference task).
|
||||
|
||||
+3
-3
@@ -110,9 +110,9 @@ For DeepEP, set `type = "deepep"` and tune `num_sms` plus optional `token_chunk_
|
||||
|
||||
### Context Parallelism
|
||||
|
||||
CP shards a single sequence across multiple GPUs along the token dimension — for long-context sequences. Prefer `ulysses`: it gets the most throughput and is the only style that works for hybrid linear-attention/Mamba models (Qwen3.5, NemotronH) and for VLMs. Each model class declares its supported styles in `cp_support`; an unsupported `cp_style`, or a model with no CP support at all (DeepSeek V4, GPT-OSS), is rejected at setup.
|
||||
CP shards a single sequence across multiple GPUs along the token dimension — for long-context sequences. Prefer `ulysses`: it gets the most throughput and is the only style that works for hybrid linear-attention/Mamba models (Qwen3.5, NemotronH) and for VLMs. Each model class declares its supported styles in `cp_support`; an unsupported `cp_style`, or a model with no CP support at all, is rejected at setup.
|
||||
|
||||
`ulysses` head-shards Q/K/V, so the CP degree must divide `num_attention_heads`. GQA models with fewer KV heads than the CP degree (e.g. NemotronH: 32 query heads, 2 KV heads) are supported via KV-head replication; the CP degree must then be a multiple of `num_key_value_heads`. Hybrid Mamba layers head-shard independently (`cp_mamba`), which requires the CP degree to divide `mamba_num_heads` and `n_groups`.
|
||||
`ulysses` head-shards Q/K/V, so the CP degree must divide `num_attention_heads`. GQA models with fewer KV heads than the CP degree (e.g. NemotronH: 32 query heads, 2 KV heads) are supported via KV-head replication; the CP degree must then be a multiple of `num_key_value_heads`. Nemotron-H redistributes its Mamba activations between sequence- and head-parallel layouts in the model-owned Mamba path; the CP degree must divide `mamba_num_heads` and `n_groups`.
|
||||
|
||||
```toml
|
||||
[trainer.model]
|
||||
@@ -232,7 +232,7 @@ gpus_per_node = 8
|
||||
|
||||
Full multi-node configs ship under [`examples/advanced/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced):
|
||||
|
||||
- [`nemotron-3-super/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/nemotron-3-super/swe.toml) — 4 trainer + 1 inference node RL on a 120B hybrid-Mamba MoE with NCCL weight broadcast.
|
||||
- [`nemotron-3-super/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/configs/advanced/nemotron-3-super/swe.toml) — 4 trainer + 1 inference node RL on a 120B hybrid-Mamba MoE with NCCL weight broadcast.
|
||||
- [`glm-5.2/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2) — large-scale and P/D-disaggregated inference across the GLM-5 family.
|
||||
|
||||
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), fronted by a single global router on node 0. Point clients at the router URL the launcher prints.
|
||||
|
||||
+3
-3
@@ -354,7 +354,7 @@ tail -F <run_dir>/logs/latest/inference/router.log # multi-node only
|
||||
|
||||
### Dashboard
|
||||
|
||||
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with five views per run: metrics (the W&B overview sections, read from the file monitor's `metrics.jsonl`), the resolved configs, a rollout trace viewer with per-token overlays (advantage, entropy, trainer/sampling mismatch, IPO stable mask, loss and content masks), merged component logs, and markdown reports from `<run>/reports/`. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node.
|
||||
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with five views per run: metrics (the W&B overview sections, read from the file monitor's `metrics.jsonl`), the resolved configs, a rollout trace viewer with per-token overlays (advantage, entropy, trainer/sampling mismatch, IPO stable mask, loss and content masks), merged component logs, and markdown reports from `<run>/reports/`. The trace viewer separates the transcript, the wall-clock timeline of physical prefix branches, a wall-clock terminal replay of model and tool activity, and a top-to-bottom semantic graph of labeled model-call relationships. Replay uses recorded model-call and message timestamps; because providers do not persist per-token timestamps, it reveals response text evenly across the measured call span and labels that cadence as inferred. Agent and context labels in the semantic graph show the latest and peak prompt lengths first, with cumulative token processing available below on hover and click. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node.
|
||||
|
||||
A coding agent on the same machine can drive the open dashboard: `POST /api/view` with an on-disk address (`{"run", "tab", "step", "kind", "subset", "episode", "highlight": [...]}`) navigates every connected tab there and paints quote-anchored highlights in the trace viewer. Reports cite traces with `[^id]` markers whose JSON definitions carry the same address plus a verbatim quote; the dashboard re-checks each quote against the trace files and marks the citation verified or broken, so answers stay grounded in what is actually on disk. The `dashboard` skill documents the full contract.
|
||||
|
||||
@@ -387,9 +387,9 @@ Or set it in TOML:
|
||||
name = "my-experiment"
|
||||
```
|
||||
|
||||
Every 10th step the orchestrator uploads the step's episodes (full conversations with rewards and advantages) to the run's sample viewer.
|
||||
The monitor is a thin layer over the [`prime-runs`](https://github.com/PrimeIntellect-ai/prime/tree/main/packages/prime-runs) SDK (installed as `prime-runs[train]`): it registers the run, streams per-step metrics, uploads every 10th step's episodes (full conversations with rewards and advantages) to the run's sample viewer, and closes the run out. A process that exits without finishing is reported as crashed. Uploaded episodes are keyed to the platform run by the SDK; the orchestrator's own run id (the launcher's `PRL_RUN_ID`) stays on W&B and in the local records.
|
||||
|
||||
Requires `PRIME_API_KEY` (set via `prime login` or env var) and an allowlisted team. Currently internal-only.
|
||||
Requires `PRIME_API_KEY` (`prime login` or the env var) and a team (`PRIME_TEAM_ID`, or the team selected with `prime login`) enabled for external runs. A configured monitor must work: a missing key or a team outside the allowlist fails the launch. `PRIME_RUNS_MODE=disabled` keeps the monitor configured but opens no platform run; `RUN_ID=<id>` attaches to an external run a launcher already created instead of registering a new one. Currently internal-only.
|
||||
|
||||
## Rules of Thumb
|
||||
|
||||
|
||||
+34
-12
@@ -2,16 +2,38 @@
|
||||
|
||||
End-to-end usage examples for prime-rl, referenced from the top-level [README](../README.md).
|
||||
|
||||
- **[`basic/`](basic)** — walk-throughs for the core environments on 1–8 GPUs (baseline eval →
|
||||
optional SFT warmup → RL → eval), each with its own README:
|
||||
- `reverse-text` — smallest end-to-end loop (single-turn, 0.6B)
|
||||
- `alphabet-sort` — multi-turn, user simulator, LoRA
|
||||
- `wiki-search` — multi-turn tool calling, LoRA
|
||||
- `wordle` — multi-turn (~6-turn games)
|
||||
- `hendrycks-sanity` — single-turn math, long-running
|
||||
- **[`advanced/`](advanced)** — larger, mostly multi-node runs on frontier models, one folder
|
||||
per model: `qwen3-30b-a3b` (math/swe/tool), `glm-4.5-air` (search/swe/terminal), `glm-5.2`
|
||||
(large-scale + PD-disaggregated inference), `minimax-m2.5` (swe), `nemotron-3-super` (swe),
|
||||
`intellect-3.1` (swe), `deepseek-v4-flash` (sft + a standalone vLLM serving pre-flight).
|
||||
New here? Follow [`basic/reverse-text/`](basic/reverse-text/README.md) first — it trains a small model end-to-end on 2 GPUs and introduces the launch → dashboard → checkpoint flow the advanced examples reuse.
|
||||
|
||||
Dev-sized (2-GPU) counterparts of `basic/` live in [`configs/basic/`](../configs/basic).
|
||||
## advanced/ — frontier models, multi-node
|
||||
|
||||
Larger runs on frontier models, one folder per model, each with a launch README covering requirements, credentials, launch, monitoring, and resume:
|
||||
|
||||
- [`qwen3-30b-a3b/`](advanced/qwen3-30b-a3b/README.md) — `Qwen3-30B-A3B` RL on math (`i3_math`), SWE (`r2e-gym`), and agentic tool use (general-agent on Modal). 2 train + 2 infer nodes; the SWE config runs at 131k context with `ep = 8` + `cp = 2`.
|
||||
- [`glm-4.5-air/`](advanced/glm-4.5-air/README.md) — `GLM-4.5-Air` (100B MoE) RL across search, SWE, and terminal domains at 131k context, with agents in sandboxes. 2 train + 4 infer nodes (SWE: 1 + 3).
|
||||
- [`glm-5.2/`](advanced/glm-5.2/README.md) — the GLM-5 family at scale: 16 trainer nodes, P/D-disaggregated FP8 inference, and an llm-d router + Mooncake KV-offload variant. Also ships standalone `infer/` pre-flights.
|
||||
- `intellect-3.1/` — reproduce the `INTELLECT-3.1` run: 4 train + 12 infer nodes on SWE.
|
||||
|
||||
All advanced configs submit through SLURM (the `rl` entrypoint writes the sbatch job when the config has a `[slurm]` table) and are monitored with `uv run dashboard`. See the per-model README for the full walkthrough.
|
||||
|
||||
## basic/ — 1 to 8 GPUs
|
||||
|
||||
Walk-throughs for the core environments (baseline eval → optional SFT warmup → RL → eval), each with its own README:
|
||||
|
||||
- [`reverse-text/`](basic/reverse-text/README.md) — smallest end-to-end loop (single-turn, 0.6B)
|
||||
- [`alphabet-sort/`](basic/alphabet-sort/README.md) — multi-turn, user simulator, LoRA
|
||||
- [`wiki-search/`](basic/wiki-search/README.md) — multi-turn tool calling, LoRA
|
||||
- [`wordle/`](basic/wordle/README.md) — multi-turn (~6-turn games)
|
||||
- [`hendrycks-sanity/`](basic/hendrycks-sanity/README.md) — single-turn math, long-running
|
||||
|
||||
## extra/ — beyond the core loop
|
||||
|
||||
Examples that don't follow the basic eval → SFT → RL walk-through pattern:
|
||||
|
||||
- [`dynamo/`](extra/dynamo/README.md) — five-step Qwen3 math training with external Dynamo inference and NCCL weight updates
|
||||
- [`vlm/`](extra/vlm/README.md) — multimodal (VLM) SFT, dense + MoE LoRA configs
|
||||
|
||||
## Related config folders
|
||||
|
||||
- Frontier-model configs without launch walkthroughs (`minimax-m2.5`, `nemotron-3-super`, `deepseek-v4-flash`) live in [`configs/advanced/`](../configs/advanced).
|
||||
- Standalone eval configs live in [`configs/evals/`](../configs/evals).
|
||||
- Dev-sized (2-GPU) counterparts of `basic/` live in [`configs/basic/`](../configs/basic).
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
# GLM-4.5-Air
|
||||
|
||||
RL on [`zai-org/GLM-4.5-Air`](https://huggingface.co/zai-org/GLM-4.5-Air) — a 100B MoE — at 131k context, across three agentic domains: web search, SWE, and terminal. Rollouts run in sandboxes ([Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default — see [Requirements](#requirements) for using your own), driven either by the `rlm` agent harness (with its `search` skill, or ipython-only) or a plain `bash` harness. All three configs share the same recipe: GRPO with a linear length penalty on input tokens (and turns, for SWE/terminal), the custom MoE trainer implementation with `cp = 4` (ulysses) context parallelism, router replay, NCCL weight broadcast, checkpoints every 50 steps (`keep_last = 1`), and evals every 20 steps (including step 0).
|
||||
|
||||
| Config | Trains on | Evals on | Topology |
|
||||
|---|---|---|---|
|
||||
| [`search.toml`](search.toml) | `openseeker` + `redsearcher` (search QA, `rlm` harness + `search` skill) | `browsecomp` (500 examples) | 2 train + 4 infer nodes |
|
||||
| [`swe.toml`](swe.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 1 train + 3 infer nodes |
|
||||
| [`terminal.toml`](terminal.toml) | `tmax` (per-task Docker image, `rlm` ipython harness) | `swebench-verified` + `terminal-bench-2` (avg@4) | 2 train + 4 infer nodes |
|
||||
|
||||
Inference serves the bf16 checkpoint as-is (no quantization), with `tensor_parallel_size = 8`. `search.toml` and `terminal.toml` train with Muon on 2 nodes; `swe.toml` fits the trainer on a single node with full optimizer offload and the stateless sign-SGD optimizer. Search answers are scored by a reference judge (`Qwen/Qwen3-235B-A22B-Instruct-2507`).
|
||||
|
||||
## Requirements
|
||||
|
||||
- A Slurm cluster with 8-GPU nodes and a shared filesystem. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path.
|
||||
- **Sandboxes.** Rollout and eval agents run in sandboxes. These configs are wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default — if you use those, log the `prime` CLI in (it ships with prime-rl's dependencies), and each config's `slurm.pre_run_command` will clean up the run's orphaned sandboxes by label before launching:
|
||||
|
||||
```bash
|
||||
uv run prime login # or: uv run prime config set-api-key <your-key>
|
||||
```
|
||||
|
||||
To run on your own infrastructure instead, swap `env.agent.runtime` on each source for a runtime your environments support (e.g. a local Docker backend) and drop the `slurm.pre_run_command` cleanup line.
|
||||
|
||||
- Environment variables, exported in the shell you launch from — the launcher passes its environment to every component:
|
||||
|
||||
- `HF_TOKEN` — `zai-org/GLM-4.5-Air` is a gated model.
|
||||
- `WANDB_API_KEY` — every config logs to W&B (`[monitors.wandb]`).
|
||||
- `SERPER_API_KEY` — search envs only; forwarded into the agent sandbox for the `search` skill (`harness.forward_env`).
|
||||
|
||||
## Setup
|
||||
|
||||
Clone prime-rl onto the shared filesystem and install everything, including the environments — they are opt-in uv workspace members, so `--all-packages` is required:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
|
||||
uv sync --all-extras --all-packages
|
||||
```
|
||||
|
||||
## Tweak before launching
|
||||
|
||||
- `[slurm] partition` is set to `all` — override with `--slurm.partition <your-partition>`, or edit the config.
|
||||
- `--output-dir` defaults to `outputs/` next to the checkout; on a cluster, point it at the shared filesystem.
|
||||
- Validate the full config without submitting a job by appending `--dry-run`: it writes `<run_dir>/launcher/rl.sbatch` plus the resolved per-process configs, and exits.
|
||||
|
||||
## Start the run
|
||||
|
||||
The `rl` entrypoint submits an sbatch job whenever the config has a `[slurm]` table — there is no separate launcher. From the shared checkout:
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/advanced/glm-4.5-air/swe.toml \
|
||||
--output-dir /shared/outputs/glm45air \
|
||||
--run.name glm45air-swe
|
||||
```
|
||||
|
||||
Swap `swe.toml` for `search.toml` or `terminal.toml` to run the other domains. Pass `--run.name`: the run directory is `<output_dir>/<run_name>` and you need a stable name to resume later (unset, it auto-generates as `<envs>--<model>--<short-id>`).
|
||||
|
||||
## Monitor with the dashboard
|
||||
|
||||
Start the local run dashboard on the head node — it only reads the run directories, so it is safe to point at a live run while the job is training:
|
||||
|
||||
```bash
|
||||
uv run dashboard /shared/outputs/glm45air # serves http://localhost:7788
|
||||
```
|
||||
|
||||
If the head node is remote, forward the port from your laptop and open `http://localhost:7788` in a browser:
|
||||
|
||||
```bash
|
||||
ssh -L 7788:localhost:7788 <head-node>
|
||||
```
|
||||
|
||||
Pick the run (`<run_name>` from the launch) and you get five views:
|
||||
|
||||
- **Metrics** — the W&B-style overview, read from the run's `metrics.jsonl`. Watch `reward/{all,env}/mean` trend upward over steps, and `seq_len/*` + `is_truncated/*` for rollout health.
|
||||
- **Configs** — the launch TOML next to the merged, resolved per-process configs the run actually started with.
|
||||
- **Trace** — a per-episode rollout viewer with per-token overlays (advantage, entropy, sampling mismatch, loss/content masks), showing the transcript, a wall-clock timeline of the rollout, a terminal replay of model and tool activity, and a semantic graph of the model-call chain.
|
||||
- **Logs** — the merged component logs (trainer, orchestrator, inference), also on disk under `<run_dir>/logs/`.
|
||||
- **Reports** — markdown reports written to `<run_dir>/reports/`, if any tooling produces them.
|
||||
|
||||
Pass several output directories to track parallel experiments side by side (`uv run dashboard /shared/outputs/a /shared/outputs/b`); a taken port automatically bumps to the next free one. SLURM stdout/stderr and the generated sbatch script land in `<run_dir>/launcher/`.
|
||||
|
||||
## Checkpoint, resume, export
|
||||
|
||||
Checkpoints land in `<run_dir>/checkpoints/step_<N>` every 50 steps (`keep_last = 1`). To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, the same `--run.name` / `--output-dir`, and a `--max-steps` at least the target final step:
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/advanced/glm-4.5-air/swe.toml \
|
||||
--output-dir /shared/outputs/glm45air \
|
||||
--run.name glm45air-swe \
|
||||
--resume --max-steps 1000
|
||||
```
|
||||
|
||||
Trainer checkpoints are DCP-sharded; export HF-format weights with:
|
||||
|
||||
```bash
|
||||
uv run python tools/convert_dcp_to_bf16.py /shared/outputs/glm45air/glm45air-swe/checkpoints/step_100
|
||||
```
|
||||
|
||||
See [Training](../../../docs/training.md) for the full knobs and metrics reference, and [Scaling](../../../docs/scaling.md) for SLURM and multi-node details.
|
||||
@@ -25,8 +25,6 @@ num_infer_replicas = 4
|
||||
project = "search-ablations"
|
||||
name = "glm45air-search"
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe` SWE taskset, bash harness on a prime sandbox
|
||||
# runtime; eval on SWE-Bench Verified. Router replay is enabled (trainer.enable_router_replay replays
|
||||
# the routed-expert decisions returned by inference via enable_return_routed_experts) — GLM-4.5-Air is
|
||||
# a glm4_moe model, which supports routed_experts.
|
||||
# runtime; eval on SWE-Bench Verified. Follows the research-prod air ablation base config
|
||||
# (research-prod PR #198): 2 trainer nodes with the Muon optimizer (instead of the single-node
|
||||
# sign-SGD setup), 4 one-node inference replicas serving the bf16 checkpoint with TP=8 + expert
|
||||
# parallelism, batch size 256 / group size 16, and the linear length penalty with the input-token
|
||||
# and turns coefficients set to 0.1. Router replay stays enabled (trainer.enable_router_replay replays the routed-expert
|
||||
# decisions returned by inference via enable_return_routed_experts) — GLM-4.5-Air is a glm4_moe
|
||||
# model, which supports routed_experts. Optimizer state is checkpointed so runs can resume.
|
||||
#
|
||||
# GRPO uses the linear length penalty with the input-token and turns coefficients set to 0.1. Each
|
||||
# term is pass_rate-scaled and normalized by the group's own max before the GRPO baseline
|
||||
# subtraction.
|
||||
# GRPO uses the linear length penalty. Each term is pass_rate-scaled and normalized by the
|
||||
# group's own max before the GRPO baseline subtraction.
|
||||
#
|
||||
# 1 train + 3 infer nodes. Inference serves the bf16 checkpoint as-is (no quantization). The trainer
|
||||
# fits on one node via cp=4 (ulysses), full CPU optimizer offload with the stateless sign-SGD optimizer, plus
|
||||
# the memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
|
||||
# chunking, activation checkpointing (freq=1) + activation offloading (max_inflight=1), and
|
||||
# skip-gather / skip-optimizer checkpointing.
|
||||
# Two trainer nodes fit GLM-4.5-Air with Muon plus the memory improvements from the GLM-5.1 prod
|
||||
# run (research-prod rlm5/prod.toml): activation checkpointing (freq=1) + activation offloading
|
||||
# (max_inflight=1). LM-head token chunking (8192) and optimizer CPU offload run at their defaults.
|
||||
# Concurrency is fully default: the controller derives its start from the measured KV budget and
|
||||
# adapts from there.
|
||||
|
||||
@@ -31,16 +32,14 @@ pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-swe" -y ||
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 1
|
||||
num_train_nodes = 2
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 3
|
||||
num_infer_replicas = 4
|
||||
|
||||
[monitors.wandb]
|
||||
project = "swe-ablations"
|
||||
name = "glm45air-scaleswe"
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
@@ -65,9 +64,6 @@ impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
cp = 4
|
||||
cp_style = "ulysses"
|
||||
optim_cpu_offload = false
|
||||
full_offload = true
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
|
||||
[trainer.model.ac]
|
||||
|
||||
@@ -76,11 +72,8 @@ max_inflight_activations = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
type = "sign_sgd"
|
||||
type = "muon"
|
||||
|
||||
# --- Orchestrator ---
|
||||
|
||||
@@ -130,6 +123,8 @@ VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.vllm]
|
||||
gpu_memory_utilization = 0.85
|
||||
max_model_len = 131072
|
||||
tensor_parallel_size = 8
|
||||
enable_expert_parallel = true
|
||||
enable_return_routed_experts = true
|
||||
|
||||
@@ -26,8 +26,6 @@ num_infer_replicas = 4
|
||||
project = "terminal-ablations"
|
||||
name = "glm45air-terminal"
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
# GLM-5 family at scale
|
||||
|
||||
Large-scale RL and serving for the GLM-5 family — `zai-org/GLM-5`, `GLM-5.1`, and `GLM-5.2-FP8` — at 131k context: 16 trainer nodes on the custom MoE implementation (expert parallelism; the llm-d variant adds context parallelism) and P/D-disaggregated FP8 inference. The `-llmd` variants front the inference plane with the [**llm-d**](https://llm-d.ai) router (Endpoint Picker + Envoy): its `active-request-scorer` load-balances in flight — instead of reacting to delayed metrics like the default `vllm-router` — which, combined with prefix-cache affinity for grouped rollouts, keeps prefill and decode ranks evenly loaded under RL's bursty request pattern. They also offload KV to a Mooncake distributed CPU pool (1TB per node by default).
|
||||
|
||||
| Config | What it runs | Topology |
|
||||
|---|---|---|
|
||||
| [`swe.toml`](swe.toml) | GLM-5 RL plane: 16 train nodes, eval on `swebench-verified` every 20 steps, default vLLM router over 2 P/D replicas (4 prefill + 4 decode nodes each). Declares **no train source** — compose yours on top with an `[[orchestrator.train.source]]` overlay. | 16 train + 16 infer nodes |
|
||||
| [`swe-llmd.toml`](swe-llmd.toml) | Full-stack GLM-5.1 RL: trains on `r2e-gym` (`rlm` harness), FP8-quantized trainer (`deepgemm_fp8` MoE compute), llm-d router + Mooncake KV offload. | 16 train + 16 infer nodes |
|
||||
| [`infer/pd.toml`](infer/pd.toml) | Inference-only pre-flight: P/D-disaggregated `GLM-5-FP8`. | 6 infer nodes |
|
||||
| [`infer/pd-llmd.toml`](infer/pd-llmd.toml) | Inference-only pre-flight: `GLM-5.2-FP8` with llm-d + Mooncake. | 16 infer nodes |
|
||||
|
||||
## Requirements
|
||||
|
||||
- A Slurm cluster with 8-GPU nodes, a shared filesystem, and at least **32 nodes** (16 trainer + 16 inference) for the RL configs. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path. If you have fewer nodes, drop `seq_len`, lower `num_train_nodes`, and reduce `cp` (llm-d variant) accordingly.
|
||||
- InfiniBand/RDMA NICs for the Mooncake KV pool (llm-d variants).
|
||||
- **Sandboxes.** Rollout and eval agents run in sandboxes, wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. If you use those, log the `prime` CLI in — it ships with prime-rl's dependencies:
|
||||
|
||||
```bash
|
||||
uv run prime login # or: uv run prime config set-api-key <your-key>
|
||||
```
|
||||
|
||||
To run on your own infrastructure instead, swap `env.agent.runtime` on each source for a runtime your environments support (e.g. a local Docker backend).
|
||||
|
||||
- Environment variables, exported in the shell you launch from — the launcher passes its environment to every component:
|
||||
|
||||
- `HF_TOKEN` — the GLM-5 family checkpoints are gated models.
|
||||
- `WANDB_API_KEY` — both RL configs log to W&B (`[monitors.wandb]`).
|
||||
|
||||
### Install llm-d (llmd variants only)
|
||||
|
||||
The llm-d router ships as vendored binaries (`epp`, `envoy`, `pd-sidecar`). Build them once into `third_party/llmd/bin`:
|
||||
|
||||
```bash
|
||||
bash scripts/install_llmd.sh
|
||||
```
|
||||
|
||||
## Setup
|
||||
|
||||
Clone prime-rl onto the shared filesystem and install everything, including the environments — they are opt-in uv workspace members, so `--all-packages` is required:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
|
||||
uv sync --all-extras --all-packages
|
||||
```
|
||||
|
||||
## Tweak before launching
|
||||
|
||||
- `swe-llmd.toml` marks two `# FILL IN` values: `output_dir` (point it at your shared filesystem) and `[slurm] partition`. `swe.toml` needs `--slurm.partition <your-partition>` or `--output-dir` overrides on the command line.
|
||||
- `[inference.kv_cache_offload] device_name` — the RDMA NIC list for Mooncake. Auto-detection is unreliable; set it by hand from `nvidia-smi topo -m` on your nodes.
|
||||
- `[inference.kv_cache_offload.cpu] num_bytes` — 1TB per node by default; lower it if your nodes have less RAM.
|
||||
- `swe-llmd.toml` ships without `[ckpt]` — add a checkpoint overlay if you want resume support.
|
||||
|
||||
## Start the run
|
||||
|
||||
The `rl` entrypoint submits an sbatch job whenever the config has a `[slurm]` table — there is no separate launcher. From the shared checkout:
|
||||
|
||||
```bash
|
||||
# GLM-5.1 RL with llm-d + Mooncake (recommended)
|
||||
uv run rl @ examples/advanced/glm-5.2/swe-llmd.toml
|
||||
|
||||
# GLM-5 base plane — compose your train source onto it
|
||||
uv run rl @ examples/advanced/glm-5.2/swe.toml @ my-train-source.toml
|
||||
```
|
||||
|
||||
The inference configs are standalone pre-flights: they serve the FP8 checkpoint through the same entrypoint the trainer uses (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster` included — never call `vllm serve` directly), and are a fast way to check that this cluster can serve the model at all before committing it to a run:
|
||||
|
||||
```bash
|
||||
uv run inference @ examples/advanced/glm-5.2/infer/pd.toml
|
||||
uv run inference @ examples/advanced/glm-5.2/infer/pd-llmd.toml
|
||||
```
|
||||
|
||||
## Monitor with the dashboard
|
||||
|
||||
Start the local run dashboard on the head node — it only reads the run directories, so it is safe to point at a live run while the job is training:
|
||||
|
||||
```bash
|
||||
uv run dashboard /shared/outputs # serves http://localhost:7788
|
||||
```
|
||||
|
||||
If the head node is remote, forward the port from your laptop and open `http://localhost:7788` in a browser:
|
||||
|
||||
```bash
|
||||
ssh -L 7788:localhost:7788 <head-node>
|
||||
```
|
||||
|
||||
Pick the run and you get five views:
|
||||
|
||||
- **Metrics** — the W&B-style overview, read from the run's `metrics.jsonl`. Watch `reward/{all,env}/mean` trend upward over steps, and `seq_len/*` + `is_truncated/*` for rollout health.
|
||||
- **Configs** — the launch TOML next to the merged, resolved per-process configs the run actually started with.
|
||||
- **Trace** — a per-episode rollout viewer with per-token overlays (advantage, entropy, sampling mismatch, loss/content masks), showing the transcript, a wall-clock timeline, a terminal replay of model and tool activity, and a semantic graph of the model-call chain.
|
||||
- **Logs** — the merged component logs (trainer, orchestrator, inference), also on disk under `<run_dir>/logs/`.
|
||||
- **Reports** — markdown reports written to `<run_dir>/reports/`, if any tooling produces them.
|
||||
|
||||
Pass several output directories to track parallel experiments side by side (`uv run dashboard /shared/outputs/a /shared/outputs/b`); a taken port automatically bumps to the next free one. SLURM stdout/stderr and the generated sbatch script land in `<run_dir>/launcher/`.
|
||||
|
||||
## Checkpoint and resume
|
||||
|
||||
`swe.toml` checkpoints every 100 steps (`[ckpt] interval = 100`). To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, a stable `--run.name`, and a `--max-steps` at least the target final step. Trainer checkpoints are DCP-sharded; export HF-format weights with `tools/convert_dcp_to_bf16.py`. See [Training](../../../docs/training.md) for the full resume and export reference.
|
||||
|
||||
See [Scaling](../../../docs/scaling.md) for SLURM details and [Inference](../../../docs/inference.md) for the disaggregated-inference and router reference.
|
||||
@@ -0,0 +1,106 @@
|
||||
# Qwen3-30B-A3B
|
||||
|
||||
RL on the 30B-A3B MoE across three domains: math, SWE, and agentic tool use. The Thinking checkpoint trains math and SWE; the tool config trains the Instruct checkpoint with colocated tools on [Modal](https://modal.com). All configs use the custom MoE trainer implementation with expert parallelism (`ep = 8`), the AdamW optimizer, NCCL weight broadcast, and W&B logging. `swe.toml` adds `cp = 2` context parallelism for its 131k context; the other two run at 32k.
|
||||
|
||||
| Config | Trains on | Evals on | Runtime | Topology |
|
||||
|---|---|---|---|---|
|
||||
| [`math.toml`](math.toml) | `i3_math` | `aime2025` (every 25 steps) | `subprocess` — runs locally, no sandbox | 2 train + 2 infer nodes |
|
||||
| [`swe.toml`](swe.toml) | `r2e-gym` (`bash` harness) | `swebench-verified` (every 25 steps) | sandbox (Prime Intellect by default) | 2 train + 2 infer nodes |
|
||||
| [`tool.toml`](tool.toml) | `general-agent` (colocated tools) | — | `modal` | 1 train + 1 infer node |
|
||||
|
||||
`tool.toml` is the odd one out: 400 steps, `group_size = 16`, checkpoints every 50 steps with `keep_last = 1`, and inference at `dp = 2` / `tp = 4`. `math.toml` and `swe.toml` run 512-task batches with checkpoints every 100 steps.
|
||||
|
||||
## Requirements
|
||||
|
||||
- A Slurm cluster with 8-GPU nodes and a shared filesystem. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path.
|
||||
- **Sandboxes** (`swe.toml` only) — the SWE agents run in sandboxes, wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. If you use those, log the `prime` CLI in (it ships with prime-rl's dependencies):
|
||||
|
||||
```bash
|
||||
uv run prime login # or: uv run prime config set-api-key <your-key>
|
||||
```
|
||||
|
||||
To run on your own infrastructure instead, swap `env.agent.runtime` on the source for a runtime your environments support (e.g. a local Docker backend).
|
||||
- **Modal** (`tool.toml` only) — the tool agents run on Modal (`env.agent.runtime.type = "modal"`). Authenticate once:
|
||||
|
||||
```bash
|
||||
uv run modal setup # or export MODAL_TOKEN_ID / MODAL_TOKEN_SECRET
|
||||
```
|
||||
|
||||
- Environment variables, exported in the shell you launch from — the launcher passes its environment to every component:
|
||||
|
||||
- `WANDB_API_KEY` — every config logs to W&B (`[monitors.wandb]`).
|
||||
- `HF_TOKEN` — optional; the Qwen checkpoints are public, but a token avoids rate limits.
|
||||
|
||||
`math.toml` needs none of the above beyond W&B: its agents run as local subprocesses on the env server.
|
||||
|
||||
## Setup
|
||||
|
||||
Clone prime-rl onto the shared filesystem and install everything, including the environments — they are opt-in uv workspace members, so `--all-packages` is required:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
|
||||
uv sync --all-extras --all-packages
|
||||
```
|
||||
|
||||
## Tweak before launching
|
||||
|
||||
- None of the configs set a `[slurm] partition` — sbatch picks your cluster default. Override with `--slurm.partition <your-partition>`.
|
||||
- `--output-dir` defaults to `outputs/` next to the checkout; on a cluster, point it at the shared filesystem.
|
||||
- Validate the full config without submitting a job by appending `--dry-run`: it writes `<run_dir>/launcher/rl.sbatch` plus the resolved per-process configs, and exits.
|
||||
|
||||
## Start the run
|
||||
|
||||
The `rl` entrypoint submits an sbatch job whenever the config has a `[slurm]` table — there is no separate launcher. From the shared checkout:
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/advanced/qwen3-30b-a3b/math.toml \
|
||||
--output-dir /shared/outputs/qwen30b \
|
||||
--run.name qwen30b-math
|
||||
```
|
||||
|
||||
Swap `math.toml` for `swe.toml` or `tool.toml` to run the other domains. Pass `--run.name`: the run directory is `<output_dir>/<run_name>` and you need a stable name to resume later (unset, it auto-generates as `<envs>--<model>--<short-id>`).
|
||||
|
||||
## Monitor with the dashboard
|
||||
|
||||
Start the local run dashboard on the head node — it only reads the run directories, so it is safe to point at a live run while the job is training:
|
||||
|
||||
```bash
|
||||
uv run dashboard /shared/outputs/qwen30b # serves http://localhost:7788
|
||||
```
|
||||
|
||||
If the head node is remote, forward the port from your laptop and open `http://localhost:7788` in a browser:
|
||||
|
||||
```bash
|
||||
ssh -L 7788:localhost:7788 <head-node>
|
||||
```
|
||||
|
||||
Pick the run and you get five views:
|
||||
|
||||
- **Metrics** — the W&B-style overview, read from the run's `metrics.jsonl`. Watch `reward/{all,env}/mean` trend upward over steps, and `seq_len/*` + `is_truncated/*` for rollout health.
|
||||
- **Configs** — the launch TOML next to the merged, resolved per-process configs the run actually started with.
|
||||
- **Trace** — a per-episode rollout viewer with per-token overlays (advantage, entropy, sampling mismatch, loss/content masks), showing the transcript, a wall-clock timeline of the rollout, a terminal replay of model and tool activity, and a semantic graph of the model-call chain.
|
||||
- **Logs** — the merged component logs (trainer, orchestrator, inference), also on disk under `<run_dir>/logs/`.
|
||||
- **Reports** — markdown reports written to `<run_dir>/reports/`, if any tooling produces them.
|
||||
|
||||
Pass several output directories to track parallel experiments side by side (`uv run dashboard /shared/outputs/a /shared/outputs/b`); a taken port automatically bumps to the next free one. SLURM stdout/stderr and the generated sbatch script land in `<run_dir>/launcher/`.
|
||||
|
||||
## Checkpoint, resume, export
|
||||
|
||||
Checkpoints land in `<run_dir>/checkpoints/step_<N>` — every 100 steps for `math.toml`/`swe.toml`, every 50 steps (`keep_last = 1`) for `tool.toml`. To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, the same `--run.name` / `--output-dir`, and a `--max-steps` at least the target final step:
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/advanced/qwen3-30b-a3b/math.toml \
|
||||
--output-dir /shared/outputs/qwen30b \
|
||||
--run.name qwen30b-math \
|
||||
--resume --max-steps 1000
|
||||
```
|
||||
|
||||
Trainer checkpoints are DCP-sharded; export HF-format weights with:
|
||||
|
||||
```bash
|
||||
uv run python tools/convert_dcp_to_bf16.py /shared/outputs/qwen30b/qwen30b-math/checkpoints/step_100
|
||||
```
|
||||
|
||||
See [Training](../../../docs/training.md) for the full knobs and metrics reference, and [Scaling](../../../docs/scaling.md) for SLURM and multi-node details.
|
||||
@@ -0,0 +1,73 @@
|
||||
# Dynamo RL
|
||||
|
||||
This example runs five steps of GRPO training on the Hendrycks math environment with `Qwen/Qwen3-0.6B`, one trainer GPU, one external Dynamo inference worker, and NCCL weight transfer.
|
||||
|
||||
Prime-RL does not launch Dynamo from this configuration. Run the frontend, worker, and trainer as separate processes. This example requires two GPUs: GPU 0 for Prime-RL training and GPU 1 for Dynamo inference.
|
||||
|
||||
## Start Dynamo
|
||||
|
||||
Install Dynamo with its vLLM backend and activate its environment. Then start the RL-enabled frontend in the first terminal:
|
||||
|
||||
```bash
|
||||
DYN_HTTP_HOST=127.0.0.1 DYN_ENABLE_RL=true DYN_RL_PORT=8001 python -m dynamo.frontend
|
||||
```
|
||||
|
||||
Start the RL-enabled vLLM worker on GPU 1 in a second terminal:
|
||||
|
||||
```bash
|
||||
CUDA_VISIBLE_DEVICES=1 DYN_SYSTEM_HOST=127.0.0.1 DYN_SYSTEM_PORT=8081 python -m dynamo.vllm \
|
||||
--model Qwen/Qwen3-0.6B \
|
||||
--enable-rl
|
||||
```
|
||||
|
||||
The `--enable-rl` flag enables worker discovery and the administration routes used for NCCL weight updates. Keep GPU 0 out of `CUDA_VISIBLE_DEVICES` for this process so it remains available to the Prime-RL trainer.
|
||||
|
||||
These commands bind the HTTP, discovery, and worker administration endpoints to loopback. If Prime-RL and Dynamo run on different hosts, expose these endpoints only on a trusted control network; configured client headers are also sent to the discovery endpoint.
|
||||
|
||||
## Endpoint contract
|
||||
|
||||
The default configuration expects:
|
||||
|
||||
- The Dynamo OpenAI-compatible frontend at `http://127.0.0.1:8000/v1`.
|
||||
- The Dynamo RL discovery endpoint at `http://127.0.0.1:8001/v1/rl/workers`.
|
||||
- Exactly one discovered worker for `Qwen/Qwen3-0.6B` with an admin URL and `world_size = 1`.
|
||||
- A vLLM worker with the Prime-RL NCCL weight-update extension enabled.
|
||||
|
||||
Verify both endpoints before starting training:
|
||||
|
||||
```bash
|
||||
curl --fail http://127.0.0.1:8000/v1/models
|
||||
curl --fail http://127.0.0.1:8001/v1/rl/workers
|
||||
```
|
||||
|
||||
## Discovery URL
|
||||
|
||||
The example enables Dynamo with:
|
||||
|
||||
```toml
|
||||
[orchestrator.model.client]
|
||||
base_url = "http://127.0.0.1:8000/v1"
|
||||
|
||||
[orchestrator.model.client.dynamo]
|
||||
enabled = true
|
||||
```
|
||||
|
||||
When `discovery_url` is omitted, Prime-RL removes the path from `base_url` and increments its explicit non-default port by one. Here, `http://127.0.0.1:8000/v1` becomes `http://127.0.0.1:8001`.
|
||||
|
||||
If your Dynamo frontend and discovery service do not use adjacent ports, configure the discovery endpoint explicitly:
|
||||
|
||||
```toml
|
||||
[orchestrator.model.client.dynamo]
|
||||
enabled = true
|
||||
discovery_url = "http://dynamo.example:9000"
|
||||
```
|
||||
|
||||
## Run training
|
||||
|
||||
After both endpoint checks pass, run Prime-RL from the repository in a third terminal. With no managed `[inference]` section, Prime-RL assigns GPU 0 to its single trainer process and leaves the external Dynamo worker on GPU 1:
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/extra/dynamo/rl.toml
|
||||
```
|
||||
|
||||
The example stops after five optimizer steps. Outputs are written under `outputs/` unless `output_dir` is overridden.
|
||||
@@ -0,0 +1,40 @@
|
||||
max_steps = 5
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-0.6B"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 1
|
||||
num_infer_gpus = 1
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 32
|
||||
group_size = 8
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
[[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.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[orchestrator.model.client]
|
||||
base_url = "http://127.0.0.1:8000/v1"
|
||||
|
||||
[orchestrator.model.client.dynamo]
|
||||
enabled = true
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
enable_thinking = false
|
||||
@@ -0,0 +1,22 @@
|
||||
# VLM SFT
|
||||
|
||||
Multimodal (VLM) supervised fine-tuning configs, dense and MoE. VLM training requires a custom PrimeRL implementation (`impl = "custom"`, `[model.vlm]` set — see [Advanced § Multimodal Training](../../../docs/advanced.md#multimodal-training)); these configs use the Qwen3.5 dense and Qwen3.6 MoE VLM implementations. Both LoRA-finetune with a frozen vision encoder and assistant-only loss masking.
|
||||
|
||||
| Config | Model | Hardware |
|
||||
|---|---|---|
|
||||
| [`sft.toml`](sft.toml) | `Qwen/Qwen3.5-0.8B` (dense, LoRA rank 16) | tiny — sanity-scale (20 steps) |
|
||||
| [`sft-moe.toml`](sft-moe.toml) | `Qwen/Qwen3.6-35B-A3B` (MoE, LoRA rank 32, `ep = 8`) | one 8-GPU node (`num_train_gpus = 8`) |
|
||||
|
||||
## Run it
|
||||
|
||||
Point `data.name` at your multimodal chat dataset (HF dataset with a `messages` column — see [Training § Dataset Format](../../../docs/training.md#dataset-format)), then:
|
||||
|
||||
```bash
|
||||
uv run sft @ examples/extra/vlm/sft.toml
|
||||
```
|
||||
|
||||
Notes:
|
||||
|
||||
- The MoE config declares `[deployment]` with `num_train_gpus = 8`; keep its `ep` in sync with the GPU count.
|
||||
- `micro_batch_size = 1` is required for VLM SFT — do not raise it.
|
||||
- Checkpoints land in `<run_dir>/checkpoints/step_<N>`; export HF-format weights with `tools/convert_dcp_to_bf16.py` (see [Training](../../../docs/training.md)).
|
||||
@@ -34,10 +34,7 @@ micro_batch_size = 1 # required for VLM SFT
|
||||
seq_len = 16384
|
||||
|
||||
[data.loss_mask]
|
||||
system = false
|
||||
user = false
|
||||
assistant = true
|
||||
tool = false
|
||||
assistant = true # only assistant turns contribute to the loss; system/user/tool default to false
|
||||
|
||||
[optim]
|
||||
lr = 1e-5
|
||||
@@ -29,5 +29,8 @@ batch_size = 1
|
||||
micro_batch_size = 1
|
||||
seq_len = 16384
|
||||
|
||||
[data.loss_mask]
|
||||
assistant = true # only assistant turns contribute to the loss; system/user/tool default to false
|
||||
|
||||
[optim]
|
||||
lr = 1e-5
|
||||
@@ -1,7 +1,8 @@
|
||||
"""Algorithm abstraction: sampling and the per-token training signal.
|
||||
|
||||
An algorithm is a named, self-contained config — a discriminated union keyed
|
||||
on ``type`` (``grpo``, ``max_rl``, ``opd``, ``opsd``, ``sft``, ``echo``).
|
||||
on ``type`` (``grpo``, ``max_rl``, ``rae``, ``hierarchical_grpo``, ``opd``,
|
||||
``opsd``, ``sft``, ``echo``, ``debug``).
|
||||
The bundle *is* the algorithm: each variant carries
|
||||
its sampling component and its credit-assignment / loss-routing parameters,
|
||||
and its class defaults are the vetted setting — ``type = "opd"`` with a
|
||||
@@ -364,6 +365,32 @@ class SFTAlgoConfig(BaseAlgoConfig):
|
||||
return self
|
||||
|
||||
|
||||
class DebugAlgoConfig(BaseAlgoConfig):
|
||||
type: Literal["debug"] = "debug"
|
||||
"""Debugging algorithm for infra work: every sampled token of every clean
|
||||
trainable trace gets the same constant ``advantage`` (default 1.0),
|
||||
ignoring rewards entirely. Every admitted rollout is trainable and every
|
||||
action token carries gradient signal, so the full RL path (advantage
|
||||
transport, importance ratios, trust region, optimizer, weight update)
|
||||
can be exercised regardless of the reward function. Not a real training
|
||||
signal — a policy pushed by it drifts monotonically."""
|
||||
|
||||
action_loss_type: ClassVar[ActionLossType] = "rl"
|
||||
|
||||
advantage: float = Field(1.0, allow_inf_nan=False)
|
||||
"""The constant per-token advantage. Must be nonzero: a zero advantage
|
||||
makes nothing trainable, the exact failure this debug tool exists to
|
||||
rule out."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def require_nonzero_advantage(self):
|
||||
if self.advantage == 0.0:
|
||||
raise ValueError(
|
||||
"the 'debug' algorithm needs a nonzero advantage — a zero advantage leaves nothing trainable."
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
AlgoConfig: TypeAlias = Annotated[
|
||||
GRPOAlgoConfig
|
||||
| EchoAlgoConfig
|
||||
@@ -372,7 +399,8 @@ AlgoConfig: TypeAlias = Annotated[
|
||||
| HierarchicalGRPOAlgoConfig
|
||||
| OPDAlgoConfig
|
||||
| OPSDAlgoConfig
|
||||
| SFTAlgoConfig,
|
||||
| SFTAlgoConfig
|
||||
| DebugAlgoConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
"""The training algorithm: sampling plus the per-token training signal (credit
|
||||
@@ -387,6 +415,8 @@ its class defaults are the vetted setting.
|
||||
- ``opsd`` — SDFT: policy samples, demo-conditioned reverse KL against the live policy (the teacher is the policy itself).
|
||||
- ``sft`` — a frozen model samples, the policy trains with CE on its tokens. Needs a frozen ``sampling.source``.
|
||||
- ``echo`` — GRPO on action tokens + weighted CE on tool-response observation tokens.
|
||||
- ``debug`` — the same constant advantage on every sampled token, ignoring
|
||||
rewards. Debugging only: for infra work that needs every token trainable.
|
||||
|
||||
A new credit-assignment scheme is a new named algorithm in code (subclass
|
||||
``Algorithm``, register it), not a config that points at an import path.
|
||||
|
||||
@@ -162,6 +162,14 @@ class BaseModelConfig(BaseConfig):
|
||||
"""VLM configuration. Setting this enables vision-language model support."""
|
||||
|
||||
|
||||
class DynamoConfig(BaseConfig):
|
||||
enabled: bool = True
|
||||
"""Enable Dynamo worker discovery for the inference admin plane."""
|
||||
|
||||
discovery_url: str | None = Field(default=None, min_length=1, max_length=2048)
|
||||
"""Dynamo frontend URL used to discover inference workers for RL control."""
|
||||
|
||||
|
||||
class ClientConfig(BaseConfig):
|
||||
wait_for_ready_timeout: int = 1800
|
||||
"""Seconds to wait at startup for the inference pool to become ready."""
|
||||
@@ -184,6 +192,9 @@ class ClientConfig(BaseConfig):
|
||||
admin_base_url: list[str] | None = None
|
||||
"""Separate base URLs for admin operations (weight updates, health checks). When set, admin clients bypass routers and hit each server directly — used in multi-replica or disaggregated P/D deployments where the router must not handle admin traffic."""
|
||||
|
||||
dynamo: DynamoConfig | None = None
|
||||
"""Dynamo RL worker-discovery configuration."""
|
||||
|
||||
|
||||
class LogConfig(BaseConfig):
|
||||
level: str = Field(default_factory=lambda: os.environ.get("PRIME_LOG_LEVEL", "info"))
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import re
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
from pydantic import BeforeValidator, Field, model_validator
|
||||
from pydantic import BeforeValidator, Field, field_validator, model_validator
|
||||
|
||||
from prime_rl.configs.monitors import MonitorsConfig
|
||||
from prime_rl.configs.shared import (
|
||||
@@ -85,6 +86,17 @@ class CompileConfig(BaseConfig):
|
||||
"""Compile transformer blocks with ``fullgraph=True``."""
|
||||
|
||||
|
||||
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."""
|
||||
|
||||
|
||||
class IndexCacheConfig(BaseConfig):
|
||||
topk_freq: int = Field(1, ge=1)
|
||||
"""Recompute DSA top-k indices every N layers; intervening layers reuse the cached indices. ``1`` recomputes every layer (effectively no reuse). Mirrors vLLM's ``index_topk_freq`` HF override."""
|
||||
@@ -169,19 +181,46 @@ class MXFP8Config(BaseConfig):
|
||||
QuantizationConfig: TypeAlias = Annotated[FP8Config | MXFP8Config, Field(discriminator="type")]
|
||||
|
||||
|
||||
class BF16MoEComputeConfig(BaseConfig):
|
||||
class MoEComputeConfigBase(BaseConfig):
|
||||
apply_to: str | list[Annotated[int, Field(ge=0, strict=True)]] = "all"
|
||||
"""Model layers to use this backend for: ``"all"``, a percentage such as ``"85%"``,
|
||||
or zero-based layer indices such as ``[0, 1, 2]``. Percentages select the first fraction
|
||||
of model layers, rounded down. Other expert groups use BF16 compute and transport.
|
||||
"""
|
||||
|
||||
@field_validator("apply_to")
|
||||
@classmethod
|
||||
def validate_apply_to(cls, value: str | list[int]) -> str | list[int]:
|
||||
if isinstance(value, str) and value != "all":
|
||||
if re.fullmatch(r"\d+(?:\.\d+)?%", value) is None or float(value[:-1]) > 100:
|
||||
raise ValueError('apply_to must be "all", a percentage from "0%" to "100%", or a list of layer indices')
|
||||
return value
|
||||
|
||||
def resolve_layers(self, num_layers: int) -> set[int]:
|
||||
if isinstance(self.apply_to, list):
|
||||
invalid = [index for index in self.apply_to if index >= num_layers]
|
||||
if invalid:
|
||||
raise ValueError(
|
||||
f"apply_to layer indices {invalid} are out of range for a model with {num_layers} layers"
|
||||
)
|
||||
return set(self.apply_to)
|
||||
count = num_layers if self.apply_to == "all" else int(num_layers * float(self.apply_to[:-1]) / 100)
|
||||
return set(range(count))
|
||||
|
||||
|
||||
class BF16MoEComputeConfig(MoEComputeConfigBase):
|
||||
"""Run routed-expert grouped GEMMs in bfloat16."""
|
||||
|
||||
type: Literal["bf16"] = "bf16"
|
||||
|
||||
|
||||
class DeepGemmFP8MoEComputeConfig(BaseConfig):
|
||||
class DeepGemmFP8MoEComputeConfig(MoEComputeConfigBase):
|
||||
"""Run routed-expert grouped GEMMs with DeepGEMM FP8 kernels."""
|
||||
|
||||
type: Literal["deepgemm_fp8"] = "deepgemm_fp8"
|
||||
|
||||
|
||||
class MXFP8MoEComputeConfig(BaseConfig):
|
||||
class MXFP8MoEComputeConfig(MoEComputeConfigBase):
|
||||
"""Run routed-expert grouped GEMMs with Prime's vendored MXFP8 implementation."""
|
||||
|
||||
type: Literal["mxfp8"] = "mxfp8"
|
||||
@@ -240,6 +279,9 @@ class ModelConfig(BaseModelConfig):
|
||||
compile: CompileConfig | None = CompileConfig()
|
||||
"""Compile the model with ``torch.compile``."""
|
||||
|
||||
fusions: FusionsConfig = FusionsConfig()
|
||||
"""Runtime parameter fusions, on by default."""
|
||||
|
||||
ac: ActivationCheckpointConfig | None = ActivationCheckpointConfig()
|
||||
"""Activation checkpointing configuration. If None, activation checkpointing is disabled."""
|
||||
|
||||
@@ -536,6 +578,25 @@ class IPOLossConfig(BaseConfig):
|
||||
"""Temperature for the KL term."""
|
||||
|
||||
|
||||
class IcePopLossConfig(BaseConfig):
|
||||
type: Literal["icepop"] = "icepop"
|
||||
|
||||
ratio_low: float = Field(0.2, gt=0)
|
||||
"""Lower accepted trainer-to-inference probability ratio."""
|
||||
|
||||
ratio_high: float = Field(5.0, gt=0)
|
||||
"""Upper accepted trainer-to-inference probability ratio."""
|
||||
|
||||
adv_tau: float = Field(1.0, ge=0)
|
||||
"""Temperature for the advantage term."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_ratio_bounds(self):
|
||||
if self.ratio_low > self.ratio_high:
|
||||
raise ValueError("ratio_low must not exceed ratio_high")
|
||||
return self
|
||||
|
||||
|
||||
class CustomLossConfig(BaseConfig):
|
||||
type: Literal["custom"] = "custom"
|
||||
|
||||
@@ -546,7 +607,7 @@ class CustomLossConfig(BaseConfig):
|
||||
"""Kwargs forwarded to the loss function."""
|
||||
|
||||
|
||||
LossConfig: TypeAlias = Annotated[IPOLossConfig | CustomLossConfig, Field(discriminator="type")]
|
||||
LossConfig: TypeAlias = Annotated[IPOLossConfig | IcePopLossConfig | CustomLossConfig, Field(discriminator="type")]
|
||||
|
||||
|
||||
class FakeDataLoaderConfig(BaseConfig):
|
||||
@@ -699,16 +760,6 @@ class TrainerConfig(BaseConfig):
|
||||
self.optim.max_norm = None
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def vlms_require_bfloat16(self):
|
||||
if self.model.vlm is not None and (
|
||||
self.model.optimization_dtype != "bfloat16" or self.model.reduce_dtype != "bfloat16"
|
||||
):
|
||||
raise ValueError(
|
||||
"VLM models must use optimization_dtype='bfloat16' and reduce_dtype='bfloat16' to match vLLM inference."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def vlm_freeze_incompatible_with_lora(self):
|
||||
if self.model.vlm is not None and not self.model.vlm.freeze_vision_encoder and self.model.lora is not None:
|
||||
|
||||
+19
-5
@@ -17,6 +17,7 @@ dependencies = [
|
||||
"wandb>=0.26.1",
|
||||
"wandb-workspaces>=0.4.3",
|
||||
"prime>=0.6.19",
|
||||
"prime-runs[train]>=0.1.1",
|
||||
"pyzmq>=27.1.0",
|
||||
"aiolimiter>=1.2.1",
|
||||
"tenacity>=8.2.0",
|
||||
@@ -61,6 +62,7 @@ gpu = [
|
||||
"dion ; sys_platform == 'linux'",
|
||||
"tilelang>=0.1.8 ; sys_platform == 'linux'",
|
||||
"flash-linear-attention ; sys_platform == 'linux'",
|
||||
"mamba-ssm>=2.3.0 ; sys_platform == 'linux'",
|
||||
"nvidia-ml-py>=12.575.51 ; sys_platform == 'linux'",
|
||||
"torchao>=0.18.0 ; sys_platform == 'linux'",
|
||||
"modelexpress==0.3.0 ; sys_platform == 'linux'",
|
||||
@@ -70,6 +72,7 @@ dashboard = [
|
||||
"fastapi>=0.115",
|
||||
"uvicorn>=0.30",
|
||||
]
|
||||
dynamo = ["ai-dynamo==1.4.2 ; sys_platform == 'linux'"]
|
||||
# Both wheels are the same flash-attn 2.8.3 / cu130 / torch 2.13 / cp312 build and carry
|
||||
# sm_80 / sm_90 / sm_100 / sm_120 cubins. `attn="auto"` picks FA4 on sm_100 and FA3 on
|
||||
# sm_90, so FA2 is the resolved backend on sm_120 (see `_resolve_attn_impl` in
|
||||
@@ -90,9 +93,6 @@ disagg = [
|
||||
"nixl-cu13==0.10.1 ; sys_platform == 'linux'",
|
||||
"vllm-router ; sys_platform == 'linux'",
|
||||
]
|
||||
gpt-oss = [
|
||||
"kernels ; sys_platform == 'linux'",
|
||||
]
|
||||
quack = [
|
||||
"quack-kernels>=0.4.1 ; sys_platform == 'linux'",
|
||||
]
|
||||
@@ -140,6 +140,8 @@ environments = [
|
||||
# Override torch's pinned cuDNN to fix the Conv3d performance regression.
|
||||
# See: https://github.com/pytorch/pytorch/issues/166122
|
||||
override-dependencies = [
|
||||
# Keep vLLM's TileLang version; Nemotron uses Mamba-2's Triton kernels.
|
||||
"tilelang==0.1.12",
|
||||
# Shared by vLLM, TileLang, and the pinned FlashAttention 4 runtime.
|
||||
"apache-tvm-ffi==0.1.11",
|
||||
"nvidia-cudnn-cu13>=9.15 ; sys_platform == 'linux'",
|
||||
@@ -191,6 +193,15 @@ requires-dist = [
|
||||
"torch>=2.6.0",
|
||||
]
|
||||
|
||||
# Mirror the upstream Pydantic compatibility correction until the next release.
|
||||
[[tool.uv.dependency-metadata]]
|
||||
name = "ai-dynamo-runtime"
|
||||
version = "1.4.2"
|
||||
requires-dist = [
|
||||
"pydantic>=2.10.6,<=2.13.5",
|
||||
"uvloop>=0.21.0",
|
||||
]
|
||||
|
||||
# NIXL publishes its CUDA 12 package as a base dependency even when the
|
||||
# caller requests its CUDA 13 extra. Use the requested CUDA 13 package only.
|
||||
[[tool.uv.dependency-metadata]]
|
||||
@@ -222,6 +233,8 @@ flash_attn_3 = false
|
||||
# appear in `uv tree` need to be listed; the resolver ignores entries for
|
||||
# packages it never sees.
|
||||
prime = false
|
||||
prime-runs = false
|
||||
prime-traces = false
|
||||
prime-sandboxes = false
|
||||
prime-tunnel = false
|
||||
prime-evals = false
|
||||
@@ -252,7 +265,7 @@ torchao = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/torchao-0.18.0+git5f2baf9d5-cp310-abi3-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/torchao-0.18.0+git5f2baf9d5-cp310-abi3-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "99e5f7e" }
|
||||
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "0251105" }
|
||||
vllm-router = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
@@ -275,12 +288,13 @@ 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_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" }
|
||||
flash_attn_3 = { index = "pytorch-cu130-test" }
|
||||
|
||||
[tool.uv.extra-build-dependencies]
|
||||
flash-attn = [{ requirement = "torch", match-runtime = true }]
|
||||
flash-attn-3 = [{ requirement = "torch", match-runtime = true }]
|
||||
mamba-ssm = [{ requirement = "torch", match-runtime = true }]
|
||||
mamba-ssm = ["torch>=2.13.0"]
|
||||
|
||||
[tool.uv.extra-build-variables]
|
||||
flash-attn = { FLASH_ATTENTION_SKIP_CUDA_BUILD = "TRUE" }
|
||||
|
||||
@@ -73,7 +73,7 @@ The `sft` entrypoint takes the same eval shape at the top level for online evals
|
||||
|
||||
**Discriminated unions** — set the `type` field to pick the variant (`[orchestrator.algo] type = "max_rl"`). Omit `type` to keep the default variant.
|
||||
|
||||
**RL loss** — `[trainer.loss]` defaults to IPO with `eps = 0.1`, `adv_tau = 1.0`, and `kl_tau = 1e-3`. Omit the section to use these defaults. Set `type = "custom"` with `import_path` and optional `kwargs` to load a custom RL loss. The `ce` and `ref_kl` components are fixed.
|
||||
**RL loss** — `[trainer.loss]` defaults to IPO with `eps = 0.1`, `adv_tau = 1.0`, and `kl_tau = 1e-3`. Omit the section to use these defaults. Set `type = "icepop"` for ratio masking with `ratio_low = 0.2`, `ratio_high = 5.0`, and `adv_tau = 1.0`; IcePop has no separate KL term. Set `type = "custom"` with `import_path` and optional `kwargs` to load a custom RL loss. The `ce` and `ref_kl` components are fixed.
|
||||
|
||||
**Algorithms** — `[orchestrator.algo] type = "grpo" | "max_rl" | "rae" | "hierarchical_grpo" | "opd" | "opsd" | "sft" | "echo"` — the type names the algorithm (credit assignment + loss routing, fused), and each type's class defaults are its vetted setting; any other key you set is your own assembly (e.g. `[orchestrator.algo.roles.user] alpha = 0.1` for echo — setting any echo role replaces the whole role table). `hierarchical_grpo` is only valid with a proposer-solver env: it compares solvers with attempts on the same proposed problem and proposers with other proposals in the group. There is no preset layer, and no config hook that points at user code — a new algorithm is a named class in the repo (subclass `Algorithm`, register it). Per-source override: `[orchestrator.train.source.algo] type = "opd"` (the source assembles its own algorithm). prime-rl only hosts the trainable policy; frozen models are inline external endpoints on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for opd (the frozen model scored against), `[orchestrator.algo.sampling.source]` for sft (the model it samples from), each with `name` + `base_url`. There is no shared `teacher` slot. opsd declares no model — it self-distills against the live policy. See `docs/algorithms.md`.
|
||||
|
||||
|
||||
@@ -15,6 +15,42 @@ The Config and Logs views default to `latest (attempt <n>)`. Select an attempt
|
||||
to inspect the immutable config or log files from an earlier launch. The Config
|
||||
view shows a copyable launch command above the launch TOML or resolved JSON.
|
||||
|
||||
The trace viewer has separate **Transcript**, **Timeline**, **Replay**, and
|
||||
**Semantic** views. Timeline is a wall-clock Gantt of physical prefix branches.
|
||||
Replay renders the selected agent branch as a terminal session with play/pause,
|
||||
seek, restart, and speed controls. It preserves recorded model-call and
|
||||
tool-result delays. Since the trace schema records a complete model-call span
|
||||
but no per-token timestamps, response text is paced evenly across that measured
|
||||
span and labeled as inferred; events without timestamps remain ordered and are
|
||||
labeled untimed. Semantic projects Verifiers `MessageNode.semantic_parents` as a
|
||||
top-to-bottom causal graph of model calls, including subagent calls, returns,
|
||||
compactions, and custom edge types. Calls occupy compact causal ranks within
|
||||
bounded agent lanes: the root stays centered, concurrent children fan out
|
||||
symmetrically, and child slots are reused after return, so graph width reflects
|
||||
peak agent concurrency rather than total subagents. Compaction starts a visibly
|
||||
separate context segment. For display only, a missing continuation is recovered
|
||||
when the physical parent chain proves a completed tool round-trip; fragments
|
||||
that still cannot be placed are shown explicitly as unlinked instead of being
|
||||
presented as contexts. Hover or click an agent or context label to see its
|
||||
latest and peak prompt lengths first, followed by cumulative token processing
|
||||
and cost. Exact timing remains available on model-call hover and in Timeline.
|
||||
Traces without semantic parents keep the other views and disable Semantic.
|
||||
|
||||
Replay defaults to 8× so long coding-agent model waits remain watchable; select
|
||||
1× for exact wall time or up to 32× for faster review. In-flight calls display
|
||||
their measured progress and recorded output-token usage even when they produce
|
||||
only tool calls. Enable **Skip inference** to collapse model calls to immediate
|
||||
responses while preserving the recorded command-to-tool-output delays. This is
|
||||
distinct from the speed control, which scales every delay uniformly. Recorded
|
||||
model thinking is shown by default. Toggle **Thinking** in the replay controls
|
||||
or press **T** while Replay is open to hide or show it without changing playback
|
||||
timing. Do not advertise Ctrl+T: browsers reserve it for a new tab before the
|
||||
page can handle the keypress. Use **Top** or the **Home** key to scroll to the
|
||||
beginning without pausing the replay. Use **Live** or **End** to resume
|
||||
following newly rendered output. Prompt-context nodes that were committed at
|
||||
response time are placed at the linked call's start so their serialization
|
||||
timestamp does not create a false blank wait before the replay.
|
||||
|
||||
Every dashboard instance serves the dirs it was started with **plus** every dir
|
||||
in the per-user registry (`~/.cache/prime-rl/dashboard/dirs.json`, re-read
|
||||
live). Launchers (`rl`, `sft`) register their output dir on every
|
||||
|
||||
@@ -59,10 +59,10 @@ See the `kernels` skill.
|
||||
### NemotronH (Mamba SSD kernels)
|
||||
|
||||
```bash
|
||||
CUDA_HOME=/usr/local/cuda uv pip install mamba-ssm
|
||||
uv sync --extra gpu
|
||||
```
|
||||
|
||||
Requires `nvcc`. Without `mamba-ssm`, NemotronH falls back to HF's pure-PyTorch SSD path, which computes softplus in bf16 and yields ~0.4 KL divergence vs vLLM. Do **not** install `causal-conv1d` unless your GPU arch matches the prebuilt kernels — the code falls back to `nn.Conv1d` when it's absent.
|
||||
Native NemotronH uses Mamba2 Triton SSD kernels and FLA's packed causal convolution. The pinned `mamba-ssm` source installs without `nvcc`; no separate `causal-conv1d` installation is needed. `uv sync --all-extras` includes these dependencies.
|
||||
|
||||
### Trainer DeepEP backend
|
||||
|
||||
|
||||
@@ -128,7 +128,7 @@ interval = 10 # completed task groups between cursor saves
|
||||
```
|
||||
|
||||
- Env servers: spawned by the evals process, one per source without an explicit `serve.address`, at `tcp://127.0.0.1:<eval.env_server_base_port + index>`; logs at `{output_dir}/logs/latest/envs/eval/{name}.log`.
|
||||
- External inference APIs (no vLLM `/metrics`, e.g. Prime Inference) have no load signal for adaptive concurrency: the startup `/metrics` probe fails fast unless the band is pinned (`min_inflight = max_inflight`). Full example: `examples/evals/swe.toml` (SWE-bench Verified + Terminal-Bench 2 on Prime Inference, `agent.timeout.rollout = 3600`).
|
||||
- External inference APIs (no vLLM `/metrics`, e.g. Prime Inference) have no load signal for adaptive concurrency: the startup `/metrics` probe fails fast unless the band is pinned (`min_inflight = max_inflight`). Full example: `configs/evals/swe.toml` (SWE-bench Verified + Terminal-Bench 2 on Prime Inference, `agent.timeout.rollout = 3600`).
|
||||
- Config: `EvalsConfig` (`packages/prime-rl-configs/src/prime_rl/configs/evals.py`)
|
||||
- Entrypoint: `src/prime_rl/entrypoints/evals.py` (implementation: `src/prime_rl/evals/evals.py`)
|
||||
|
||||
|
||||
@@ -47,8 +47,7 @@ if _hub_kernels is not None:
|
||||
try:
|
||||
return _original_lazy_load_kernel(kernel_name, mapping)
|
||||
except OfflineModeIsEnabled:
|
||||
# Return None so NemotronH skips hub kernels; prime-rl's
|
||||
# _patch_mamba2_use_triton_ssd() uses mamba_ssm directly.
|
||||
# Return None so callers can use their non-hub implementation.
|
||||
mapping[kernel_name] = None
|
||||
return None
|
||||
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
`uv run dashboard [output_dir ...]` — a local web dashboard for run output
|
||||
directories (metrics, resolved configs, rollout traces, cited reports,
|
||||
component logs) at
|
||||
http://localhost:7788. The trace viewer includes transcript and synchronized
|
||||
agent timeline views; timeline activities open the corresponding transcript
|
||||
call. Needs the `dashboard` extra. Every instance also serves
|
||||
http://localhost:7788. The trace viewer includes transcript, synchronized
|
||||
agent timeline, and terminal replay views; timeline activities open the
|
||||
corresponding transcript call. Needs the `dashboard` extra. Every instance also serves
|
||||
the dirs registered by launchers in `~/.cache/prime-rl/dashboard/dirs.json`
|
||||
(one dashboard per host per user); `--isolated` serves only the given dirs and
|
||||
skips the registry. See `skills/dashboard/SKILL.md` for discovery,
|
||||
@@ -30,6 +30,23 @@ truth, and the viewer reports when IDs, the renderer model, or its tokenizer
|
||||
are unavailable. Text, advantage, logprob, mask, and content signals apply to
|
||||
both views; Rendered with Text uses the exact full-sequence decode.
|
||||
|
||||
**Replay** plays the selected trace branch as a terminal session. Model
|
||||
responses, tool commands, and tool results follow their recorded wall-clock
|
||||
spans, with play/pause, seeking, restart, and speed controls. Providers persist
|
||||
the full model-call span rather than timestamps for individual tokens, so text
|
||||
is revealed evenly across that measured span and the UI labels the token cadence
|
||||
as inferred. Replay defaults to 8× for long coding-agent waits while preserving
|
||||
their relative timing; 1× restores exact wall time, and speeds up to 32× are
|
||||
available. In-flight calls show measured progress and recorded output usage even
|
||||
when the response contains only a tool call. Events from older traces without
|
||||
timing stay in order and are marked untimed. Prompt context committed at response
|
||||
time appears at the linked model call's start rather than creating a false blank
|
||||
delay. **Skip inference** makes every model response immediate while retaining
|
||||
the recorded delays between tool commands and their outputs. Recorded model
|
||||
thinking is visible by default and can be toggled from the controls or with
|
||||
**T** while Replay is open. **Top** (or **Home**) stops following the newest
|
||||
line and scrolls to the beginning; **Live** (or **End**) resumes following output.
|
||||
|
||||
This package is fully AI-generated and maintained by agents - it is not meant to be read or edited by humans. Change it by asking an agent, and verify through the browser smoke tests.
|
||||
The integration suite covers it end to end (`tests/integration/dashboard_smoke.py`
|
||||
runs after every integration test).
|
||||
|
||||
@@ -884,6 +884,7 @@ def activity_spans(
|
||||
if reasoning_tokens is None:
|
||||
reasoning_tokens = (usage.get("completion_tokens_details") or {}).get("reasoning_tokens")
|
||||
text = " ".join(message_text(node.get("message") or {}).split())
|
||||
mask = node.get("mask")
|
||||
spans.append(
|
||||
{
|
||||
"kind": "model_call",
|
||||
@@ -901,6 +902,7 @@ def activity_spans(
|
||||
"output_tokens": output_tokens,
|
||||
"reasoning_tokens": reasoning_tokens,
|
||||
"cost": usage.get("cost"),
|
||||
"trainable": any(mask) if isinstance(mask, list) and mask else None,
|
||||
}
|
||||
)
|
||||
return sorted(spans, key=lambda span: span["started_at"] if span["started_at"] is not None else float("inf"))
|
||||
@@ -991,6 +993,7 @@ def timeline_lane(
|
||||
"total_input_tokens": total_input_tokens,
|
||||
"output_tokens": output_tokens,
|
||||
"reasoning_tokens": reasoning_tokens,
|
||||
"latest_context_tokens": context_lengths[-1] if context_lengths else None,
|
||||
"max_context_tokens": max(context_lengths, default=None),
|
||||
"total_tokens": total_tokens,
|
||||
"cost": total("cost"),
|
||||
@@ -999,8 +1002,254 @@ def timeline_lane(
|
||||
}
|
||||
|
||||
|
||||
def trace_semantic_edges(trace: dict, trace_index: int) -> list[dict]:
|
||||
"""Resolve persisted ``MessageNode.semantic_parents`` into timeline edges."""
|
||||
nodes = trace.get("nodes") or []
|
||||
call_order = {
|
||||
node_index: call_index
|
||||
for call_index, call in enumerate(trace.get("calls") or [])
|
||||
if isinstance((node_index := call.get("node")), int) and 0 <= node_index < len(nodes)
|
||||
}
|
||||
call_nodes = set(call_order)
|
||||
edges = []
|
||||
for target_node, node in enumerate(nodes):
|
||||
if target_node not in call_nodes:
|
||||
continue
|
||||
for link in node.get("semantic_parents") or []:
|
||||
source_node = link.get("node")
|
||||
edge_type = link.get("type")
|
||||
if source_node not in call_nodes or not isinstance(edge_type, str):
|
||||
continue
|
||||
edges.append(
|
||||
{
|
||||
"trace_index": trace_index,
|
||||
"source_node": source_node,
|
||||
"target_node": target_node,
|
||||
"type": edge_type,
|
||||
}
|
||||
)
|
||||
if not edges:
|
||||
return []
|
||||
|
||||
incoming = {edge["target_node"] for edge in edges}
|
||||
for target_node in sorted(call_nodes - incoming, key=call_order.get):
|
||||
source_node = physical_continuation_source(nodes, call_nodes, target_node)
|
||||
if source_node is None or call_order[source_node] >= call_order[target_node]:
|
||||
continue
|
||||
edges.append(
|
||||
{
|
||||
"trace_index": trace_index,
|
||||
"source_node": source_node,
|
||||
"target_node": target_node,
|
||||
"type": "continuation",
|
||||
"inferred": True,
|
||||
}
|
||||
)
|
||||
return edges
|
||||
|
||||
|
||||
def physical_continuation_source(nodes: list[dict], call_nodes: set[int], target_node: int) -> int | None:
|
||||
"""Recover a missing continuation only from a completed tool round-trip."""
|
||||
between = []
|
||||
visited = {target_node}
|
||||
cursor = nodes[target_node].get("parent")
|
||||
while isinstance(cursor, int) and 0 <= cursor < len(nodes) and cursor not in visited:
|
||||
if cursor in call_nodes:
|
||||
source_node = cursor
|
||||
break
|
||||
visited.add(cursor)
|
||||
between.append(cursor)
|
||||
cursor = nodes[cursor].get("parent")
|
||||
else:
|
||||
return None
|
||||
|
||||
source_message = nodes[source_node].get("message") or {}
|
||||
tool_call_ids = {
|
||||
tool_call.get("id")
|
||||
for tool_call in source_message.get("tool_calls") or []
|
||||
if isinstance(tool_call, dict) and isinstance(tool_call.get("id"), str)
|
||||
}
|
||||
if not tool_call_ids or not between:
|
||||
return None
|
||||
for node_index in between:
|
||||
message = nodes[node_index].get("message") or {}
|
||||
if message.get("role") != "tool" or message.get("tool_call_id") not in tool_call_ids:
|
||||
return None
|
||||
return source_node
|
||||
|
||||
|
||||
def semantic_context_lanes(
|
||||
trace: dict,
|
||||
trace_index: int,
|
||||
role: str,
|
||||
edges: list[dict],
|
||||
) -> list[dict]:
|
||||
"""Project continuation components as execution-context timeline lanes.
|
||||
|
||||
``continuation`` keeps calls in one context. ``subagent_call`` creates a child
|
||||
agent, ``compaction_attempt`` creates a summary leaf beside its source context,
|
||||
and ``compaction`` starts a new context for the same agent. Other edge labels
|
||||
remain visible but do not invent session semantics.
|
||||
"""
|
||||
nodes = trace.get("nodes") or []
|
||||
call_nodes = {
|
||||
node_index
|
||||
for call in trace.get("calls") or []
|
||||
if isinstance((node_index := call.get("node")), int) and 0 <= node_index < len(nodes)
|
||||
}
|
||||
if not call_nodes or not edges:
|
||||
return []
|
||||
|
||||
representatives = {node_index: node_index for node_index in call_nodes}
|
||||
|
||||
def find(node_index: int) -> int:
|
||||
while representatives[node_index] != node_index:
|
||||
representatives[node_index] = representatives[representatives[node_index]]
|
||||
node_index = representatives[node_index]
|
||||
return node_index
|
||||
|
||||
def union(left: int, right: int) -> None:
|
||||
left_root = find(left)
|
||||
right_root = find(right)
|
||||
if left_root != right_root:
|
||||
representatives[right_root] = left_root
|
||||
|
||||
for edge in edges:
|
||||
if edge["type"] == "continuation":
|
||||
union(edge["source_node"], edge["target_node"])
|
||||
|
||||
components: dict[int, set[int]] = {}
|
||||
for node_index in call_nodes:
|
||||
components.setdefault(find(node_index), set()).add(node_index)
|
||||
component_for = {
|
||||
node_index: component for component, node_indexes in components.items() for node_index in node_indexes
|
||||
}
|
||||
|
||||
component_activities = {
|
||||
component: activity_spans(trace, node_indexes) for component, node_indexes in components.items()
|
||||
}
|
||||
|
||||
def component_start(component: int) -> float:
|
||||
activities = component_activities[component]
|
||||
starts = [span["started_at"] for span in activities if span["started_at"] is not None]
|
||||
timestamps = [
|
||||
nodes[node_index].get("timestamp")
|
||||
for node_index in components[component]
|
||||
if nodes[node_index].get("timestamp") is not None
|
||||
]
|
||||
return min(starts or timestamps, default=float("inf"))
|
||||
|
||||
ordered_components = sorted(components, key=lambda component: (component_start(component), component))
|
||||
cross_edges = [edge for edge in edges if component_for[edge["source_node"]] != component_for[edge["target_node"]]]
|
||||
created_components = {
|
||||
component_for[edge["target_node"]]
|
||||
for edge in cross_edges
|
||||
if edge["type"] in {"subagent_call", "compaction_attempt", "compaction"}
|
||||
}
|
||||
root_components = [component for component in ordered_components if component not in created_components]
|
||||
|
||||
# component -> (agent label, depth, context index)
|
||||
identities: dict[int, tuple[str, int, int]] = {}
|
||||
unlinked_components = set()
|
||||
if root_components:
|
||||
identities[root_components[0]] = (role, 0, 0)
|
||||
for index, component in enumerate(root_components[1:], start=1):
|
||||
identities[component] = (f"unlinked {index}", 0, 0)
|
||||
unlinked_components.add(component)
|
||||
|
||||
subagent_number = 0
|
||||
changed = True
|
||||
while changed:
|
||||
changed = False
|
||||
for edge in cross_edges:
|
||||
source = component_for[edge["source_node"]]
|
||||
target = component_for[edge["target_node"]]
|
||||
if source not in identities or target in identities:
|
||||
continue
|
||||
agent_label, depth, context_index = identities[source]
|
||||
if edge["type"] == "subagent_call":
|
||||
subagent_number += 1
|
||||
identities[target] = (f"subagent {subagent_number}", depth + 1, 0)
|
||||
elif edge["type"] == "compaction_attempt":
|
||||
identities[target] = (agent_label, depth, context_index)
|
||||
elif edge["type"] == "compaction":
|
||||
identities[target] = (agent_label, depth, context_index + 1)
|
||||
else:
|
||||
continue
|
||||
changed = True
|
||||
|
||||
unlinked_index = len(unlinked_components)
|
||||
for component in ordered_components:
|
||||
if component not in identities:
|
||||
unlinked_index += 1
|
||||
identities[component] = (f"unlinked {unlinked_index}", 0, 0)
|
||||
unlinked_components.add(component)
|
||||
|
||||
lanes = []
|
||||
accepted_attempt_nodes = {edge["source_node"] for edge in cross_edges if edge["type"] == "compaction"}
|
||||
attempt_by_component = {
|
||||
component_for[edge["target_node"]]: {
|
||||
"source_node": edge["source_node"],
|
||||
"target_node": edge["target_node"],
|
||||
"accepted": edge["target_node"] in accepted_attempt_nodes,
|
||||
}
|
||||
for edge in cross_edges
|
||||
if edge["type"] == "compaction_attempt"
|
||||
}
|
||||
for component in ordered_components:
|
||||
agent_label, depth, context_index = identities[component]
|
||||
activities = component_activities[component]
|
||||
start = component_start(component)
|
||||
end = max(
|
||||
[span["ended_at"] for span in activities if span.get("ended_at") is not None]
|
||||
+ [
|
||||
nodes[node_index].get("timestamp")
|
||||
for node_index in components[component]
|
||||
if nodes[node_index].get("timestamp") is not None
|
||||
],
|
||||
default=None,
|
||||
)
|
||||
completed = bool(trace.get("is_completed"))
|
||||
label = f"{agent_label} · context {context_index}"
|
||||
lifecycle = (
|
||||
[
|
||||
{
|
||||
"kind": "agent",
|
||||
"label": label,
|
||||
"track": "lifecycle",
|
||||
"started_at": start,
|
||||
"ended_at": end if completed else None,
|
||||
"status": "completed" if completed else "running",
|
||||
}
|
||||
]
|
||||
if start != float("inf")
|
||||
else []
|
||||
)
|
||||
lane = timeline_lane(
|
||||
trace,
|
||||
trace_index,
|
||||
label=label,
|
||||
depth=depth + 1,
|
||||
branch=True,
|
||||
lifecycle=lifecycle,
|
||||
activities=activities,
|
||||
)
|
||||
lane["context"] = {
|
||||
"agent": agent_label,
|
||||
"index": context_index,
|
||||
}
|
||||
if component in unlinked_components:
|
||||
lane["context"]["unlinked"] = True
|
||||
if component in attempt_by_component:
|
||||
lane["compaction_attempt"] = attempt_by_component[component]
|
||||
lanes.append(lane)
|
||||
return lanes
|
||||
|
||||
|
||||
def project_episode_timeline(episode: dict) -> dict:
|
||||
lane_groups = []
|
||||
semantic_lane_groups = []
|
||||
semantic_edges = []
|
||||
for trace_index, trace in enumerate(episode.get("traces") or []):
|
||||
nodes = trace.get("nodes") or []
|
||||
branch_paths = branch_node_paths(nodes)
|
||||
@@ -1085,9 +1334,22 @@ def project_episode_timeline(episode: dict) -> dict:
|
||||
)
|
||||
branches.sort(key=lambda item: (item[0] if item[0] is not None else float("inf"), item[1]))
|
||||
lane_groups.append((parent, [lane for _, _, lane in branches]))
|
||||
trace_edges = trace_semantic_edges(trace, trace_index)
|
||||
semantic_lanes = semantic_context_lanes(trace, trace_index, role, trace_edges)
|
||||
if semantic_lanes:
|
||||
semantic_lane_groups.append((parent, semantic_lanes))
|
||||
semantic_edges.extend(trace_edges)
|
||||
lane_groups.sort(key=lambda group: group[0]["started_at"] if group[0]["started_at"] is not None else float("inf"))
|
||||
lanes = [lane for parent, children in lane_groups for lane in (parent, *children)]
|
||||
return {"lanes": lanes}
|
||||
semantic_lane_groups.sort(
|
||||
key=lambda group: group[0]["started_at"] if group[0]["started_at"] is not None else float("inf")
|
||||
)
|
||||
semantic_lanes = [lane for parent, children in semantic_lane_groups for lane in (parent, *children)]
|
||||
return {
|
||||
"lanes": lanes,
|
||||
"semantic_lanes": semantic_lanes,
|
||||
"semantic_edges": semantic_edges,
|
||||
}
|
||||
|
||||
|
||||
NICE_BINS = [1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 900, 1800, 3600, 7200, 10800, 21600, 43200, 86400]
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -232,6 +232,13 @@
|
||||
<div class="seg" id="tm-view">
|
||||
<button data-view="transcript" class="active">Transcript</button>
|
||||
<button data-view="timeline">Timeline</button>
|
||||
<button data-view="replay">Replay</button>
|
||||
<button data-view="semantic">Semantic</button>
|
||||
</div>
|
||||
<div id="tm-semantic-nav" class="tm-semantic-nav" hidden>
|
||||
<button id="tm-episode-prev" class="btn tm-nav" title="previous episode">‹</button>
|
||||
<span id="tm-episode-label"></span>
|
||||
<button id="tm-episode-next" class="btn tm-nav" title="next episode">›</button>
|
||||
</div>
|
||||
<div class="spacer"></div>
|
||||
<div class="seg" id="trace-view-mode">
|
||||
@@ -258,6 +265,14 @@
|
||||
</div>
|
||||
<div id="tm-messages"></div>
|
||||
<div id="tm-timeline" hidden></div>
|
||||
<aside id="sg-inspector" hidden>
|
||||
<div class="sg-inspector-head">
|
||||
<span id="sg-inspector-title">Model call</span>
|
||||
<button id="sg-inspector-close" class="btn" title="close inspector">✕</button>
|
||||
</div>
|
||||
<div id="sg-inspector-body"></div>
|
||||
<button id="sg-open-transcript" class="btn">open in transcript</button>
|
||||
</aside>
|
||||
</section>
|
||||
<aside id="tm-right">
|
||||
<div class="tm-head"><span class="tm-title">Overview</span></div>
|
||||
|
||||
@@ -680,6 +680,10 @@ mark.hit {
|
||||
display: grid;
|
||||
grid-template-columns: 280px minmax(0, 1fr) 320px;
|
||||
}
|
||||
#trace-modal.semantic-view { grid-template-columns: minmax(0, 1fr); }
|
||||
#trace-modal.semantic-view #tm-left,
|
||||
#trace-modal.semantic-view #tm-right { display: none; }
|
||||
#trace-modal.semantic-view #tm-main { grid-column: 1; position: relative; }
|
||||
.tm-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -698,6 +702,15 @@ mark.hit {
|
||||
#tm-evidence-tabs [data-evidence="judge"].active { color: #7adfff; }
|
||||
#tm-evidence-tabs { margin-left: auto; }
|
||||
.tm-title { font-size: 12px; font-weight: 500; color: var(--grey-6); white-space: nowrap; }
|
||||
.tm-semantic-nav { display: flex; align-items: center; gap: 7px; min-width: 0; }
|
||||
#tm-episode-label {
|
||||
max-width: 260px;
|
||||
overflow: hidden;
|
||||
color: var(--grey-5);
|
||||
font-size: 10.5px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
#tm-left { border-right: 1px solid var(--hairline); display: flex; flex-direction: column; min-height: 0; }
|
||||
#tm-left .search { margin: 10px 14px 6px; }
|
||||
#tm-list { flex: 1; overflow-y: auto; padding: 4px 8px 10px; }
|
||||
@@ -741,11 +754,39 @@ mark.hit {
|
||||
#tm-messages { display: flex; flex: 1; flex-direction: column; overflow-y: auto; padding: 14px 16px; }
|
||||
#tm-messages > * { flex-shrink: 0; }
|
||||
#tm-timeline { flex: 1; min-height: 0; overflow: auto; padding: 14px 16px 24px; }
|
||||
#tm-timeline.semantic-canvas { padding: 0; background: var(--grey-1); }
|
||||
#tm-right { border-left: 1px solid var(--hairline); overflow-y: auto; min-height: 0; }
|
||||
#tm-meta { padding: 12px 14px; }
|
||||
|
||||
/* episode timeline: lifecycle spans above exact model-call activity */
|
||||
.tl-shell { min-width: 780px; border: 1px solid var(--hairline); }
|
||||
.tl-shell { position: relative; min-width: 780px; border: 1px solid var(--hairline); }
|
||||
.tl-edge-legend {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 14px;
|
||||
min-height: 34px;
|
||||
padding: 7px 10px;
|
||||
border-bottom: 1px solid var(--hairline);
|
||||
color: var(--grey-4);
|
||||
font-size: 9px;
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.tl-edge-legend-title { color: var(--grey-5); }
|
||||
.tl-edge-key { color: var(--grey-5); white-space: nowrap; }
|
||||
.tl-edge-key i {
|
||||
display: inline-block;
|
||||
width: 18px;
|
||||
margin-right: 6px;
|
||||
vertical-align: 3px;
|
||||
border-top: 2px solid var(--grey-4);
|
||||
}
|
||||
.tl-edge-key i.subagent-call { border-color: var(--infra); }
|
||||
.tl-edge-key i.subagent-return { border-color: var(--risk); }
|
||||
.tl-edge-key i.compaction-attempt { border-color: var(--chart-2); border-top-style: dotted; }
|
||||
.tl-edge-key i.compaction { border-color: var(--chart-2); border-top-style: dashed; }
|
||||
.tl-edge-key i.custom { border-color: var(--accent); border-top-style: dotted; }
|
||||
.tl-head, .tl-lane {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(160px, 220px) minmax(390px, 1fr) 105px 150px;
|
||||
@@ -776,7 +817,7 @@ mark.hit {
|
||||
.tl-label-meta { color: var(--grey-4); font-size: 9.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.tl-track { position: relative; height: 42px; margin: 11px 0; border: 1px solid var(--hairline); overflow: hidden; }
|
||||
.tl-gridline { position: absolute; top: 0; bottom: 0; border-left: 1px solid var(--hairline-faint); pointer-events: none; }
|
||||
.tl-span { position: absolute; min-width: 3px; cursor: pointer; border: 0; padding: 0; }
|
||||
.tl-span { position: absolute; z-index: 2; min-width: 3px; cursor: pointer; border: 0; padding: 0; }
|
||||
.tl-span.lifecycle { top: 7px; height: 13px; opacity: 0.78; }
|
||||
.tl-span.activity { top: 28px; height: 6px; background: var(--grey-4); }
|
||||
.tl-span.activity.shared { opacity: 0.28; }
|
||||
@@ -790,11 +831,10 @@ mark.hit {
|
||||
.tl-time { color: var(--grey-5); font-size: 11px; }
|
||||
.tl-time .muted { display: block; font-size: 9.5px; }
|
||||
.tl-outcome { display: flex; flex-direction: column; align-items: flex-start; gap: 5px; font-size: 9.5px; }
|
||||
.tl-state, .tl-reward { border: 1px solid var(--grey-3); padding: 1px 5px; white-space: nowrap; }
|
||||
.tl-state { border: 1px solid var(--grey-3); padding: 1px 5px; white-space: nowrap; }
|
||||
.tl-state.completed { color: var(--positive); }
|
||||
.tl-state.failed { color: var(--negative); }
|
||||
.tl-state.running { color: var(--infra); }
|
||||
.tl-reward { color: var(--chart-3); }
|
||||
.tl-tooltip {
|
||||
position: fixed;
|
||||
z-index: 60;
|
||||
@@ -812,6 +852,221 @@ mark.hit {
|
||||
.tl-tooltip dd { color: var(--grey-6); margin: 0; }
|
||||
.tl-tooltip-hint { color: var(--grey-4); border-top: 1px solid var(--hairline); margin-top: 9px; padding-top: 7px; font-size: 9.5px; }
|
||||
|
||||
/* Semantic view: ordinal causal flow down the page. Agent identities occupy
|
||||
reusable concurrency slots, so width reflects peak fan-out rather than the
|
||||
total number of children created over a rollout. */
|
||||
.semantic-canvas > .tl-edge-legend {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
left: 0;
|
||||
z-index: 9;
|
||||
width: max-content;
|
||||
min-width: 100%;
|
||||
box-sizing: border-box;
|
||||
background: var(--grey-1);
|
||||
font-size: 11px;
|
||||
}
|
||||
.sg-shell {
|
||||
position: relative;
|
||||
min-width: 100%;
|
||||
overflow: clip;
|
||||
background: var(--grey-1);
|
||||
}
|
||||
.sg-lane-band {
|
||||
position: absolute;
|
||||
inset-block: 0;
|
||||
z-index: 0;
|
||||
border-inline: 1px solid rgba(255, 255, 255, 0.035);
|
||||
background: rgba(255, 255, 255, 0.009);
|
||||
pointer-events: none;
|
||||
}
|
||||
.sg-lane-band.root {
|
||||
border-inline-color: rgba(182, 255, 60, 0.07);
|
||||
background: rgba(182, 255, 60, 0.012);
|
||||
}
|
||||
.sg-edge-layer { position: absolute; inset: 0; z-index: 1; pointer-events: none; overflow: visible; }
|
||||
.sg-lifeline {
|
||||
fill: none;
|
||||
stroke: var(--lane-color);
|
||||
stroke-width: 1.5;
|
||||
vector-effect: non-scaling-stroke;
|
||||
opacity: 0.38;
|
||||
}
|
||||
.sg-edge {
|
||||
fill: none;
|
||||
stroke: var(--grey-4);
|
||||
stroke-width: 1.4;
|
||||
stroke-linecap: round;
|
||||
stroke-linejoin: round;
|
||||
vector-effect: non-scaling-stroke;
|
||||
opacity: 0.68;
|
||||
}
|
||||
.sg-edge.continuation { opacity: 0.34; }
|
||||
.sg-edge.subagent-call { stroke: var(--infra); stroke-width: 2.2; opacity: 0.9; }
|
||||
.sg-edge.subagent-return { stroke: var(--risk); stroke-width: 2.2; opacity: 0.9; }
|
||||
.sg-edge.compaction-attempt { stroke: var(--chart-2); stroke-dasharray: 2 4; opacity: 0.66; }
|
||||
.sg-edge.compaction { stroke: var(--chart-2); stroke-dasharray: 5 4; opacity: 0.9; }
|
||||
.sg-edge.custom { stroke: var(--accent); stroke-dasharray: 2 4; opacity: 0.9; }
|
||||
#sg-arrow-continuation path { fill: var(--grey-4); }
|
||||
#sg-arrow-subagent-call path { fill: var(--infra); }
|
||||
#sg-arrow-subagent-return path { fill: var(--risk); }
|
||||
#sg-arrow-compaction-attempt path { fill: var(--chart-2); }
|
||||
#sg-arrow-compaction path { fill: var(--chart-2); }
|
||||
#sg-arrow-custom path { fill: var(--accent); }
|
||||
.sg-agent-label {
|
||||
position: absolute;
|
||||
z-index: 6;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 1px;
|
||||
padding: 2px 6px;
|
||||
background: var(--grey-1);
|
||||
pointer-events: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.sg-agent-label.unlinked {
|
||||
outline: 1px dashed var(--grey-3);
|
||||
}
|
||||
.sg-agent-label.unlinked .sg-agent-name,
|
||||
.sg-agent-label.unlinked .sg-context-name {
|
||||
color: var(--grey-5);
|
||||
}
|
||||
.sg-agent-name,
|
||||
.sg-context-name {
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
white-space: nowrap;
|
||||
pointer-events: auto;
|
||||
}
|
||||
.sg-agent-name {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
color: var(--grey-6);
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.sg-agent-name i { width: 8px; height: 8px; flex: none; }
|
||||
.sg-context-name { color: var(--grey-5); font-size: 10.5px; letter-spacing: var(--track-caps); text-transform: uppercase; }
|
||||
.sg-agent-label.compacted .sg-context-name { color: var(--chart-2); }
|
||||
.sg-agent-name:hover,
|
||||
.sg-agent-name:focus-visible,
|
||||
.sg-context-name:hover,
|
||||
.sg-context-name:focus-visible { color: var(--accent); outline: none; }
|
||||
.sg-agent-name:focus-visible,
|
||||
.sg-context-name:focus-visible { text-decoration: underline; text-underline-offset: 3px; }
|
||||
.sg-agent-label.side-left { align-items: flex-end; text-align: right; }
|
||||
.sg-agent-label.side-right { align-items: flex-start; text-align: left; }
|
||||
.sg-turn {
|
||||
position: absolute;
|
||||
z-index: 3;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--grey-4);
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
outline: none;
|
||||
}
|
||||
.sg-turn-mark {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
width: var(--turn-mark-width, 44px);
|
||||
height: var(--turn-mark-height, 12px);
|
||||
background: var(--turn-color);
|
||||
transform: translate(-50%, -50%);
|
||||
transition: width 100ms ease, height 100ms ease, background 100ms ease;
|
||||
}
|
||||
.sg-turn-index {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: calc(50% + var(--turn-label-offset, 31px));
|
||||
color: var(--grey-5);
|
||||
font-size: 12.5px;
|
||||
transform: translateY(-50%);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.sg-turn:hover,
|
||||
.sg-turn:focus-visible { z-index: 4; }
|
||||
.sg-turn:hover .sg-turn-mark,
|
||||
.sg-turn:focus-visible .sg-turn-mark {
|
||||
width: calc(var(--turn-mark-width, 44px) + 6px);
|
||||
height: calc(var(--turn-mark-height, 12px) + 2px);
|
||||
background: var(--accent);
|
||||
}
|
||||
.sg-turn:focus-visible .sg-turn-mark { outline: 1px solid var(--grey-6); outline-offset: 2px; }
|
||||
.sg-turn.compaction-attempt.accepted .sg-turn-mark {
|
||||
outline: 1px solid var(--chart-2);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.sg-turn.compaction-attempt.rejected .sg-turn-mark {
|
||||
border: 1px dashed var(--chart-2);
|
||||
background: var(--grey-1);
|
||||
opacity: 0.72;
|
||||
}
|
||||
.sg-turn.compaction-attempt.rejected .sg-turn-index { color: var(--grey-4); }
|
||||
.sg-turn.compaction-attempt.rejected:hover .sg-turn-mark,
|
||||
.sg-turn.compaction-attempt.rejected:focus-visible .sg-turn-mark {
|
||||
border-color: var(--grey-6);
|
||||
background: var(--grey-2);
|
||||
opacity: 1;
|
||||
}
|
||||
.sg-turn-run {
|
||||
position: absolute;
|
||||
z-index: 5;
|
||||
padding: 0 7px;
|
||||
border: 0;
|
||||
border-block: 1px solid color-mix(in srgb, var(--turn-color) 56%, var(--grey-3));
|
||||
background: var(--grey-1);
|
||||
color: var(--grey-5);
|
||||
cursor: pointer;
|
||||
font: 10.5px/1 var(--font-mono);
|
||||
letter-spacing: 0.04em;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.sg-turn-run.collapsed {
|
||||
box-shadow: 0 0 0 4px var(--grey-1);
|
||||
}
|
||||
.sg-turn-run.expanded {
|
||||
border: 1px dashed color-mix(in srgb, var(--turn-color) 45%, var(--grey-3));
|
||||
color: var(--grey-4);
|
||||
}
|
||||
.sg-turn-run:hover,
|
||||
.sg-turn-run:focus-visible {
|
||||
color: var(--grey-6);
|
||||
outline: none;
|
||||
}
|
||||
.sg-turn-run.collapsed:hover,
|
||||
.sg-turn-run.collapsed:focus-visible { border-block-color: var(--turn-color); }
|
||||
.sg-turn-run:focus-visible { box-shadow: 0 0 0 2px var(--grey-1), 0 0 0 3px var(--turn-color); }
|
||||
|
||||
#sg-inspector {
|
||||
position: absolute;
|
||||
top: 62px;
|
||||
right: 14px;
|
||||
bottom: 14px;
|
||||
z-index: 20;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: min(330px, calc(100% - 28px));
|
||||
border: 1px solid var(--grey-4);
|
||||
background: rgba(25, 25, 25, 0.98);
|
||||
}
|
||||
.sg-inspector-head { display: flex; align-items: center; gap: 8px; min-height: 46px; padding: 0 12px; border-bottom: 1px solid var(--hairline); color: var(--grey-6); font-size: 11px; }
|
||||
.sg-inspector-head button { margin-left: auto; }
|
||||
#sg-inspector-body { flex: 1; min-height: 0; overflow-y: auto; padding: 4px 13px 14px; }
|
||||
.sg-inspector-section { margin: 13px 0 6px; color: var(--accent); font-size: 9px; letter-spacing: var(--track-caps); text-transform: uppercase; }
|
||||
.sg-inspector-row { display: flex; gap: 12px; padding: 3px 0; font-size: 10.5px; }
|
||||
.sg-inspector-row span { color: var(--grey-4); }
|
||||
.sg-inspector-row strong { margin-left: auto; color: var(--grey-6); font-weight: 400; }
|
||||
.sg-inspector-snippet { color: var(--grey-5); font-size: 10.5px; line-height: 1.5; white-space: pre-wrap; word-break: break-word; }
|
||||
#sg-open-transcript { margin: 0 12px 12px; min-height: 30px; }
|
||||
|
||||
/* the banners lead the transcript, so they stand off the first entry */
|
||||
.trace-errors { margin-top: auto; padding-top: 12px; margin-bottom: 14px; }
|
||||
.trace-error-banner {
|
||||
@@ -847,6 +1102,13 @@ mark.hit {
|
||||
|
||||
/* numbered collapsible message entries */
|
||||
details.entry { border: 1px solid var(--hairline); margin-bottom: 8px; }
|
||||
details.entry.semantic-origin {
|
||||
border-color: var(--accent);
|
||||
outline: 1px solid rgba(182, 255, 60, 0.55);
|
||||
outline-offset: 2px;
|
||||
scroll-margin-block: 80px;
|
||||
}
|
||||
details.entry.semantic-origin > summary { background: rgba(182, 255, 60, 0.08); }
|
||||
details.entry > summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -1055,6 +1317,78 @@ details.meta-fold > pre { margin: 0; border: none; border-top: 1px solid var(--h
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
/* terminal replay follows the trace's wall clock; message text is revealed
|
||||
across its recorded model-call span because providers do not persist per-token timestamps */
|
||||
.replay-shell {
|
||||
display: flex;
|
||||
flex: 1 1 auto !important;
|
||||
min-height: 420px;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--grey-3);
|
||||
background: #080b07;
|
||||
}
|
||||
.replay-bar, .replay-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-height: 40px;
|
||||
padding: 7px 12px;
|
||||
border-bottom: 1px solid rgba(182, 255, 60, 0.12);
|
||||
background: #0d110c;
|
||||
}
|
||||
.replay-lights { color: var(--grey-3); letter-spacing: 3px; font-size: 8px; }
|
||||
.replay-title { color: var(--grey-6); font-size: 11px; }
|
||||
.replay-bar .chip { margin-left: auto; }
|
||||
.replay-controls .btn { min-width: 48px; }
|
||||
#replay-top, #replay-live { min-width: 52px; }
|
||||
#replay-top.active, #replay-live.active { color: var(--accent); border-color: rgba(182, 255, 60, 0.35); }
|
||||
#replay-restart { min-width: 30px; }
|
||||
#replay-progress { flex: 1; min-width: 80px; accent-color: var(--accent); }
|
||||
#replay-time { color: var(--grey-4); font: 400 10.5px var(--font-mono); white-space: nowrap; }
|
||||
.replay-skip { display: flex; align-items: center; gap: 5px; color: var(--grey-5); font-size: 10.5px; white-space: nowrap; }
|
||||
.replay-skip input { accent-color: var(--accent); }
|
||||
.replay-skip kbd { color: var(--grey-4); font: 400 8.5px var(--font-mono); border: 1px solid var(--grey-3); padding: 1px 3px; }
|
||||
.replay-control-label { color: var(--grey-4); font-size: 9px; letter-spacing: var(--track-caps); text-transform: uppercase; }
|
||||
#replay-speed {
|
||||
border: 1px solid var(--grey-3);
|
||||
background: var(--grey-1);
|
||||
color: var(--grey-5);
|
||||
font: 400 10.5px var(--font-mono);
|
||||
padding: 4px 6px;
|
||||
}
|
||||
.replay-output-pane {
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
padding: 16px 18px 40px;
|
||||
color: #c8d1c5;
|
||||
font: 400 12px/1.6 var(--font-mono);
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.replay-event { display: grid; grid-template-columns: 64px minmax(0, 1fr); gap: 12px; margin-bottom: 14px; }
|
||||
.replay-event > div > span { display: block; }
|
||||
.replay-stamp { color: #52604e; font-size: 9.5px; padding-top: 2px; }
|
||||
.replay-system { color: #7c8978; }
|
||||
.replay-user { color: #f1f5ef; }
|
||||
.replay-assistant { color: #c8d1c5; }
|
||||
.replay-command { margin-top: 7px; color: var(--accent); }
|
||||
.replay-output { padding-left: 10px; border-left: 1px solid #33432d; color: #9dac98; }
|
||||
.replay-wait, .replay-running { color: #70806c; }
|
||||
.replay-model-wait {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
gap: 4px 16px;
|
||||
margin-bottom: 8px;
|
||||
color: #70806c;
|
||||
font-size: 10.5px;
|
||||
}
|
||||
.replay-model-wait > i { grid-column: 1 / -1; height: 2px; overflow: hidden; background: #1c2719; }
|
||||
.replay-model-wait > i > b { display: block; height: 100%; background: var(--accent); }
|
||||
.replay-running { display: flex; align-items: center; gap: 8px; margin: 0 0 14px 76px; }
|
||||
.replay-spinner { width: 7px; height: 7px; border: 1px solid #52604e; border-top-color: var(--accent); border-radius: 50%; animation: replay-spin 0.8s linear infinite; }
|
||||
@keyframes replay-spin { to { transform: rotate(360deg); } }
|
||||
|
||||
.tok { padding: 0 1px; }
|
||||
.tok:hover { outline: 1px solid var(--grey-6); }
|
||||
.tok-tip {
|
||||
|
||||
@@ -37,7 +37,7 @@ from prime_rl.configs.evals import EvalsConfig
|
||||
from prime_rl.configs.trainer import FileSystemWeightBroadcastConfig
|
||||
from prime_rl.evals.ckpt import CheckpointManager
|
||||
from prime_rl.orchestrator.annotations import stamp_arrival, stamp_batch
|
||||
from prime_rl.orchestrator.clients import AdminClients, InferenceClient
|
||||
from prime_rl.orchestrator.clients import AdminPlane, InferenceClient
|
||||
from prime_rl.orchestrator.concurrency import ConcurrencyController
|
||||
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
|
||||
from prime_rl.orchestrator.envs import EvalEnvs
|
||||
@@ -99,7 +99,7 @@ class Evals:
|
||||
# Assigned in setup(); None-initialized so stop() can tear down a
|
||||
# partially completed setup with plain attribute checks.
|
||||
self.clients: InferenceClient | None = None
|
||||
self.admin_clients: AdminClients | None = None
|
||||
self.admin_plane: AdminPlane | None = None
|
||||
self.dispatcher: Dispatcher | None = None
|
||||
self.inference_metrics: InferenceMetricsCollector | None = None
|
||||
self.periodic_logger: PeriodicLogger | None = None
|
||||
@@ -125,7 +125,7 @@ class Evals:
|
||||
|
||||
get_logger().info(f"Initializing inference pool (base_url={config.eval.client.base_url}, model={config.model})")
|
||||
self.clients = InferenceClient(config.eval.client, model_name=config.model)
|
||||
self.admin_clients = AdminClients(config.eval.client)
|
||||
self.admin_plane = AdminPlane(config.eval.client)
|
||||
|
||||
self.spawn_env_servers()
|
||||
|
||||
@@ -135,7 +135,7 @@ class Evals:
|
||||
get_logger().success(f"Eval environment(s) ready ({', '.join(self.eval_envs.names)})")
|
||||
|
||||
get_logger().info("Waiting for inference pool to be ready")
|
||||
await self.admin_clients.wait_for_ready(config.model)
|
||||
await self.admin_plane.wait_for_ready(config.model)
|
||||
get_logger().success("Inference pool ready")
|
||||
|
||||
self.receiver: WeightReceiver | None = None
|
||||
@@ -148,7 +148,7 @@ class Evals:
|
||||
self.receiver = setup_weight_receiver(
|
||||
config.online.broadcasts_dir,
|
||||
weight_broadcast,
|
||||
admin_clients=self.admin_clients.clients,
|
||||
admin_plane=self.admin_plane,
|
||||
model_name=config.model,
|
||||
)
|
||||
await self.receiver.initialize()
|
||||
@@ -201,7 +201,7 @@ class Evals:
|
||||
# The collector always polls — it feeds the concurrency controller;
|
||||
# metrics fan out to every registered monitor.
|
||||
self.inference_metrics = InferenceMetricsCollector(
|
||||
self.admin_clients.clients,
|
||||
self.admin_plane.clients,
|
||||
on_load=self.concurrency.observe,
|
||||
)
|
||||
# Fail fast when adaptivity has no signal: external API endpoints
|
||||
@@ -212,7 +212,7 @@ class Evals:
|
||||
if not await self.inference_metrics.probe():
|
||||
concurrency = config.eval.concurrency
|
||||
if concurrency.min_inflight != concurrency.max_inflight:
|
||||
urls = ", ".join(str(client.base_url) for client in self.admin_clients.clients)
|
||||
urls = ", ".join(str(client.base_url) for client in self.admin_plane.clients)
|
||||
raise ValueError(
|
||||
f"No engine metrics at {urls} - adaptive concurrency has no load signal. "
|
||||
"The endpoint does not expose vLLM /metrics (e.g. an external inference API); "
|
||||
@@ -579,8 +579,8 @@ class Evals:
|
||||
await self.dispatcher.stop()
|
||||
if self.clients is not None:
|
||||
await self.clients.aclose()
|
||||
if self.admin_clients is not None:
|
||||
await self.admin_clients.aclose()
|
||||
if self.admin_plane is not None:
|
||||
await self.admin_plane.aclose()
|
||||
cleanup_processes(self.env_server_procs)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,431 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
import httpx
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from prime_rl.configs.shared import ClientConfig
|
||||
from prime_rl.orchestrator.clients import (
|
||||
ADMIN_TIMEOUT_S,
|
||||
UPDATE_WEIGHTS_TIMEOUT_S,
|
||||
AdminPlane,
|
||||
_admin_post,
|
||||
check_health,
|
||||
maybe_check_has_model,
|
||||
setup_admin_clients,
|
||||
)
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
class DynamoWorker(BaseModel):
|
||||
admin_base_url: str
|
||||
instance_id: int = Field(ge=0, strict=True)
|
||||
|
||||
|
||||
class DynamoSnapshot(BaseModel):
|
||||
protocol_version: Literal[1]
|
||||
workers: tuple[dict[str, object], ...]
|
||||
|
||||
|
||||
class DynamoDiscoveryPending(RuntimeError):
|
||||
"""The discovery endpoint is healthy but has not published a complete worker set."""
|
||||
|
||||
|
||||
def parse_dynamo_worker(
|
||||
payload: object,
|
||||
model_name: str,
|
||||
*,
|
||||
expected_admin_host: str | None = None,
|
||||
) -> DynamoWorker:
|
||||
snapshot = DynamoSnapshot.model_validate(payload)
|
||||
matching_workers: list[DynamoWorker] = []
|
||||
for raw_worker in snapshot.workers:
|
||||
if raw_worker.get("model") != model_name:
|
||||
continue
|
||||
if raw_worker.get("error") is not None:
|
||||
raise DynamoDiscoveryPending("Dynamo worker is not ready")
|
||||
if raw_worker.get("admin_base_url") is None:
|
||||
raise DynamoDiscoveryPending("Dynamo worker is missing admin_base_url")
|
||||
if type(raw_worker.get("world_size")) is not int or raw_worker["world_size"] != 1:
|
||||
raise ValueError("Dynamo RL currently supports exactly one inference rank")
|
||||
worker = DynamoWorker.model_validate(raw_worker)
|
||||
try:
|
||||
admin_url = httpx.URL(worker.admin_base_url)
|
||||
except httpx.InvalidURL as error:
|
||||
raise ValueError("admin_base_url must be a valid URL") from error
|
||||
if (
|
||||
admin_url.scheme not in {"http", "https"}
|
||||
or not admin_url.host
|
||||
or (admin_url.port is not None and not 1 <= admin_url.port <= 65535)
|
||||
or admin_url.userinfo
|
||||
or admin_url.query
|
||||
or admin_url.fragment
|
||||
or admin_url.path != "/"
|
||||
):
|
||||
raise ValueError("admin_base_url must be an http(s) origin")
|
||||
if expected_admin_host is not None and admin_url.host != expected_admin_host:
|
||||
raise ValueError(
|
||||
f"Dynamo worker admin host {admin_url.host!r} does not match discovery host {expected_admin_host!r}"
|
||||
)
|
||||
matching_workers.append(worker)
|
||||
|
||||
if not matching_workers:
|
||||
raise DynamoDiscoveryPending(f"Dynamo returned no bound workers for model {model_name!r}")
|
||||
if len(matching_workers) != 1:
|
||||
raise ValueError("Dynamo RL currently supports exactly one inference worker")
|
||||
return matching_workers[0]
|
||||
|
||||
|
||||
def topology_fingerprint(worker: DynamoWorker) -> tuple[int, str]:
|
||||
return worker.instance_id, str(httpx.URL(worker.admin_base_url))
|
||||
|
||||
|
||||
def _discovery_headers(client_config: ClientConfig) -> dict[str, str]:
|
||||
env_headers = {
|
||||
name: value
|
||||
for name, env_name in client_config.headers_from_env.items()
|
||||
if (value := os.getenv(env_name)) is not None
|
||||
}
|
||||
headers = {**client_config.headers, **env_headers}
|
||||
api_key = os.getenv(client_config.api_key_var)
|
||||
if api_key and api_key != "EMPTY":
|
||||
headers = {name: value for name, value in headers.items() if name.lower() != "authorization"}
|
||||
headers["Authorization"] = f"Bearer {api_key}"
|
||||
return headers
|
||||
|
||||
|
||||
def resolve_dynamo_discovery_url(client_config: ClientConfig) -> str:
|
||||
dynamo = client_config.dynamo
|
||||
if dynamo is None or not dynamo.enabled:
|
||||
raise ValueError("Dynamo discovery is not enabled")
|
||||
if dynamo.discovery_url is not None:
|
||||
return dynamo.discovery_url
|
||||
|
||||
try:
|
||||
base_url = httpx.URL(client_config.base_url)
|
||||
except httpx.InvalidURL as error:
|
||||
raise ValueError("Set dynamo.discovery_url when client.base_url is not a valid URL") from error
|
||||
if base_url.port is None or base_url.port == 65535:
|
||||
raise ValueError("Set dynamo.discovery_url when client.base_url has no incrementable port")
|
||||
return str(base_url.copy_with(port=base_url.port + 1, path="", query=None, fragment=None, userinfo=b""))
|
||||
|
||||
|
||||
async def discover_dynamo_worker(
|
||||
discovery_url: str,
|
||||
model_name: str,
|
||||
*,
|
||||
headers: dict[str, str],
|
||||
timeout: float,
|
||||
) -> DynamoWorker:
|
||||
try:
|
||||
base_url = httpx.URL(discovery_url)
|
||||
except httpx.InvalidURL as error:
|
||||
raise ValueError("dynamo.discovery_url must be a valid URL") from error
|
||||
if (
|
||||
base_url.scheme not in {"http", "https"}
|
||||
or not base_url.host
|
||||
or (base_url.port is not None and not 1 <= base_url.port <= 65535)
|
||||
or base_url.userinfo
|
||||
or base_url.query
|
||||
or base_url.fragment
|
||||
):
|
||||
raise ValueError("dynamo.discovery_url must be an http(s) URL without credentials, query, or fragment")
|
||||
base_path = base_url.path.rstrip("/")
|
||||
if base_path.endswith("/v1"):
|
||||
base_path = base_path.removesuffix("/v1")
|
||||
url = base_url.copy_with(path=f"{base_path}/v1/rl/workers")
|
||||
try:
|
||||
async with asyncio.timeout(timeout):
|
||||
async with httpx.AsyncClient(headers=headers, timeout=timeout, trust_env=False) as client:
|
||||
response = await client.get(url)
|
||||
response.raise_for_status()
|
||||
payload = response.json()
|
||||
except TimeoutError as error:
|
||||
raise TimeoutError(f"Dynamo discovery request exceeded {timeout} seconds") from error
|
||||
return parse_dynamo_worker(payload, model_name, expected_admin_host=base_url.host)
|
||||
|
||||
|
||||
class DynamoAdminPlane(AdminPlane):
|
||||
"""Admin plane pinned to two identical snapshots from a trusted Dynamo discovery endpoint."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
client_config: ClientConfig,
|
||||
model_name: str,
|
||||
*,
|
||||
poll_interval: float = 1.0,
|
||||
) -> None:
|
||||
if client_config.dynamo is None or not client_config.dynamo.enabled:
|
||||
raise ValueError("Dynamo discovery configuration is required")
|
||||
self._discovery_url = resolve_dynamo_discovery_url(client_config)
|
||||
self._client_config = client_config
|
||||
self._model_name = model_name
|
||||
self._poll_interval = poll_interval
|
||||
self._timeout = client_config.wait_for_ready_timeout
|
||||
self._headers = _discovery_headers(client_config)
|
||||
self._frontend_clients = setup_admin_clients(client_config.model_copy(update={"admin_base_url": None}))
|
||||
self.clients: list[httpx.AsyncClient] = []
|
||||
self._fingerprint: tuple[int, str] | None = None
|
||||
self._nccl_initialization_state: Literal["uninitialized", "initializing", "ready", "terminal"] = "uninitialized"
|
||||
self._mutation_lock = asyncio.Lock()
|
||||
|
||||
def _require_uninitialized_nccl(self) -> None:
|
||||
if self._nccl_initialization_state != "uninitialized":
|
||||
raise RuntimeError(
|
||||
"Dynamo NCCL can only be initialized once; restart the inference workers before retrying"
|
||||
)
|
||||
|
||||
def _require_ready_nccl(self) -> None:
|
||||
if self._nccl_initialization_state != "ready":
|
||||
raise RuntimeError("Dynamo weight updates require a ready NCCL initialization")
|
||||
|
||||
def _terminalize_nccl(self) -> None:
|
||||
self._nccl_initialization_state = "terminal"
|
||||
|
||||
async def _discover(self) -> DynamoWorker:
|
||||
return await discover_dynamo_worker(
|
||||
self._discovery_url,
|
||||
self._model_name,
|
||||
headers=self._headers,
|
||||
timeout=min(30.0, max(1.0, float(self._timeout))),
|
||||
)
|
||||
|
||||
async def wait_for_ready(self, model_name: str) -> None:
|
||||
if model_name != self._model_name:
|
||||
raise ValueError(f"Dynamo admin plane was configured for {self._model_name!r}, not {model_name!r}")
|
||||
deadline = time.monotonic() + self._timeout
|
||||
try:
|
||||
async with asyncio.timeout(self._remaining(deadline)):
|
||||
await check_health(self._frontend_clients, timeout=self._remaining(deadline))
|
||||
await maybe_check_has_model(
|
||||
self._frontend_clients,
|
||||
model_name,
|
||||
skip_model_check=self._client_config.skip_model_check,
|
||||
)
|
||||
except TimeoutError as error:
|
||||
raise TimeoutError(f"Dynamo frontend readiness exceeded {self._timeout} seconds") from error
|
||||
|
||||
previous_fingerprint: tuple[int, str] | None = None
|
||||
last_error: Exception | None = None
|
||||
while (remaining := deadline - time.monotonic()) > 0:
|
||||
try:
|
||||
async with asyncio.timeout(remaining):
|
||||
worker = await self._discover()
|
||||
fingerprint = topology_fingerprint(worker)
|
||||
if fingerprint == previous_fingerprint:
|
||||
candidate_client = self._make_worker_client(worker)
|
||||
try:
|
||||
remaining = self._remaining(deadline)
|
||||
async with asyncio.timeout(remaining):
|
||||
await check_health([candidate_client], timeout=remaining, quiet=True)
|
||||
except BaseException:
|
||||
await candidate_client.aclose()
|
||||
raise
|
||||
self._bind(worker, fingerprint, candidate_client)
|
||||
return
|
||||
previous_fingerprint = fingerprint
|
||||
except httpx.HTTPStatusError as error:
|
||||
if error.response.status_code < 500:
|
||||
raise
|
||||
previous_fingerprint = None
|
||||
last_error = error
|
||||
except (DynamoDiscoveryPending, httpx.TransportError, TimeoutError) as error:
|
||||
previous_fingerprint = None
|
||||
last_error = error
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining > 0:
|
||||
await asyncio.sleep(min(self._poll_interval, remaining))
|
||||
raise TimeoutError("Dynamo workers did not become ready before the discovery timeout") from last_error
|
||||
|
||||
@staticmethod
|
||||
def _remaining(deadline: float) -> float:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("Dynamo readiness deadline expired")
|
||||
return remaining
|
||||
|
||||
def _make_worker_client(self, worker: DynamoWorker) -> httpx.AsyncClient:
|
||||
worker_timeout = min(30.0, max(1.0, float(self._timeout)))
|
||||
return httpx.AsyncClient(
|
||||
base_url=worker.admin_base_url,
|
||||
headers=self._headers,
|
||||
limits=httpx.Limits(max_connections=4, max_keepalive_connections=1),
|
||||
timeout=httpx.Timeout(worker_timeout),
|
||||
trust_env=False,
|
||||
)
|
||||
|
||||
def _bind(
|
||||
self,
|
||||
worker: DynamoWorker,
|
||||
fingerprint: tuple[int, str],
|
||||
client: httpx.AsyncClient | None = None,
|
||||
) -> None:
|
||||
self._fingerprint = fingerprint
|
||||
self.clients = [client if client is not None else self._make_worker_client(worker)]
|
||||
|
||||
async def ensure_topology_current(self) -> None:
|
||||
if self._nccl_initialization_state == "terminal":
|
||||
raise RuntimeError("Dynamo administration is in a terminal state; restart is required")
|
||||
if self._fingerprint is None:
|
||||
raise RuntimeError("Dynamo topology has not been pinned")
|
||||
previous_changed_fingerprint: tuple[int, str] | None = None
|
||||
last_error: Exception | None = None
|
||||
deadline = time.monotonic() + self._timeout
|
||||
for attempt in range(3):
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
break
|
||||
try:
|
||||
async with asyncio.timeout(remaining):
|
||||
worker = await self._discover()
|
||||
fingerprint = topology_fingerprint(worker)
|
||||
if fingerprint == self._fingerprint:
|
||||
return
|
||||
if fingerprint == previous_changed_fingerprint:
|
||||
raise RuntimeError("Dynamo worker topology changed after initialization")
|
||||
previous_changed_fingerprint = fingerprint
|
||||
last_error = None
|
||||
except httpx.HTTPStatusError as error:
|
||||
if error.response.status_code < 500:
|
||||
raise
|
||||
last_error = error
|
||||
except (DynamoDiscoveryPending, httpx.TransportError, TimeoutError) as error:
|
||||
last_error = error
|
||||
if attempt < 2:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
break
|
||||
await asyncio.sleep(min(self._poll_interval, remaining))
|
||||
if last_error is not None:
|
||||
raise RuntimeError("Could not verify the pinned Dynamo topology") from last_error
|
||||
raise RuntimeError("Dynamo topology changed but could not be confirmed")
|
||||
|
||||
async def _collective_rpc(
|
||||
self,
|
||||
client: httpx.AsyncClient,
|
||||
*,
|
||||
method: Literal["init_broadcaster", "update_weights_from_path"],
|
||||
timeout: int | float,
|
||||
args: list[object],
|
||||
) -> None:
|
||||
operation_timeout = max(1.0, float(timeout))
|
||||
async with asyncio.timeout(operation_timeout + 15.0):
|
||||
response = await client.post(
|
||||
"/collective_rpc",
|
||||
timeout=httpx.Timeout(connect=10.0, read=operation_timeout, write=10.0, pool=10.0),
|
||||
json={"method": method, "timeout": operation_timeout, "args": args, "kwargs": {}},
|
||||
)
|
||||
response.raise_for_status()
|
||||
payload = response.json()
|
||||
if payload != {"results": [None]}:
|
||||
raise ValueError("Dynamo worker returned an invalid collective RPC response")
|
||||
|
||||
async def update_weights(
|
||||
self,
|
||||
weight_dir: Path | None,
|
||||
*,
|
||||
transport: Literal["filesystem", "nccl", "nixl"],
|
||||
step: int = 0,
|
||||
on_paused: Callable[[], None] | None = None,
|
||||
) -> None:
|
||||
if transport != "nccl":
|
||||
async with self._mutation_lock:
|
||||
await self.ensure_topology_current()
|
||||
await super().update_weights(
|
||||
weight_dir,
|
||||
transport=transport,
|
||||
step=step,
|
||||
on_paused=on_paused,
|
||||
)
|
||||
return
|
||||
if weight_dir is None:
|
||||
raise ValueError(f"{transport.upper()} weight updates require a broadcast directory")
|
||||
self._require_ready_nccl()
|
||||
async with self._mutation_lock:
|
||||
await self.ensure_topology_current()
|
||||
self._nccl_initialization_state = "terminal"
|
||||
|
||||
try:
|
||||
await _admin_post(self.clients[0], "/pause", params={"mode": "keep", "clear_cache": "false"})
|
||||
except BaseException as failure:
|
||||
raise RuntimeError("Dynamo pause failed; worker state is unknown and restart is required") from failure
|
||||
|
||||
if on_paused is not None:
|
||||
try:
|
||||
on_paused()
|
||||
except BaseException as error:
|
||||
raise RuntimeError(
|
||||
"Dynamo pause callback failed; engines remain paused and restart is required"
|
||||
) from error
|
||||
try:
|
||||
await self._collective_rpc(
|
||||
self.clients[0],
|
||||
method="update_weights_from_path",
|
||||
timeout=UPDATE_WEIGHTS_TIMEOUT_S,
|
||||
args=[weight_dir.as_posix()],
|
||||
)
|
||||
except BaseException as failure:
|
||||
self._terminalize_nccl()
|
||||
raise RuntimeError(
|
||||
f"Dynamo {transport} update failed; engines remain paused and restart is required"
|
||||
) from failure
|
||||
|
||||
try:
|
||||
await _admin_post(self.clients[0], "/resume", timeout_s=ADMIN_TIMEOUT_S)
|
||||
except BaseException as failure:
|
||||
self._terminalize_nccl()
|
||||
raise RuntimeError("Dynamo resume failed; worker state is unknown and restart is required") from failure
|
||||
self._nccl_initialization_state = "ready"
|
||||
get_logger().info(f"Applied NCCL weights for policy v{step} to the Dynamo worker")
|
||||
|
||||
async def initialize_nccl(
|
||||
self,
|
||||
*,
|
||||
host: str,
|
||||
port: int,
|
||||
timeout: int,
|
||||
inference_world_size: int,
|
||||
quantize_in_weight_transfer: bool = False,
|
||||
) -> None:
|
||||
async with self._mutation_lock:
|
||||
self._require_uninitialized_nccl()
|
||||
if inference_world_size != 1:
|
||||
raise ValueError("Dynamo RL currently supports exactly one inference rank")
|
||||
self._nccl_initialization_state = "initializing"
|
||||
try:
|
||||
await self.ensure_topology_current()
|
||||
get_logger().info("Initializing Dynamo NCCL broadcast for one inference rank")
|
||||
await self._collective_rpc(
|
||||
self.clients[0],
|
||||
method="init_broadcaster",
|
||||
timeout=timeout,
|
||||
args=[
|
||||
host,
|
||||
port,
|
||||
0,
|
||||
1,
|
||||
timeout,
|
||||
quantize_in_weight_transfer,
|
||||
"default",
|
||||
],
|
||||
)
|
||||
except asyncio.CancelledError:
|
||||
self._terminalize_nccl()
|
||||
raise
|
||||
except BaseException as error:
|
||||
self._terminalize_nccl()
|
||||
raise RuntimeError(
|
||||
"Dynamo NCCL initialization failed; inference workers must restart before retrying"
|
||||
) from error
|
||||
|
||||
self._nccl_initialization_state = "ready"
|
||||
|
||||
async def aclose(self) -> None:
|
||||
unique_clients = {id(client): client for client in [*self._frontend_clients, *self.clients]}
|
||||
await asyncio.gather(*(client.aclose() for client in unique_clients.values()))
|
||||
@@ -9,6 +9,9 @@ def apply_shared_vllm_patches():
|
||||
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
|
||||
|
||||
patch_gpt_oss_weight_loading()
|
||||
_patch_lora_key_prefix()
|
||||
_patch_qwen35_moe_lora_format()
|
||||
monkey_patch_nano_v3_reasoning_parser()
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
from collections.abc import Iterable
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
def patch_gpt_oss_weight_loading() -> None:
|
||||
"""Route GPT-OSS BF16 expert and sink weights through vLLM loaders.
|
||||
|
||||
Remove this patch when the pinned vLLM version uses weight loaders for these
|
||||
prepared tensors in ``GptOssModel._load_weights_other``.
|
||||
"""
|
||||
from vllm.model_executor.layers.fused_moe.routed_experts import RoutedExperts
|
||||
from vllm.model_executor.model_loader.weight_utils import (
|
||||
default_weight_loader,
|
||||
maybe_remap_moe_expert_param_name,
|
||||
)
|
||||
from vllm.model_executor.models import gpt_oss
|
||||
|
||||
original_load_weights = gpt_oss.GptOssModel._load_weights_other
|
||||
if getattr(original_load_weights, "_prime_rl_uses_weight_loaders", False):
|
||||
return
|
||||
|
||||
original_expert_weight_loader = RoutedExperts.weight_loader
|
||||
|
||||
def expert_weight_loader(
|
||||
self,
|
||||
param,
|
||||
loaded_weight,
|
||||
weight_name,
|
||||
shard_id,
|
||||
expert_id,
|
||||
return_success=False,
|
||||
):
|
||||
if expert_id is None:
|
||||
if shard_id is not None:
|
||||
raise ValueError("A combined expert tensor must already be sharded")
|
||||
if param.shape != loaded_weight.shape:
|
||||
raise ValueError(
|
||||
f"Combined expert tensor shape {tuple(loaded_weight.shape)} does not match "
|
||||
f"parameter shape {tuple(param.shape)}"
|
||||
)
|
||||
param.copy_(loaded_weight)
|
||||
return True if return_success else None
|
||||
return original_expert_weight_loader(
|
||||
self,
|
||||
param,
|
||||
loaded_weight,
|
||||
weight_name,
|
||||
shard_id,
|
||||
expert_id,
|
||||
return_success,
|
||||
)
|
||||
|
||||
RoutedExperts.weight_loader = expert_weight_loader
|
||||
|
||||
def load_weights(
|
||||
self,
|
||||
ep_rank_end: int,
|
||||
ep_rank_start: int,
|
||||
heads_per_rank: int,
|
||||
head_start: int,
|
||||
weights: Iterable[tuple[str, torch.Tensor]],
|
||||
stacked_params_mapping: list[tuple[str, ...]],
|
||||
) -> set[str]:
|
||||
params = dict(self.named_parameters())
|
||||
loaded_params: set[str] = set()
|
||||
use_ep = self.parallel_config.enable_expert_parallel
|
||||
tp_size, tp_rank = gpt_oss.FusedMoEParallelConfig.flatten_tp_across_dp_and_pcp(
|
||||
tp_size=gpt_oss.get_tensor_model_parallel_world_size(),
|
||||
dp_size=gpt_oss.get_dp_group().world_size,
|
||||
dp_rank=gpt_oss.get_dp_group().rank_in_group,
|
||||
pcp_size=gpt_oss.get_pcp_group().world_size,
|
||||
pcp_rank=gpt_oss.get_pcp_group().rank_in_group,
|
||||
)
|
||||
intermediate_size = self.config.intermediate_size
|
||||
per_rank_intermediate_size = gpt_oss.cdiv(intermediate_size, tp_size)
|
||||
tp_rank_start = tp_rank * per_rank_intermediate_size
|
||||
tp_rank_end = min((tp_rank + 1) * per_rank_intermediate_size, intermediate_size)
|
||||
|
||||
def remaining_weights():
|
||||
for name, weight in weights:
|
||||
if not (
|
||||
name.endswith((".w13_weight", ".w2_weight", ".w13_bias", ".w2_bias")) or name.endswith(".sinks")
|
||||
):
|
||||
yield name, weight
|
||||
continue
|
||||
|
||||
name = maybe_remap_moe_expert_param_name(name, params)
|
||||
if gpt_oss.is_pp_missing_parameter(name, self):
|
||||
continue
|
||||
|
||||
param = params[name]
|
||||
if name.endswith(".w13_weight"):
|
||||
if use_ep:
|
||||
weight = weight[ep_rank_start:ep_rank_end]
|
||||
else:
|
||||
weight = weight[:, :, 2 * tp_rank_start : 2 * tp_rank_end]
|
||||
weight = weight.permute(0, 2, 1).contiguous()
|
||||
elif name.endswith(".w2_weight"):
|
||||
if use_ep:
|
||||
weight = weight[ep_rank_start:ep_rank_end]
|
||||
else:
|
||||
weight = weight[:, tp_rank_start:tp_rank_end]
|
||||
weight = weight.permute(0, 2, 1).contiguous()
|
||||
elif name.endswith(".w13_bias"):
|
||||
if use_ep:
|
||||
weight = weight[ep_rank_start:ep_rank_end]
|
||||
else:
|
||||
weight = weight[:, 2 * tp_rank_start : 2 * tp_rank_end]
|
||||
elif name.endswith(".w2_bias"):
|
||||
if use_ep:
|
||||
weight = weight[ep_rank_start:ep_rank_end]
|
||||
elif tp_rank != 0:
|
||||
weight = weight.zero_()
|
||||
else:
|
||||
weight = weight.narrow(0, head_start, heads_per_rank)
|
||||
weight_loader = getattr(param, "weight_loader", default_weight_loader)
|
||||
weight_loader(param, weight)
|
||||
loaded_params.add(name)
|
||||
continue
|
||||
|
||||
param.weight_loader(
|
||||
param,
|
||||
weight,
|
||||
weight_name=name,
|
||||
shard_id=None,
|
||||
expert_id=None,
|
||||
)
|
||||
loaded_params.add(name)
|
||||
|
||||
loaded_params.update(
|
||||
original_load_weights(
|
||||
self,
|
||||
ep_rank_end,
|
||||
ep_rank_start,
|
||||
heads_per_rank,
|
||||
head_start,
|
||||
remaining_weights(),
|
||||
stacked_params_mapping,
|
||||
)
|
||||
)
|
||||
return loaded_params
|
||||
|
||||
load_weights._prime_rl_uses_weight_loaders = True
|
||||
gpt_oss.GptOssModel._load_weights_other = load_weights
|
||||
+80
-295
@@ -1,331 +1,116 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import atexit
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Coroutine
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import httpx
|
||||
import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
import verifiers.v1 as vf
|
||||
from prime_cli.core.config import Config as PrimeConfig
|
||||
from verifiers.v1.utils.platform import build_samples
|
||||
import prime_runs as pr
|
||||
|
||||
from prime_rl.configs.monitors import PrimeMonitorConfig
|
||||
from prime_rl.monitors.base import Kind, Monitor, Subset
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.utils import sanitize
|
||||
|
||||
BASE_URL = "https://api.primeintellect.ai/api/v1/rft"
|
||||
BASE_URL_VAR = "PRIME_API_BASE"
|
||||
API_KEY_VAR = "PRIME_API_KEY"
|
||||
if TYPE_CHECKING:
|
||||
import verifiers.v1 as vf
|
||||
|
||||
SAMPLE_SCHEMA = pa.schema(
|
||||
[
|
||||
("run_id", pa.string()),
|
||||
("step", pa.int64()),
|
||||
("tag", pa.string()),
|
||||
("problem_id", pa.int64()),
|
||||
("sample_id", pa.int64()),
|
||||
("prompt", pa.string()),
|
||||
("completion", pa.string()),
|
||||
("trajectory", pa.string()),
|
||||
("answer", pa.string()),
|
||||
("env_name", pa.string()),
|
||||
("task", pa.string()),
|
||||
("info", pa.string()),
|
||||
("reward", pa.float64()),
|
||||
("advantage", pa.float64()),
|
||||
("metrics", pa.string()),
|
||||
("timing", pa.string()),
|
||||
("num_input_tokens", pa.int64()),
|
||||
("num_output_tokens", pa.int64()),
|
||||
("created_at", pa.timestamp("us", tz="UTC")),
|
||||
]
|
||||
)
|
||||
BASE_URL_VAR = "PRIME_API_BASE"
|
||||
# How long finish() and the SDK's atexit crash hook let queued uploads drain. The SDK
|
||||
# default (300 s) is sized for eval sample batches; a crashed training process should
|
||||
# not linger that long, and a clean finish rarely has more than the last step queued.
|
||||
FINISH_TIMEOUT = 60.0
|
||||
|
||||
|
||||
def _base_url() -> str | None:
|
||||
"""$PRIME_API_BASE historically points at the RFT API root (``.../api/v1/rft``);
|
||||
the SDK takes the platform base URL. Unset means the SDK resolves it."""
|
||||
base = os.getenv(BASE_URL_VAR)
|
||||
return base.rstrip("/").removesuffix("/rft") if base else None
|
||||
|
||||
|
||||
class PrimeMonitor(Monitor):
|
||||
"""Logs metrics and episodes to the Prime platform.
|
||||
"""Logs metrics and episodes to the Prime platform through ``prime_runs``.
|
||||
|
||||
Uploads are fire-and-forget tasks on the caller's event loop — the prime
|
||||
monitor only runs in the orchestrator, whose call sites are all async. The
|
||||
platform calls and the episode serialization run in worker threads via
|
||||
``asyncio.to_thread``, so they never stall the loop.
|
||||
The run handle owns what ``TrainRun`` used to do by hand: the RFT
|
||||
lifecycle (register or attach, finalize), the per-step metrics POSTs, the
|
||||
every-10th-step Parquet sample uploads (presign -> PUT -> confirm), and
|
||||
the terminal status — a process that exits without finalizing is reported
|
||||
crashed by the SDK's atexit hook, replacing the old ``_mark_failed`` one.
|
||||
|
||||
``init``/``finish`` do network I/O and run in worker threads; the log
|
||||
calls are queue puts onto the SDK's uploader thread, which owns retries
|
||||
and backpressure, so they never stall the loop.
|
||||
"""
|
||||
|
||||
config: PrimeMonitorConfig
|
||||
run: pr.Run
|
||||
|
||||
async def init(self, config: BaseConfig | None = None) -> None:
|
||||
api_key = os.getenv(API_KEY_VAR) or PrimeConfig().api_key
|
||||
if not api_key:
|
||||
raise RuntimeError(f"API key not found - set {API_KEY_VAR} or run `prime login`")
|
||||
self.run = TrainRun(api_key)
|
||||
init_kwargs: dict[str, Any]
|
||||
if run_id := os.getenv("RUN_ID"):
|
||||
# A managed launch pre-created the platform run and injected its id -
|
||||
# attach instead of registering a duplicate. The backend owns the run's
|
||||
# failure marking then; finalize still marks it completed on clean exit.
|
||||
self.run.id = run_id
|
||||
self.logger.info(f"Logging metrics and episodes to platform run {run_id} (attached via $RUN_ID)")
|
||||
return
|
||||
run_fields: dict[str, Any] = {}
|
||||
if config is not None:
|
||||
run_fields = dict(
|
||||
base_model=config.model.name,
|
||||
max_steps=config.max_steps or 0,
|
||||
batch_size=config.batch_size,
|
||||
rollouts_per_example=config.group_size,
|
||||
seq_len=config.seq_len,
|
||||
# failure marking then; a clean finish() still marks it completed.
|
||||
init_kwargs = {"id": run_id}
|
||||
elif config is not None:
|
||||
init_kwargs = dict(
|
||||
name=self.config.name,
|
||||
model=config.model.name,
|
||||
environments=[env.env_id for env in config.train.source],
|
||||
run_config=config.model_dump(exclude_none=True, mode="json"),
|
||||
wandb_project=config.monitors.wandb.project if config.monitors.wandb else None,
|
||||
training=pr.TrainingSpec(
|
||||
max_steps=config.max_steps or 0,
|
||||
batch_size=config.batch_size,
|
||||
rollouts_per_example=config.group_size,
|
||||
seq_len=config.seq_len,
|
||||
wandb_project=config.monitors.wandb.project if config.monitors.wandb else None,
|
||||
),
|
||||
config=config.model_dump(exclude_none=True, mode="json"),
|
||||
)
|
||||
await self.run.create(name=self.config.name, **run_fields)
|
||||
else:
|
||||
# The RFT API requires a base model; "unknown" is what the
|
||||
# pre-SDK register sent for a config-less init.
|
||||
init_kwargs = {"name": self.config.name, "model": "unknown"}
|
||||
|
||||
# A configured monitor must work (see monitors.setup), so the default is
|
||||
# mode="online": a missing key or a team outside the external-runs allowlist
|
||||
# raises here instead of training silently untracked. $PRIME_RUNS_MODE=disabled
|
||||
# stays the explicit opt-out.
|
||||
self.run = await asyncio.to_thread(
|
||||
pr.init,
|
||||
kind="train",
|
||||
mode=os.getenv(pr.MODE_ENV) or "online",
|
||||
base_url=_base_url(),
|
||||
finish_timeout=FINISH_TIMEOUT,
|
||||
**init_kwargs,
|
||||
)
|
||||
if self.run.url:
|
||||
attached = " (attached via $RUN_ID)" if self.run.attached else ""
|
||||
self.logger.info(f"Logging metrics and episodes to platform run {self.run.id} ({self.run.url}){attached}")
|
||||
else:
|
||||
self.logger.info(f"Platform run disabled ({pr.MODE_ENV}=disabled)")
|
||||
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
|
||||
# The SDK also drops non-finite values, but silently; sanitize first so
|
||||
# the dropped paths are named in the log.
|
||||
metrics, dropped = sanitize(metrics)
|
||||
if dropped:
|
||||
self.logger.warning(f"Dropping {len(dropped)} non-finite metric value(s): {', '.join(dropped[:5])}")
|
||||
# every monitor stamps its own wall time; without it, step=None rows
|
||||
# (e.g. inference metrics) reach the platform with no time anchor
|
||||
metrics["_timestamp"] = time.time()
|
||||
self.run.submit("metrics upload", self.run.log_metrics(metrics))
|
||||
# A queue put that can block briefly under backpressure - off the loop. The SDK
|
||||
# stamps `_timestamp` on every row, so step=None rows keep a time anchor.
|
||||
await asyncio.to_thread(self.run.log_metrics, metrics, step=step)
|
||||
|
||||
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
|
||||
"""Upload one platform sample per episode via the presigned-URL Parquet flow.
|
||||
Only the trained cohort ships to the platform."""
|
||||
# Upload every 10th step, unsampled - the pre-refactor cadence - to not
|
||||
# overwhelm the platform's ingestion. TODO: Lift once we integrate the
|
||||
# prime traces SDK.
|
||||
if kind != "train" or subset != "effective" or not episodes or step % 10 != 0:
|
||||
"""Only the trained cohort ships to the platform. The upload cadence
|
||||
(every 10th step) and the Parquet encoding live in the SDK's training
|
||||
samples sink, which reads each episode's dispatch step off ``run.work``
|
||||
- the ``TrainRunInfo`` the dispatcher stamps at emit time."""
|
||||
if kind != "train" or subset != "effective" or not episodes:
|
||||
return
|
||||
|
||||
async def upload() -> None:
|
||||
# Serialization dumps every episode's full model - heavy pure-Python work
|
||||
# that would stall the event loop (and with it dispatch) if run inline.
|
||||
parquet_bytes = await asyncio.to_thread(episodes_to_parquet_bytes, episodes, self.run.id, step)
|
||||
if parquet_bytes is not None:
|
||||
await self.run.upload_samples(parquet_bytes, step)
|
||||
|
||||
self.run.submit(f"episodes upload at step {step}", upload())
|
||||
# A queue put that can block briefly under backpressure - off the loop.
|
||||
await asyncio.to_thread(self.run.log_episodes, episodes)
|
||||
|
||||
async def finalize(self) -> None:
|
||||
await self.run.finalize()
|
||||
|
||||
|
||||
class TrainRun:
|
||||
"""A training run on the Prime platform's RFT API.
|
||||
|
||||
Owns the HTTP client and the run lifecycle (create, log, finalize) — the
|
||||
natural seam to be subsumed by the train SDK, and it mirrors ``wandb.Run``'s
|
||||
exit behavior: a created run that is never finalized is marked failed at
|
||||
process exit via an atexit hook that ``finalize`` disarms. Fully async,
|
||||
except the atexit hook itself — at interpreter shutdown there is no event
|
||||
loop, so it sends one synchronous request.
|
||||
"""
|
||||
|
||||
def __init__(self, api_key: str):
|
||||
self.id: str | None = None
|
||||
self.logger = get_logger()
|
||||
self._tasks: set[asyncio.Task] = set()
|
||||
self.base_url = (os.getenv(BASE_URL_VAR) or BASE_URL).rstrip("/")
|
||||
self.headers = {
|
||||
"Authorization": f"Bearer {api_key}",
|
||||
"x-api-key": api_key,
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
self.client = httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
headers=self.headers,
|
||||
timeout=30,
|
||||
transport=httpx.AsyncHTTPTransport(retries=3),
|
||||
)
|
||||
|
||||
def submit(self, what: str, request: Coroutine[Any, Any, None]) -> None:
|
||||
"""Run a request as a fire-and-forget task; a failure only warns. The task set
|
||||
keeps strong references - the loop alone won't."""
|
||||
|
||||
async def guarded() -> None:
|
||||
try:
|
||||
await request
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Failed {what}: {type(e).__name__}: {e}")
|
||||
|
||||
task = asyncio.get_running_loop().create_task(guarded())
|
||||
self._tasks.add(task)
|
||||
task.add_done_callback(self._tasks.discard)
|
||||
|
||||
async def create(
|
||||
self,
|
||||
name: str | None = None,
|
||||
team_id: str | None = None,
|
||||
base_model: str = "unknown",
|
||||
max_steps: int = 0,
|
||||
batch_size: int | None = None,
|
||||
rollouts_per_example: int | None = None,
|
||||
seq_len: int | None = None,
|
||||
environments: list[str] | None = None,
|
||||
run_config: dict[str, Any] | None = None,
|
||||
wandb_project: str | None = None,
|
||||
) -> str:
|
||||
"""Register the run with the platform and return its id."""
|
||||
prime_config = PrimeConfig()
|
||||
team_id = team_id or prime_config.team_id
|
||||
|
||||
payload: dict[str, Any] = {"base_model": base_model, "max_steps": max_steps}
|
||||
if batch_size is not None:
|
||||
payload["batch_size"] = batch_size
|
||||
if rollouts_per_example is not None:
|
||||
payload["rollouts_per_example"] = rollouts_per_example
|
||||
if seq_len is not None:
|
||||
payload["seq_len"] = seq_len
|
||||
if environments is not None:
|
||||
payload["environments"] = [{"id": env_id} for env_id in environments]
|
||||
if run_config is not None:
|
||||
payload["run_config"] = run_config
|
||||
if wandb_project is not None:
|
||||
payload["wandb_project"] = wandb_project
|
||||
if name:
|
||||
payload["name"] = name
|
||||
if team_id:
|
||||
payload["team_id"] = team_id
|
||||
|
||||
response = await self.client.post("/external-runs", json=payload)
|
||||
if response.status_code != 201:
|
||||
raise RuntimeError(f"Failed to create platform run (HTTP {response.status_code}): {response.text}")
|
||||
|
||||
self.id = response.json()["run"]["id"]
|
||||
self._owner_pid = os.getpid()
|
||||
atexit.register(self._mark_failed)
|
||||
if prime_config.frontend_url:
|
||||
self.logger.info(
|
||||
f"Logging metrics and episodes to platform run {self.id} ({prime_config.frontend_url.rstrip('/')}/dashboard/training/{self.id})"
|
||||
)
|
||||
else:
|
||||
self.logger.info(f"Logging metrics and episodes to platform run {self.id}")
|
||||
return self.id
|
||||
|
||||
async def log_metrics(self, metrics: dict[str, Any]) -> None:
|
||||
(await self.client.post("/metrics", json={"run_id": self.id, "metrics": metrics})).raise_for_status()
|
||||
|
||||
async def upload_samples(self, parquet_bytes: bytes, step: int) -> None:
|
||||
"""Presigned-URL flow: presign -> R2 PUT -> confirm."""
|
||||
presign = await self.client.post("/samples/presign", json={"run_id": self.id, "step": step})
|
||||
presign.raise_for_status()
|
||||
data = presign.json()["data"]
|
||||
# Bare client - the presigned URL rejects the run client's auth headers.
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
put = await client.put(
|
||||
data["presignedUrl"], content=parquet_bytes, headers={"Content-Type": "application/parquet"}
|
||||
)
|
||||
put.raise_for_status()
|
||||
confirm = await self.client.post(
|
||||
"/samples/confirm", json={"run_id": self.id, "step": step, "s3_key": data["s3Key"]}
|
||||
)
|
||||
confirm.raise_for_status()
|
||||
|
||||
async def finalize(self) -> None:
|
||||
"""Finalize the run as completed."""
|
||||
self.logger.info(f"Finalizing platform run {self.id}")
|
||||
# Drain in-flight uploads so the final step's metrics and episodes land
|
||||
# before the run is marked completed.
|
||||
await asyncio.gather(*self._tasks, return_exceptions=True)
|
||||
try:
|
||||
(await self.client.post("/finalize", json={"run_id": self.id, "summary": {}})).raise_for_status()
|
||||
except httpx.HTTPError as e:
|
||||
self.logger.warning(f"Failed to finalize platform run {self.id}: {e}")
|
||||
await self.set_status(success=True)
|
||||
atexit.unregister(self._mark_failed)
|
||||
|
||||
def _mark_failed(self) -> None:
|
||||
# Forked children inherit the atexit table; only the creating process may
|
||||
# flip the run's status. At interpreter shutdown there is no event loop and
|
||||
# no executor for async DNS, so this path must stay synchronous.
|
||||
if os.getpid() != self._owner_pid:
|
||||
return
|
||||
self.logger.info(f"Marking platform run {self.id} as failed")
|
||||
try:
|
||||
httpx.put(
|
||||
f"{self.base_url}/external-runs/{self.id}/status",
|
||||
headers=self.headers,
|
||||
json={"status": "failed"},
|
||||
timeout=30,
|
||||
).raise_for_status()
|
||||
except httpx.HTTPError as e:
|
||||
self.logger.warning(f"Failed to mark platform run {self.id} as failed: {e}")
|
||||
|
||||
async def set_status(self, success: bool) -> None:
|
||||
"""Mark the run as completed or failed."""
|
||||
status = "completed" if success else "failed"
|
||||
self.logger.info(f"Marking platform run {self.id} as {status}")
|
||||
try:
|
||||
put = await self.client.put(f"/external-runs/{self.id}/status", json={"status": status})
|
||||
put.raise_for_status()
|
||||
except httpx.HTTPError as e:
|
||||
self.logger.warning(f"Failed to mark platform run {self.id} as {status}: {e}")
|
||||
|
||||
|
||||
def episodes_to_parquet_bytes(episodes: list[vf.Episode], run_id: str | None, step: int) -> bytes | None:
|
||||
"""One row per episode. Sample construction is shared with verifiers' eval
|
||||
``--push`` (``build_samples``: complete native episode in ``info.native_wrapper``,
|
||||
flat summary from one trainable trace), so a training episode and an eval sample
|
||||
land on the platform identically; the RFT-only columns (run/step/advantage/
|
||||
problem_id/env_name) are layered on here."""
|
||||
advantages: dict[str, float | None] = {}
|
||||
env_names: dict[str, str] = {}
|
||||
for episode in episodes:
|
||||
summary_trace = next((trace for trace in episode.traces if trace.agent.trainable), episode.traces[0])
|
||||
advantages[episode.id] = summary_trace.info.get("advantage")
|
||||
env_names[episode.id] = episode.env.id
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
rows = []
|
||||
for sample_id, sample in enumerate(build_samples(episodes)):
|
||||
trajectory = sample["trajectory"]
|
||||
if not trajectory: # no branches (e.g. an episode that errored before any message)
|
||||
continue
|
||||
advantage = advantages.get(sample["episode_id"])
|
||||
trajectory = [{**branch, "advantage": advantage} for branch in trajectory]
|
||||
|
||||
try:
|
||||
problem_id = int(sample["example_id"]) if sample["example_id"] is not None else sample_id
|
||||
except (TypeError, ValueError):
|
||||
problem_id = sample_id
|
||||
|
||||
rows.append(
|
||||
{
|
||||
"run_id": run_id,
|
||||
"step": step,
|
||||
"tag": "",
|
||||
"problem_id": problem_id,
|
||||
"sample_id": sample_id,
|
||||
"prompt": "",
|
||||
"completion": json.dumps(sample["completion"]),
|
||||
"trajectory": json.dumps(trajectory),
|
||||
"answer": "",
|
||||
"env_name": env_names.get(sample["episode_id"], ""),
|
||||
"task": json.dumps(sample["task"]),
|
||||
"info": json.dumps(sample["info"]),
|
||||
"reward": sample["reward"],
|
||||
"advantage": advantage,
|
||||
"metrics": json.dumps(sample["metrics"]),
|
||||
"timing": json.dumps(sample["timing"]),
|
||||
"num_input_tokens": trajectory[-1]["num_input_tokens"],
|
||||
"num_output_tokens": trajectory[-1]["num_output_tokens"],
|
||||
"created_at": now,
|
||||
}
|
||||
)
|
||||
|
||||
if not rows:
|
||||
return None
|
||||
|
||||
table = pa.Table.from_pylist(rows, schema=SAMPLE_SCHEMA)
|
||||
buf = io.BytesIO()
|
||||
pq.write_table(table, buf, compression="snappy", use_dictionary=True, write_statistics=True)
|
||||
return buf.getvalue()
|
||||
# Drains queued uploads so the final step's metrics and episodes land,
|
||||
# then finalizes (idempotent on the platform side); an attached run's
|
||||
# failure marking stays with the launcher.
|
||||
await asyncio.to_thread(self.run.finish)
|
||||
|
||||
@@ -6,8 +6,8 @@ turns the signal half into runtime objects (the sampling half is the env's
|
||||
:class:`~prime_rl.orchestrator.generation_source.GenerationSource`):
|
||||
|
||||
- one module per algorithm (``grpo``, ``echo``, ``max_rl``, ``rae``,
|
||||
``hierarchical_grpo``, ``opd``, ``opsd``, ``sft``) — each named class owns
|
||||
its scoring hooks
|
||||
``hierarchical_grpo``, ``opd``, ``opsd``, ``sft``, ``debug``) — each named
|
||||
class owns its scoring hooks
|
||||
(``score_episode`` / ``score_group``) and declares what it needs (loss
|
||||
component, a "teacher", ...). One instance per env, built by
|
||||
:func:`build_algorithm`. A new credit-assignment scheme is a new named class:
|
||||
@@ -23,6 +23,7 @@ from __future__ import annotations
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from prime_rl.orchestrator.algo.base import Algorithm, connect_frozen_client
|
||||
from prime_rl.orchestrator.algo.debug import DebugAlgorithm
|
||||
from prime_rl.orchestrator.algo.echo import EchoAlgorithm
|
||||
from prime_rl.orchestrator.algo.grpo import GRPOAlgorithm
|
||||
from prime_rl.orchestrator.algo.hierarchical_grpo import HierarchicalGRPOAlgorithm
|
||||
@@ -48,6 +49,7 @@ ALGORITHM_CLASSES: dict[str, type[Algorithm]] = {
|
||||
"opd": OPDAlgorithm,
|
||||
"opsd": OPSDAlgorithm,
|
||||
"sft": SFTDistillAlgorithm,
|
||||
"debug": DebugAlgorithm,
|
||||
}
|
||||
|
||||
|
||||
@@ -64,6 +66,7 @@ def build_algorithm(config: AlgoConfig, clients: InferenceClient) -> Algorithm:
|
||||
|
||||
__all__ = [
|
||||
"Algorithm",
|
||||
"DebugAlgorithm",
|
||||
"EchoAlgorithm",
|
||||
"GRPOAlgorithm",
|
||||
"HierarchicalGRPOAlgorithm",
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.configs.algorithm import DebugAlgoConfig
|
||||
from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces
|
||||
from prime_rl.orchestrator.algo.routing import assign_advantages
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.clients import InferenceClient
|
||||
|
||||
|
||||
class DebugAlgorithm(Algorithm):
|
||||
"""Debugging credit assignment: the same constant advantage (default 1.0)
|
||||
on every sampled token of every clean trainable trace, ignoring rewards
|
||||
entirely. For infra work — every rollout is trainable and every action
|
||||
token carries gradient signal, so the full RL path (advantage transport,
|
||||
importance ratios, trust region, optimizer, weight update) can be exercised
|
||||
regardless of the reward function. Not a real training signal: a policy
|
||||
pushed by it drifts monotonically."""
|
||||
|
||||
def __init__(self, config: DebugAlgoConfig, clients: InferenceClient):
|
||||
super().__init__(config, clients)
|
||||
self.advantage = config.advantage
|
||||
|
||||
async def score_episode(self, episode: vf.Episode) -> None:
|
||||
for _, trace in iter_trainable_traces([episode]):
|
||||
assign_advantages(trace, self.advantage)
|
||||
@@ -9,8 +9,9 @@ from prime_rl.transports.batch import TrainingSample
|
||||
|
||||
|
||||
def assign_advantages(trace: vf.Trace, values: float | list[float]) -> None:
|
||||
"""Assign credit in compact sampled-token order across the trace graph."""
|
||||
nodes = [node for node in trace.nodes if any(node.mask)]
|
||||
"""Assign credit in compact sampled-token order across trainable graph paths."""
|
||||
trainable_nodes = {id(node) for branch in trace.branches if branch.trainable for node in branch.nodes}
|
||||
nodes = [node for node in trace.nodes if id(node) in trainable_nodes and any(node.mask)]
|
||||
for node in nodes:
|
||||
if len(node.mask) != len(node.token_ids):
|
||||
raise ValueError(
|
||||
|
||||
@@ -43,7 +43,7 @@ def stamp_batch(episodes: list[vf.Episode], step: int) -> list[dict[str, Any]]:
|
||||
branches = {
|
||||
branch.index: {"advantages": advantages}
|
||||
for branch in trace.branches
|
||||
if (advantages := branch.advantages) is not None
|
||||
if branch.trainable and (advantages := branch.advantages) is not None
|
||||
}
|
||||
updates.append(make_update(trace.id, info=info, branches=branches))
|
||||
return updates
|
||||
|
||||
@@ -4,6 +4,7 @@ import asyncio
|
||||
import os
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
import httpx
|
||||
import verifiers.v1 as vf
|
||||
@@ -73,16 +74,15 @@ class InferenceClient:
|
||||
await self._scorer.aclose()
|
||||
|
||||
|
||||
class AdminClients:
|
||||
class AdminPlane:
|
||||
"""Admin plane of the policy inference deployment: one httpx client per
|
||||
engine process. The router serves no admin routes (pause/resume,
|
||||
update_weights, init_broadcaster, load_lora_adapter live on the engines),
|
||||
so these clients bypass it via ``admin_base_url``.
|
||||
|
||||
The client order is load-bearing: ``admin_base_url`` order must match the
|
||||
GPU rank order — the ``rank_offset`` math in ``init_nccl_broadcast`` /
|
||||
``init_nixl_broadcast`` and the metrics collector's role list index into
|
||||
it."""
|
||||
GPU rank order used by NCCL/NIXL initialization and the metrics collector's
|
||||
role list index."""
|
||||
|
||||
def __init__(self, client_config: ClientConfig):
|
||||
self.clients = setup_admin_clients(client_config)
|
||||
@@ -107,16 +107,96 @@ class AdminClients:
|
||||
)
|
||||
await maybe_check_has_model(self.clients, model_name, skip_model_check=self._skip_model_check)
|
||||
|
||||
async def initialize_nccl(
|
||||
self,
|
||||
*,
|
||||
host: str,
|
||||
port: int,
|
||||
timeout: int,
|
||||
inference_world_size: int,
|
||||
quantize_in_weight_transfer: bool = False,
|
||||
) -> None:
|
||||
gpus_per_server = inference_world_size // len(self.clients)
|
||||
get_logger().info(
|
||||
f"Initializing NCCL broadcast: {len(self.clients)} servers, "
|
||||
f"inference_world_size={inference_world_size}, gpus_per_server={gpus_per_server}"
|
||||
)
|
||||
|
||||
async def initialize_client(admin_client: AsyncClient, rank_offset: int) -> None:
|
||||
try:
|
||||
response = await admin_client.post(
|
||||
"/init_broadcaster",
|
||||
json={
|
||||
"host": host,
|
||||
"port": port,
|
||||
"rank_offset": rank_offset,
|
||||
"inference_world_size": inference_world_size,
|
||||
"timeout": timeout,
|
||||
"quantize_in_weight_transfer": quantize_in_weight_transfer,
|
||||
},
|
||||
)
|
||||
response.raise_for_status()
|
||||
except httpx.HTTPStatusError as error:
|
||||
if error.response.status_code == 404:
|
||||
get_logger().warning(
|
||||
"The route /init_broadcaster does not exist. Skipping NCCL broadcast initialization."
|
||||
)
|
||||
|
||||
await asyncio.gather(
|
||||
*(
|
||||
initialize_client(admin_client, client_num * gpus_per_server)
|
||||
for client_num, admin_client in enumerate(self.clients)
|
||||
)
|
||||
)
|
||||
|
||||
async def update_weights(
|
||||
self,
|
||||
weight_dir: Path | None,
|
||||
*,
|
||||
transport: Literal["filesystem", "nccl", "nixl"],
|
||||
step: int = 0,
|
||||
on_paused: Callable[[], None] | None = None,
|
||||
) -> None:
|
||||
"""Update every inference engine through its configured weight transport."""
|
||||
weight_dir_posix = weight_dir.as_posix() if weight_dir is not None else None
|
||||
|
||||
await _pause_engines(self.clients, step=step)
|
||||
try:
|
||||
if on_paused is not None:
|
||||
on_paused()
|
||||
await asyncio.gather(
|
||||
*[
|
||||
_admin_post(
|
||||
admin_client,
|
||||
"/update_weights",
|
||||
json={"weight_dir": weight_dir_posix},
|
||||
timeout_s=UPDATE_WEIGHTS_TIMEOUT_S,
|
||||
)
|
||||
for admin_client in self.clients
|
||||
]
|
||||
)
|
||||
finally:
|
||||
await _resume_engines(self.clients)
|
||||
|
||||
async def aclose(self) -> None:
|
||||
for client in self.clients + self._router_clients:
|
||||
await client.aclose()
|
||||
|
||||
|
||||
def setup_admin_plane(client_config: ClientConfig, model_name: str) -> AdminPlane:
|
||||
dynamo = client_config.dynamo
|
||||
if dynamo is not None and dynamo.enabled:
|
||||
from prime_rl.inference.dynamo import DynamoAdminPlane
|
||||
|
||||
return DynamoAdminPlane(client_config, model_name)
|
||||
return AdminPlane(client_config)
|
||||
|
||||
|
||||
async def check_inference_ready(client_config: ClientConfig, model_name: str) -> None:
|
||||
"""One-shot readiness check of an inference endpoint (health + model
|
||||
listing) with transient clients — for frozen endpoints that never need a
|
||||
persistent admin plane."""
|
||||
admin = AdminClients(client_config)
|
||||
admin = AdminPlane(client_config)
|
||||
try:
|
||||
await admin.wait_for_ready(model_name)
|
||||
finally:
|
||||
@@ -300,44 +380,6 @@ async def _resume_engines(admin_clients: list[AsyncClient]) -> None:
|
||||
logger.debug("All inference engines resumed")
|
||||
|
||||
|
||||
async def update_weights(
|
||||
admin_clients: list[AsyncClient],
|
||||
weight_dir: Path | None,
|
||||
step: int = 0,
|
||||
on_paused: Callable[[], None] | None = None,
|
||||
) -> None:
|
||||
"""Update weights on static inference servers.
|
||||
|
||||
Pauses all engines first to drain in-flight requests, then performs the
|
||||
weight update, then resumes. This ensures all DP workers are idle and can
|
||||
participate in the collective weight transfer. ``on_paused`` runs between
|
||||
the pause and the update RPC — the NCCL receiver signals the trainer there.
|
||||
|
||||
Note: the prefix cache is intentionally not reset on weight update. The orchestrator
|
||||
salts the prefix cache per weight version (``cache_salt`` in the sampling request, see
|
||||
``orchestrator/envs.py``), so KV computed under old weights is never reused.
|
||||
"""
|
||||
weight_dir_posix = weight_dir.as_posix() if weight_dir is not None else None
|
||||
|
||||
await _pause_engines(admin_clients, step=step)
|
||||
try:
|
||||
if on_paused is not None:
|
||||
on_paused()
|
||||
await asyncio.gather(
|
||||
*[
|
||||
_admin_post(
|
||||
admin_client,
|
||||
"/update_weights",
|
||||
json={"weight_dir": weight_dir_posix},
|
||||
timeout_s=UPDATE_WEIGHTS_TIMEOUT_S,
|
||||
)
|
||||
for admin_client in admin_clients
|
||||
]
|
||||
)
|
||||
finally:
|
||||
await _resume_engines(admin_clients)
|
||||
|
||||
|
||||
def _is_retryable_lora_error(exception: BaseException) -> bool:
|
||||
"""Check if an exception should trigger a retry for LoRA loading."""
|
||||
if isinstance(exception, httpx.HTTPStatusError):
|
||||
@@ -362,7 +404,7 @@ LORA_LOAD_READ_TIMEOUT_S = 30.0
|
||||
LORA_LOAD_TOTAL_TIMEOUT_S = 120.0
|
||||
|
||||
|
||||
async def load_lora_adapter(admin_clients: list[AsyncClient], lora_name: str, lora_path: Path) -> None:
|
||||
async def load_lora_adapter(admin_plane: AdminPlane, lora_name: str, lora_path: Path) -> None:
|
||||
"""Make a HTTP post request to the vLLM server to load a LoRA adapter.
|
||||
|
||||
Uses our wrapper around vLLM's /v1/load_lora_adapter. The prefix cache is not reset
|
||||
@@ -390,61 +432,11 @@ async def load_lora_adapter(admin_clients: list[AsyncClient], lora_name: str, lo
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
await asyncio.gather(*[_load_lora_adapter(admin_client) for admin_client in admin_clients])
|
||||
|
||||
|
||||
async def init_nccl_broadcast(
|
||||
admin_clients: list[AsyncClient],
|
||||
host: str,
|
||||
port: int,
|
||||
timeout: int,
|
||||
inference_world_size: int,
|
||||
quantize_in_weight_transfer: bool = False,
|
||||
) -> None:
|
||||
"""Initialize NCCL broadcast on all inference servers.
|
||||
|
||||
Each admin client represents one vLLM server. The function computes
|
||||
per-server rank_offset and gpus_per_server so that every inference GPU
|
||||
gets a unique rank in the NCCL broadcast group.
|
||||
"""
|
||||
logger = get_logger()
|
||||
|
||||
gpus_per_server = inference_world_size // len(admin_clients)
|
||||
|
||||
logger.info(
|
||||
f"Initializing NCCL broadcast: {len(admin_clients)} servers, "
|
||||
f"inference_world_size={inference_world_size}, gpus_per_server={gpus_per_server}"
|
||||
)
|
||||
|
||||
async def _init_nccl_broadcast(admin_client: AsyncClient, rank_offset: int) -> None:
|
||||
try:
|
||||
response = await admin_client.post(
|
||||
"/init_broadcaster",
|
||||
json={
|
||||
"host": host,
|
||||
"port": port,
|
||||
"rank_offset": rank_offset,
|
||||
"inference_world_size": inference_world_size,
|
||||
"timeout": timeout,
|
||||
"quantize_in_weight_transfer": quantize_in_weight_transfer,
|
||||
},
|
||||
)
|
||||
response.raise_for_status()
|
||||
except httpx.HTTPStatusError as e:
|
||||
if e.response.status_code == 404:
|
||||
logger.warning("The route /init_broadcaster does not exist. Skipping NCCL broadcast initialization.")
|
||||
return
|
||||
|
||||
await asyncio.gather(
|
||||
*[
|
||||
_init_nccl_broadcast(admin_client, client_num * gpus_per_server)
|
||||
for client_num, admin_client in enumerate(admin_clients)
|
||||
]
|
||||
)
|
||||
await asyncio.gather(*[_load_lora_adapter(client) for client in admin_plane.clients])
|
||||
|
||||
|
||||
async def init_nixl_broadcast(
|
||||
admin_clients: list[AsyncClient],
|
||||
admin_plane: AdminPlane,
|
||||
host: str,
|
||||
port: int,
|
||||
timeout: int,
|
||||
@@ -452,6 +444,7 @@ async def init_nixl_broadcast(
|
||||
session_id: str,
|
||||
) -> None:
|
||||
"""Configure every vLLM worker for NIXL + ModelExpress pulls."""
|
||||
admin_clients = admin_plane.clients
|
||||
workers_per_server = inference_world_size // len(admin_clients)
|
||||
|
||||
async def initialize(admin_client: AsyncClient, rank_offset: int) -> None:
|
||||
|
||||
@@ -39,7 +39,7 @@ from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.algo.routing import is_trainable
|
||||
from prime_rl.orchestrator.annotations import stamp_arrival, stamp_batch
|
||||
from prime_rl.orchestrator.ckpt import setup_ckpt_manager
|
||||
from prime_rl.orchestrator.clients import AdminClients, InferenceClient
|
||||
from prime_rl.orchestrator.clients import AdminPlane, InferenceClient, setup_admin_plane
|
||||
from prime_rl.orchestrator.concurrency import ConcurrencyController
|
||||
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
|
||||
from prime_rl.orchestrator.envs import EvalEnvs, TrainEnvs
|
||||
@@ -119,7 +119,7 @@ class Orchestrator:
|
||||
# Always set by ``setup()``
|
||||
tokenizer: PreTrainedTokenizer
|
||||
clients: InferenceClient | None
|
||||
admin_clients: AdminClients | None
|
||||
admin_plane: AdminPlane | None
|
||||
sender: BatchSender | None
|
||||
packer: BatchPacker
|
||||
train_envs: TrainEnvs
|
||||
@@ -172,7 +172,7 @@ class Orchestrator:
|
||||
# Always assigned by ``setup()``; None-initialized so teardown can run
|
||||
# on a partially completed setup with plain attribute checks
|
||||
self.clients = None
|
||||
self.admin_clients = None
|
||||
self.admin_plane = None
|
||||
|
||||
# Optional attributes — ``setup()`` populates them when the relevant
|
||||
# config is present
|
||||
@@ -208,7 +208,7 @@ class Orchestrator:
|
||||
eval_client_type="openai_chat_completions",
|
||||
renderer_config=config.renderer,
|
||||
)
|
||||
self.admin_clients = AdminClients(config.model.client)
|
||||
self.admin_plane = setup_admin_plane(config.model.client, config.model.name)
|
||||
|
||||
await monitors.setup(
|
||||
producer="orch",
|
||||
@@ -290,7 +290,7 @@ class Orchestrator:
|
||||
|
||||
get_logger().info("Waiting for policy inference pool to be ready")
|
||||
t0 = time.perf_counter()
|
||||
await self.admin_clients.wait_for_ready(config.model.name)
|
||||
await self.admin_plane.wait_for_ready(config.model.name)
|
||||
get_logger().success(f"Policy inference pool ready after {format_time(time.perf_counter() - t0)}")
|
||||
# Build + ready pools for each env's frozen generation source and the
|
||||
# algorithm's frozen reference model
|
||||
@@ -307,7 +307,7 @@ class Orchestrator:
|
||||
self.receiver = setup_weight_receiver(
|
||||
get_broadcast_dir(config.output_dir),
|
||||
config.weight_broadcast,
|
||||
admin_clients=self.admin_clients.clients,
|
||||
admin_plane=self.admin_plane,
|
||||
model_name=config.model.name,
|
||||
)
|
||||
await self.receiver.initialize()
|
||||
@@ -360,7 +360,7 @@ class Orchestrator:
|
||||
# The collector always polls — it feeds the concurrency controller;
|
||||
# metrics fan out to every registered monitor when collection is on.
|
||||
self.inference_metrics = InferenceMetricsCollector(
|
||||
self.admin_clients.clients,
|
||||
self.admin_plane.clients,
|
||||
roles=config.inference_metrics_roles,
|
||||
on_load=self.concurrency.observe,
|
||||
log_metrics=config.collect_inference_metrics,
|
||||
@@ -1056,8 +1056,8 @@ class Orchestrator:
|
||||
await self.inference_metrics.stop()
|
||||
if self.clients is not None:
|
||||
await self.clients.aclose()
|
||||
if self.admin_clients is not None:
|
||||
await self.admin_clients.aclose()
|
||||
if self.admin_plane is not None:
|
||||
await self.admin_plane.aclose()
|
||||
if self.train_envs is not None:
|
||||
get_logger().debug("Stopping generation source and algorithm clients")
|
||||
for env in self.train_envs:
|
||||
|
||||
@@ -91,6 +91,7 @@ def _encode_sampling_mask(mask: vf.SamplingMask | None, num_tokens: int) -> Samp
|
||||
def iter_trainable_branches(trace: vf.Trace) -> Iterator[tuple[vf.Branch, list[bool]]]:
|
||||
"""Yield each branch that yields a training sample, with its trainable-token mask.
|
||||
|
||||
Branches excluded by trace semantics are skipped before shared-node accounting.
|
||||
The mask is `branch.sampled_mask` except that a sampled node shared by several branches
|
||||
(a mid-trajectory fork) is trainable only in the first branch containing it; later
|
||||
branches carry its tokens as context (mask False). Branches left with no trainable
|
||||
@@ -99,6 +100,8 @@ def iter_trainable_branches(trace: vf.Trace) -> Iterator[tuple[vf.Branch, list[b
|
||||
"""
|
||||
trained_nodes: set[int] = set()
|
||||
for branch in trace.branches:
|
||||
if not branch.trainable:
|
||||
continue
|
||||
mask: list[bool] = []
|
||||
for node in branch.nodes:
|
||||
if node.sampled and any(node.mask) and id(node) in trained_nodes:
|
||||
|
||||
@@ -64,6 +64,7 @@ DEFAULT_SELECTIVE_SAVE_OPERATIONS = frozenset(
|
||||
"aten::convolution",
|
||||
"aten::linear",
|
||||
"aten::mm",
|
||||
"prime_rl::dsv4_sparse_attn",
|
||||
"prime_rl::fp8_blockwise_mm",
|
||||
"prime_rl::grouped_fp8_gemm",
|
||||
"prime_rl::sparse_mla",
|
||||
|
||||
@@ -19,6 +19,11 @@ from torchdata.stateful_dataloader import StatefulDataLoader
|
||||
|
||||
from prime_rl.configs.shared import ResumeConfig
|
||||
from prime_rl.configs.trainer import CheckpointConfig
|
||||
from prime_rl.trainer.models.fusions import (
|
||||
join_loaded_optimizer_state_for_runtime,
|
||||
split_packed_optimizer_state_for_checkpoint,
|
||||
write_back_loaded_packed_optimizer_state,
|
||||
)
|
||||
from prime_rl.trainer.optim import OffloadOptimizer, OptimizerLike
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import format_time, get_logger
|
||||
@@ -79,9 +84,12 @@ class AppState(Stateful):
|
||||
# Automatically manages FSDP FQN's, as well as sets the default state dict type to FSDP.SHARDED_STATE_DICT
|
||||
checkpoint_optimizers = self._get_checkpoint_optimizers()
|
||||
model_state_dict, optimizer_state_dict = get_state_dict(self.model, checkpoint_optimizers)
|
||||
# Runtime fusions own one physical state tensor per fused parameter; the checkpoint
|
||||
# sees it under the canonical names. This dict is also the template dcp_load writes
|
||||
# into, and load_state_dict packs the loaded entries back into the runtime state.
|
||||
state_dict = {
|
||||
"model": model_state_dict,
|
||||
"optimizers": optimizer_state_dict,
|
||||
"optimizers": split_packed_optimizer_state_for_checkpoint(self.model, optimizer_state_dict),
|
||||
}
|
||||
if self.scheduler is not None:
|
||||
scheduler_state_dict = self.scheduler.state_dict()
|
||||
@@ -118,15 +126,23 @@ class AppState(Stateful):
|
||||
# apply the model side here and flip the wrappers to initialized so
|
||||
# subsequent steps take the steady-state path.
|
||||
set_model_state_dict(self.model, model_state_dict=state_dict["model"])
|
||||
# The template only aliases a packed parameter's state where the packing
|
||||
# dimension is unsharded, so the loaded logical entries are packed back in.
|
||||
write_back_loaded_packed_optimizer_state(self.model, checkpoint_optimizers, state_dict["optimizers"])
|
||||
for optimizer in self.optimizers:
|
||||
if isinstance(optimizer, OffloadOptimizer):
|
||||
optimizer.finish_checkpoint_load()
|
||||
else:
|
||||
# The runtime state dict read back here keys the fused parameters' state by their
|
||||
# physical names; the loaded logical entries are packed into it.
|
||||
_, runtime_optimizer_state_dict = get_state_dict(self.model, checkpoint_optimizers)
|
||||
set_state_dict(
|
||||
self.model,
|
||||
checkpoint_optimizers,
|
||||
model_state_dict=state_dict["model"],
|
||||
optim_state_dict=state_dict["optimizers"],
|
||||
optim_state_dict=join_loaded_optimizer_state_for_runtime(
|
||||
self.model, state_dict["optimizers"], runtime_optimizer_state_dict
|
||||
),
|
||||
)
|
||||
|
||||
if self.scheduler is not None:
|
||||
|
||||
+35
-326
@@ -4,9 +4,8 @@ import time
|
||||
from pathlib import Path
|
||||
from typing import cast
|
||||
|
||||
# Disable transformers hub kernel interception by default. The `kernels` package, when installed,
|
||||
# causes transformers to auto-replace modules (e.g. mamba-ssm) with hub kernel versions that may
|
||||
# have incompatible CUDA requirements. We only enable it explicitly for models that need it (GPT-OSS).
|
||||
# Disable transformers hub kernel interception. Installed hub kernels can otherwise replace
|
||||
# modules with implementations that have incompatible CUDA requirements.
|
||||
os.environ.setdefault("USE_HUB_KERNELS", "NO")
|
||||
|
||||
import torch
|
||||
@@ -42,6 +41,12 @@ from prime_rl.trainer.models import (
|
||||
get_custom_vlm_cls,
|
||||
supports_custom_impl,
|
||||
)
|
||||
from prime_rl.trainer.models.deepseek_v4.attention import DeepseekV4Indexer
|
||||
from prime_rl.trainer.models.fusions import (
|
||||
apply_model_fusions,
|
||||
get_fsdp_shard_placement_fn,
|
||||
write_back_loaded_packed_parameters,
|
||||
)
|
||||
from prime_rl.trainer.models.glm_moe_dsa.sparse_mla_attention import Indexer
|
||||
from prime_rl.trainer.models.layers.fp8_linear import replace_linear_with_fp8_blockwise_linear
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
@@ -51,7 +56,6 @@ 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
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
from prime_rl.utils.utils import format_time
|
||||
from prime_rl.utils.vlm import get_language_model, get_vision_encoder, is_vlm_architecture
|
||||
from prime_rl.utils.weights import (
|
||||
@@ -83,277 +87,6 @@ def pre_download_model(model_name: str, *, skip_weights: bool = False) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _patch_qwen3_5_moe_conversion_mapping():
|
||||
"""Fix Qwen3.5 MoE conversion mapping incorrectly applying qwen2_moe expert weight splitting.
|
||||
|
||||
Qwen3.5 MoE stores expert weights as fused 3D tensors natively in the checkpoint
|
||||
(e.g. experts.gate_up_proj [num_experts, 2*intermediate, hidden]). The upstream mapping
|
||||
incorrectly maps qwen3_5_moe → qwen2_moe, which assumes per-expert 2D checkpoint weights,
|
||||
causing revert_weight_conversion to produce wrong shapes during weight broadcasting.
|
||||
|
||||
Remove once an official Transformers release fixes this.
|
||||
"""
|
||||
from transformers.conversion_mapping import (
|
||||
get_checkpoint_conversion_mapping,
|
||||
register_checkpoint_conversion_mapping,
|
||||
)
|
||||
|
||||
# qwen3_5_moe_text: keep only the qwen3_5_text renaming, remove qwen2_moe expert conversion
|
||||
qwen3_5_text_mapping = get_checkpoint_conversion_mapping("qwen3_5_text")
|
||||
if qwen3_5_text_mapping is not None:
|
||||
register_checkpoint_conversion_mapping("qwen3_5_moe_text", qwen3_5_text_mapping, overwrite=True)
|
||||
|
||||
# qwen3_5_moe: remove the qwen2_moe fallback entirely
|
||||
register_checkpoint_conversion_mapping("qwen3_5_moe", [], overwrite=True)
|
||||
|
||||
|
||||
def _patch_qwen3_5_text_position_ids():
|
||||
"""Fix Qwen3.5 passing 3D MRoPE position_ids to decoder layers instead of 2D text_position_ids.
|
||||
|
||||
Upstream fix: https://github.com/huggingface/transformers/pull/44399
|
||||
Remove once an official Transformers release includes this fix.
|
||||
"""
|
||||
import inspect
|
||||
|
||||
from transformers.models.qwen3_5.modeling_qwen3_5 import Qwen3_5DecoderLayer, Qwen3_5TextModel
|
||||
from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeDecoderLayer, Qwen3_5MoeTextModel
|
||||
|
||||
for text_model_cls, decoder_layer_cls in [
|
||||
(Qwen3_5TextModel, Qwen3_5DecoderLayer),
|
||||
(Qwen3_5MoeTextModel, Qwen3_5MoeDecoderLayer),
|
||||
]:
|
||||
source = inspect.getsource(text_model_cls.forward)
|
||||
if "decoder_layer" in source and "position_ids=text_position_ids" in source.split("decoder_layer")[-1]:
|
||||
continue # already fixed upstream
|
||||
|
||||
_original_forward = decoder_layer_cls.forward
|
||||
|
||||
def _make_patched_forward(original):
|
||||
def _patched_forward(self, hidden_states, position_ids=None, **kwargs):
|
||||
if position_ids is not None and position_ids.ndim == 3:
|
||||
position_ids = position_ids[0]
|
||||
return original(self, hidden_states, position_ids=position_ids, **kwargs)
|
||||
|
||||
return _patched_forward
|
||||
|
||||
decoder_layer_cls.forward = _make_patched_forward(_original_forward)
|
||||
|
||||
|
||||
def _patch_qwen3_5_linear_attn_varlen():
|
||||
"""Thread cu_seqlens through Qwen3.5 GatedDeltaNet so packed batches don't
|
||||
leak conv/SSM state across sequences.
|
||||
|
||||
HF's forward hardcodes seq_idx=None for causal_conv1d and omits cu_seqlens
|
||||
for chunk_gated_delta_rule, so packed RL training sees ~0.23 Mismatch KL vs
|
||||
vLLM (target <0.01). Mirrors the NemotronH mamba fix.
|
||||
"""
|
||||
import torch.nn.functional as F
|
||||
from transformers.models.qwen3_5.modeling_qwen3_5 import (
|
||||
Qwen3_5DecoderLayer,
|
||||
Qwen3_5GatedDeltaNet,
|
||||
Qwen3_5TextModel,
|
||||
apply_mask_to_padding_states,
|
||||
)
|
||||
|
||||
try:
|
||||
from fla.modules.convolution import causal_conv1d as fla_causal_conv1d
|
||||
from fla.ops.cp import build_cp_context
|
||||
except ImportError:
|
||||
build_cp_context = None
|
||||
fla_causal_conv1d = None
|
||||
|
||||
if fla_causal_conv1d is not None:
|
||||
# The CP boundary-state exchange inside fla's conv is not dynamo-traceable;
|
||||
# graph-break deliberately so the rest of the layer still compiles.
|
||||
fla_causal_conv1d = torch.compiler.disable(fla_causal_conv1d)
|
||||
|
||||
if getattr(Qwen3_5GatedDeltaNet.forward, "_prl_varlen_patched", False):
|
||||
return
|
||||
|
||||
_gdn_orig = Qwen3_5GatedDeltaNet.forward
|
||||
|
||||
def _build_cp_context(self, local_seq_len: int, device: torch.device, cu_seqlens=None):
|
||||
cp_group = getattr(self, "cp_group", None)
|
||||
if cp_group is None or build_cp_context is None:
|
||||
return None
|
||||
global_seq_len = local_seq_len * self.cp_world_size
|
||||
if cu_seqlens is not None and int(cu_seqlens[-1].item()) == global_seq_len:
|
||||
global_cu_seqlens = cu_seqlens.to(device=device, dtype=torch.int32)
|
||||
else:
|
||||
global_cu_seqlens = torch.tensor([0, global_seq_len], dtype=torch.int32, device=device)
|
||||
return build_cp_context(
|
||||
cu_seqlens=global_cu_seqlens,
|
||||
group=cp_group,
|
||||
conv1d_kernel_size=self.conv_kernel_size,
|
||||
)
|
||||
|
||||
def _gdn_forward(self, hidden_states, cache_params=None, attention_mask=None, cu_seqlens=None):
|
||||
if cu_seqlens is None or cache_params is not None:
|
||||
return _gdn_orig(self, hidden_states, cache_params=cache_params, attention_mask=attention_mask)
|
||||
|
||||
hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
|
||||
batch_size, seq_len, _ = hidden_states.shape
|
||||
|
||||
mixed_qkv = self.in_proj_qkv(hidden_states).transpose(1, 2)
|
||||
z = self.in_proj_z(hidden_states).reshape(batch_size, seq_len, -1, self.head_v_dim)
|
||||
b = self.in_proj_b(hidden_states)
|
||||
a = self.in_proj_a(hidden_states)
|
||||
|
||||
cp_context = _build_cp_context(self, seq_len, hidden_states.device, cu_seqlens)
|
||||
|
||||
if cp_context is not None and fla_causal_conv1d is not None:
|
||||
mixed_qkv, _ = fla_causal_conv1d(
|
||||
x=mixed_qkv.transpose(1, 2),
|
||||
weight=self.conv1d.weight.squeeze(1),
|
||||
bias=self.conv1d.bias,
|
||||
activation=self.activation,
|
||||
cp_context=cp_context,
|
||||
)
|
||||
mixed_qkv = mixed_qkv.transpose(1, 2)
|
||||
elif self.causal_conv1d_fn is not None:
|
||||
seg_lens = cu_seqlens[1:] - cu_seqlens[:-1]
|
||||
seq_idx = torch.repeat_interleave(
|
||||
torch.arange(seg_lens.numel(), dtype=torch.int32, device=hidden_states.device),
|
||||
seg_lens,
|
||||
).unsqueeze(0)
|
||||
mixed_qkv = self.causal_conv1d_fn(
|
||||
x=mixed_qkv,
|
||||
weight=self.conv1d.weight.squeeze(1),
|
||||
bias=self.conv1d.bias,
|
||||
activation=self.activation,
|
||||
seq_idx=seq_idx,
|
||||
)
|
||||
else:
|
||||
# Per-segment conv1d so the kernel-1 left pad only draws from within each sequence.
|
||||
cu = cu_seqlens.tolist()
|
||||
conv_outs = []
|
||||
for i in range(len(cu) - 1):
|
||||
s, e = cu[i], cu[i + 1]
|
||||
if s == e:
|
||||
continue
|
||||
conv_outs.append(self.conv1d(mixed_qkv[:, :, s:e])[:, :, : e - s])
|
||||
mixed_qkv = F.silu(torch.cat(conv_outs, dim=-1))
|
||||
|
||||
mixed_qkv = mixed_qkv.transpose(1, 2)
|
||||
query, key, value = torch.split(mixed_qkv, [self.key_dim, self.key_dim, self.value_dim], dim=-1)
|
||||
query = query.reshape(batch_size, seq_len, -1, self.head_k_dim)
|
||||
key = key.reshape(batch_size, seq_len, -1, self.head_k_dim)
|
||||
value = value.reshape(batch_size, seq_len, -1, self.head_v_dim)
|
||||
|
||||
beta = b.sigmoid()
|
||||
g = -self.A_log.float().exp() * F.softplus(a.float() + self.dt_bias)
|
||||
if self.num_v_heads // self.num_k_heads > 1:
|
||||
query = query.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
|
||||
key = key.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
|
||||
|
||||
if cp_context is not None:
|
||||
core_attn_out, _ = self.chunk_gated_delta_rule(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
g=g,
|
||||
beta=beta,
|
||||
use_qk_l2norm_in_kernel=True,
|
||||
cu_seqlens=cp_context.cu_seqlens,
|
||||
cp_context=cp_context,
|
||||
)
|
||||
else:
|
||||
core_attn_out, _ = self.chunk_gated_delta_rule(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
g=g,
|
||||
beta=beta,
|
||||
initial_state=None,
|
||||
output_final_state=False,
|
||||
use_qk_l2norm_in_kernel=True,
|
||||
cu_seqlens=cu_seqlens,
|
||||
)
|
||||
|
||||
core_attn_out = core_attn_out.reshape(-1, self.head_v_dim)
|
||||
z = z.reshape(-1, self.head_v_dim)
|
||||
core_attn_out = self.norm(core_attn_out, z)
|
||||
core_attn_out = core_attn_out.reshape(batch_size, seq_len, -1)
|
||||
return self.out_proj(core_attn_out)
|
||||
|
||||
_gdn_forward._prl_varlen_patched = True
|
||||
Qwen3_5GatedDeltaNet.forward = _gdn_forward
|
||||
|
||||
_dec_orig = Qwen3_5DecoderLayer.forward
|
||||
|
||||
def _dec_forward(
|
||||
self,
|
||||
hidden_states,
|
||||
position_embeddings,
|
||||
attention_mask=None,
|
||||
position_ids=None,
|
||||
past_key_values=None,
|
||||
cu_seqlens=None,
|
||||
**kwargs,
|
||||
):
|
||||
if position_ids is not None and position_ids.ndim == 3:
|
||||
position_ids = position_ids[0]
|
||||
if self.layer_type != "linear_attention":
|
||||
return _dec_orig(
|
||||
self,
|
||||
hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
attention_mask=attention_mask,
|
||||
position_ids=position_ids,
|
||||
past_key_values=past_key_values,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
residual = hidden_states
|
||||
hidden_states = self.input_layernorm(hidden_states)
|
||||
hidden_states = self.linear_attn(
|
||||
hidden_states=hidden_states,
|
||||
cache_params=past_key_values,
|
||||
attention_mask=attention_mask,
|
||||
cu_seqlens=cu_seqlens,
|
||||
)
|
||||
hidden_states = residual + hidden_states
|
||||
residual = hidden_states
|
||||
hidden_states = self.post_attention_layernorm(hidden_states)
|
||||
hidden_states = self.mlp(hidden_states)
|
||||
return residual + hidden_states
|
||||
|
||||
Qwen3_5DecoderLayer.forward = _dec_forward
|
||||
|
||||
_text_orig = Qwen3_5TextModel.forward
|
||||
|
||||
def _text_forward(
|
||||
self,
|
||||
input_ids=None,
|
||||
attention_mask=None,
|
||||
position_ids=None,
|
||||
past_key_values=None,
|
||||
inputs_embeds=None,
|
||||
use_cache=None,
|
||||
**kwargs,
|
||||
):
|
||||
attn_impl = getattr(self.config, "_attn_implementation", None)
|
||||
cu_seqlens = None
|
||||
if attn_impl in ("flash_attention_2", "flash_attention_3", "flash_attention_4") and position_ids is not None:
|
||||
pids = position_ids
|
||||
if pids.ndim == 3:
|
||||
pids = pids[0]
|
||||
cu_seqlens, _ = get_cu_seqlens_from_position_ids(pids)
|
||||
kwargs["cu_seqlens"] = cu_seqlens
|
||||
return _text_orig(
|
||||
self,
|
||||
input_ids=input_ids,
|
||||
attention_mask=attention_mask,
|
||||
position_ids=position_ids,
|
||||
past_key_values=past_key_values,
|
||||
inputs_embeds=inputs_embeds,
|
||||
use_cache=use_cache,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
Qwen3_5TextModel.forward = _text_forward
|
||||
|
||||
|
||||
# Add filter to the standard logging module for transformers.modeling_utils to supress the
|
||||
# flash attention dtype warnings since FSDP is used to handle mixed precision.
|
||||
transformers_modeling_utils_logger = logging.getLogger("transformers.modeling_utils")
|
||||
@@ -456,20 +189,22 @@ def get_full_offload_dtype_policy(
|
||||
|
||||
|
||||
def freeze_sparse_indexer(model: nn.Module) -> None:
|
||||
"""Freeze DSA sparse-attention indexer parameters.
|
||||
"""Freeze sparse-attention indexer parameters.
|
||||
|
||||
The indexer's `compute_sparse_indices` forward runs under `torch.no_grad()`, so its
|
||||
params never receive a gradient and cannot be trained. Left with requires_grad=True
|
||||
they stay stateless in the optimizer, which breaks strict checkpoint resume: DCP
|
||||
materializes optimizer state for every requires_grad param at load time, but the
|
||||
stateless params were never saved -> "Missing key in checkpoint state_dict". Freezing
|
||||
them keeps the saved and loaded optimizer state symmetric.
|
||||
An indexer forward runs under `torch.no_grad()`, so its params never receive a gradient
|
||||
and cannot be trained. Left with requires_grad=True they stay stateless in the optimizer,
|
||||
which breaks strict checkpoint resume: DCP materializes optimizer state for every
|
||||
requires_grad param at load time, but the stateless params were never saved -> "Missing
|
||||
key in checkpoint state_dict". Freezing them keeps the saved and loaded optimizer state
|
||||
symmetric.
|
||||
"""
|
||||
# TODO: no model here trains its indexer. DeepSeek's auxiliary KL objective, which supervises
|
||||
# the top-k selection, is unimplemented, so these params are frozen rather than learned.
|
||||
logger = get_logger()
|
||||
num_frozen = 0
|
||||
|
||||
for module in model.modules():
|
||||
if isinstance(module, Indexer):
|
||||
if isinstance(module, (Indexer, DeepseekV4Indexer)):
|
||||
for param in module.parameters():
|
||||
param.requires_grad = False
|
||||
num_frozen += 1
|
||||
@@ -500,7 +235,8 @@ def apply_force_balanced_routing(model: nn.Module) -> None:
|
||||
|
||||
|
||||
def is_tt_moe_model(model: nn.Module) -> bool:
|
||||
return hasattr(model.config, "num_experts") or hasattr(model.config, "n_routed_experts")
|
||||
config = getattr(model.config, "text_config", model.config)
|
||||
return hasattr(config, "num_experts") or hasattr(config, "n_routed_experts")
|
||||
|
||||
|
||||
def get_load_balance_stats(
|
||||
@@ -557,37 +293,7 @@ def get_model(
|
||||
|
||||
if is_vlm_training:
|
||||
logger.info(f"Detected vision-language model: {config.name}")
|
||||
if config.optimization_dtype != "bfloat16" or config.reduce_dtype != "bfloat16":
|
||||
raise ValueError(
|
||||
"VLM models must use optimization_dtype='bfloat16' and reduce_dtype='bfloat16' to match vLLM inference."
|
||||
)
|
||||
|
||||
# GPT-OSS only supports FlashAttention via kernels-community/vllm-flash-attn3, which requires Hopper (SM 90).
|
||||
HOPPER_MAJOR = 9
|
||||
if getattr(model_config, "model_type", "") == "gpt_oss":
|
||||
major, minor = torch.cuda.get_device_capability()
|
||||
if major != HOPPER_MAJOR:
|
||||
raise ValueError(
|
||||
f"GPT-OSS requires Hopper (SM 90) for flash attention, detected SM {major}{minor}. "
|
||||
f"GPT-OSS is not supported on non-Hopper GPUs."
|
||||
)
|
||||
# Enable hub kernels for GPT-OSS (disabled by default to avoid interfering with other models).
|
||||
import transformers.integrations.hub_kernels as _hub_kernels
|
||||
|
||||
_hub_kernels._kernels_enabled = True
|
||||
|
||||
# Qwen3.6 and Qwen3.8 reuse the Qwen3.5 architecture, so match on model_type, not repo name.
|
||||
if getattr(model_config, "model_type", "").startswith("qwen3_5"):
|
||||
_patch_qwen3_5_text_position_ids()
|
||||
_patch_qwen3_5_moe_conversion_mapping()
|
||||
_patch_qwen3_5_linear_attn_varlen()
|
||||
if is_vlm_arch and config.cp > 1 and config.cp_style == "ulysses":
|
||||
vision_config = getattr(model_config, "vision_config", None)
|
||||
if vision_config is not None:
|
||||
logger.info("Using SDPA for VLM vision encoder under CP")
|
||||
vision_config._attn_implementation = "sdpa"
|
||||
if hasattr(vision_config, "_attn_implementation_internal"):
|
||||
vision_config._attn_implementation_internal = "sdpa"
|
||||
for subconfig_key in getattr(model_config, "sub_configs", {}):
|
||||
subconfig = getattr(model_config, subconfig_key, None)
|
||||
if subconfig is not None and hasattr(subconfig, "use_cache"):
|
||||
@@ -640,15 +346,6 @@ def get_model(
|
||||
|
||||
logger.debug(f"Loaded model config ({model_config.to_dict()})")
|
||||
|
||||
# NemotronH: transformers' Mamba2 mixer __init__ calls lazy_load_kernel("mamba-ssm" /
|
||||
# "causal-conv1d") whenever config.use_mamba_kernels is set. That hub-kernel path is gated only
|
||||
# by whether the `kernels` package is importable (NOT by USE_HUB_KERNELS) and resolves from the
|
||||
# HF Hub, which hard-crashes under HF_HUB_OFFLINE=1. prime-rl swaps in its own mamba_ssm Triton
|
||||
# SSD kernels via _patch_mamba2_use_triton_ssd, so the hub kernels are redundant; disable them
|
||||
# to keep model init offline-safe.
|
||||
if getattr(model_config, "model_type", "") == "nemotron_h":
|
||||
model_config.use_mamba_kernels = False
|
||||
|
||||
if config.debug.num_layers is not None:
|
||||
# VLM configs nest num_hidden_layers under text_config
|
||||
target_config = getattr(model_config, "text_config", model_config)
|
||||
@@ -774,10 +471,12 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
|
||||
mp_policy = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=DTYPE_MAP[config.reduce_dtype])
|
||||
offload_policy: OffloadPolicy = CPUOffloadPolicy(pin_memory=True) if config.fsdp_cpu_offload else OffloadPolicy()
|
||||
|
||||
shard_placement_fn = get_fsdp_shard_placement_fn(model) if config.fusions.shard_fused_on_dim1 else None
|
||||
fsdp_config = {
|
||||
"mp_policy": mp_policy,
|
||||
"offload_policy": offload_policy,
|
||||
"reshard_after_forward": config.reshard_after_forward,
|
||||
"shard_placement_fn": shard_placement_fn,
|
||||
}
|
||||
|
||||
hsdp_mesh = parallel_dims.get_mesh("hsdp")
|
||||
@@ -819,6 +518,7 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
|
||||
mp_policy=MixedPrecisionPolicy(param_dtype=torch.float32, reduce_dtype=torch.float32),
|
||||
offload_policy=offload_policy,
|
||||
reshard_after_forward=config.reshard_after_forward,
|
||||
shard_placement_fn=shard_placement_fn,
|
||||
)
|
||||
|
||||
fully_shard(
|
||||
@@ -844,6 +544,7 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
|
||||
mp_policy=mp_policy,
|
||||
offload_policy=offload_policy,
|
||||
reshard_after_forward=False,
|
||||
shard_placement_fn=shard_placement_fn,
|
||||
)
|
||||
else:
|
||||
get_logger().warning("Model uses tied word embeddings, so skipping the last-layer no-reshard optimization.")
|
||||
@@ -854,6 +555,7 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
|
||||
mp_policy=mp_policy,
|
||||
offload_policy=offload_policy,
|
||||
reshard_after_forward=config.reshard_after_forward,
|
||||
shard_placement_fn=shard_placement_fn,
|
||||
)
|
||||
|
||||
if not parallel_dims.ep_enabled:
|
||||
@@ -1006,6 +708,7 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
|
||||
state_dict,
|
||||
storage_reader=HuggingFaceStorageReader(path=snapshot_path.as_posix()),
|
||||
)
|
||||
write_back_loaded_packed_parameters(model, state_dict)
|
||||
# Restore weight tying broken by to_empty() for HF models
|
||||
if not isinstance(model, PreTrainedModelPrimeRL) and model.config.tie_word_embeddings:
|
||||
model.tie_weights()
|
||||
@@ -1257,6 +960,12 @@ def setup_model(
|
||||
logger.warning("Cannot load model to meta device only, loading to CPU instead.")
|
||||
model = get_model(config, device=torch.device("cpu"), dtype=DTYPE_MAP[config.optimization_dtype])
|
||||
|
||||
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)
|
||||
logger.info(f"Applied runtime model fusions: {applied}")
|
||||
|
||||
lm_head_chunk_size: int | None = None
|
||||
if isinstance(config.fused_lm_head_token_chunk_size, int):
|
||||
lm_head_chunk_size = config.fused_lm_head_token_chunk_size
|
||||
@@ -1273,9 +982,9 @@ def setup_model(
|
||||
if config.moe_router_dtype == "float32":
|
||||
apply_fp32_moe_router(model)
|
||||
|
||||
# The DSA sparse-attention indexer runs its forward under torch.no_grad(), so it is
|
||||
# never trainable. Freeze it so optimizer state stays symmetric across checkpoint
|
||||
# save/resume. No-op for models without a sparse indexer.
|
||||
# A sparse-attention indexer runs its forward under torch.no_grad(), so it is never
|
||||
# trainable. Freeze it so optimizer state stays symmetric across checkpoint save/resume.
|
||||
# No-op for models without a sparse indexer.
|
||||
freeze_sparse_indexer(model)
|
||||
|
||||
if config.debug.force_balanced_routing:
|
||||
|
||||
@@ -8,7 +8,6 @@ from transformers.models.auto.auto_factory import _BaseAutoModelClass, _LazyAuto
|
||||
from transformers.models.auto.configuration_auto import CONFIG_MAPPING_NAMES
|
||||
from transformers.models.llama.configuration_llama import LlamaConfig
|
||||
from transformers.models.qwen3.configuration_qwen3 import Qwen3Config
|
||||
from transformers.models.qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfig
|
||||
|
||||
from prime_rl.trainer.models.afmoe import AfmoeConfig, AfmoeForCausalLM
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
@@ -22,8 +21,14 @@ from prime_rl.trainer.models.llama import LlamaForCausalLM
|
||||
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2Config, MiniMaxM2ForCausalLM
|
||||
from prime_rl.trainer.models.nemotron_h import NemotronHConfig, NemotronHForCausalLM
|
||||
from prime_rl.trainer.models.qwen3 import Qwen3ForCausalLM
|
||||
from prime_rl.trainer.models.qwen3_5 import Qwen3_5ForCausalLM
|
||||
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeConfig, Qwen3_5MoeForCausalLM
|
||||
from prime_rl.trainer.models.qwen3_5 import (
|
||||
Qwen3_5Config,
|
||||
Qwen3_5ForCausalLM,
|
||||
Qwen3_5MoeConfig,
|
||||
Qwen3_5MoeTextConfig,
|
||||
Qwen3_5TextConfig,
|
||||
Qwen3_5VisionConfig,
|
||||
)
|
||||
from prime_rl.trainer.models.qwen3_moe import Qwen3MoeConfig, Qwen3MoeForCausalLM
|
||||
|
||||
# Make custom config discoverable by AutoConfig
|
||||
@@ -31,13 +36,16 @@ AutoConfig.register("afmoe", AfmoeConfig, exist_ok=True)
|
||||
AutoConfig.register("deepseek_v4", DeepseekV4Config, exist_ok=True)
|
||||
AutoConfig.register("glm4_moe", Glm4MoeConfig, exist_ok=True)
|
||||
AutoConfig.register("glm_moe_dsa", GlmMoeDsaConfig, exist_ok=True)
|
||||
AutoConfig.register("gpt_oss", GptOssConfig, exist_ok=True)
|
||||
AutoConfig.register("laguna", LagunaConfig, exist_ok=True)
|
||||
AutoConfig.register("minimax_m2", MiniMaxM2Config, exist_ok=True)
|
||||
AutoConfig.register("nemotron_h", NemotronHConfig, exist_ok=True)
|
||||
AutoConfig.register("qwen3_moe", Qwen3MoeConfig, exist_ok=True)
|
||||
AutoConfig.register("qwen3_5", Qwen3_5Config, exist_ok=True)
|
||||
AutoConfig.register("qwen3_5_text", Qwen3_5TextConfig, exist_ok=True)
|
||||
AutoConfig.register("qwen3_5_moe_text", Qwen3_5MoeConfig, exist_ok=True)
|
||||
# GptOssConfig is just HF's class - already registered by transformers, no override needed.
|
||||
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)
|
||||
|
||||
_CUSTOM_CAUSAL_LM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, OrderedDict())
|
||||
_CUSTOM_CAUSAL_LM_MODELS: tuple[
|
||||
@@ -55,7 +63,9 @@ _CUSTOM_CAUSAL_LM_MODELS: tuple[
|
||||
(NemotronHConfig, NemotronHForCausalLM),
|
||||
(Qwen3MoeConfig, Qwen3MoeForCausalLM),
|
||||
(Qwen3_5TextConfig, Qwen3_5ForCausalLM),
|
||||
(Qwen3_5MoeConfig, Qwen3_5MoeForCausalLM),
|
||||
(Qwen3_5MoeTextConfig, Qwen3_5ForCausalLM),
|
||||
(Qwen3_5Config, Qwen3_5ForCausalLM),
|
||||
(Qwen3_5MoeConfig, Qwen3_5ForCausalLM),
|
||||
(GptOssConfig, GptOssForCausalLM),
|
||||
)
|
||||
for config_cls, model_cls in _CUSTOM_CAUSAL_LM_MODELS:
|
||||
@@ -95,7 +105,7 @@ def supports_custom_impl(model_config: PretrainedConfig) -> bool:
|
||||
# Points to the same unified class — the config drives text-only vs VLM behavior.
|
||||
_CUSTOM_VLM_MAPPING: dict[str, type] = {
|
||||
"qwen3_5": Qwen3_5ForCausalLM,
|
||||
"qwen3_5_moe": Qwen3_5MoeForCausalLM,
|
||||
"qwen3_5_moe": Qwen3_5ForCausalLM,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ from typing import Literal
|
||||
from torch import Tensor
|
||||
from transformers.modeling_utils import PreTrainedModel
|
||||
|
||||
from prime_rl.utils.cp import CPContext
|
||||
|
||||
CPStyle = Literal["ring", "ulysses"]
|
||||
ALL_CP_STYLES: frozenset[CPStyle] = frozenset({"ring", "ulysses"})
|
||||
|
||||
@@ -25,6 +27,8 @@ class PreTrainedModelPrimeRL(PreTrainedModel):
|
||||
after loading with meta device.
|
||||
"""
|
||||
|
||||
cp_context: CPContext = CPContext()
|
||||
|
||||
@classmethod
|
||||
def cp_support(cls, config) -> CPSupport:
|
||||
"""CP styles this architecture supports, given its config.
|
||||
@@ -44,7 +48,7 @@ class PreTrainedModelPrimeRL(PreTrainedModel):
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def from_config(cls, config, **kwargs):
|
||||
def from_config(cls, config, trust_remote_code: bool = False, **kwargs):
|
||||
"""Public from_config that mirrors the Auto class API."""
|
||||
return cls._from_config(config, **kwargs)
|
||||
|
||||
|
||||
@@ -23,14 +23,13 @@ Design constraints:
|
||||
``expert_offset`` so a rank can unstack just its *local* experts into
|
||||
globally-numbered per-expert keys — no all-gather. Any op that genuinely
|
||||
needs a full tensor is the caller's responsibility to gather first (via the
|
||||
trainer's ``_resolve_dtensors``); none of the ops here gather on their own.
|
||||
trainer's ``resolve_dtensors``); none of the ops here gather on their own.
|
||||
* **Every op is present-guarded** — it no-ops when its inputs are absent — so
|
||||
the same per-layer op list can be emitted for every layer and simply skips
|
||||
dense / non-matching layers, exactly as the imperative loops did.
|
||||
* **"Backward" means "what the imperative ``*_to_hf`` did"**, not a strict
|
||||
mathematical inverse: a few conversions are intentionally lossy (e.g.
|
||||
NemotronH shifts a router bias one way and does not undo it). Such ops carry
|
||||
an explicit backward (see :class:`MapValue`).
|
||||
* **"Backward" means "what the imperative ``*_to_hf`` did"**, not necessarily
|
||||
a strict mathematical inverse. Value transforms can provide an explicit
|
||||
backward through :class:`MapValue`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -32,7 +32,7 @@ of the compressed variants is below, tensors flowing downwards:
|
||||
│ │
|
||||
└────────── concatenate ──────┘
|
||||
│
|
||||
QKᵀ (with {compression,position}-aware masking)
|
||||
gather each query's slots, then QKᵀ
|
||||
│
|
||||
softmax + sink
|
||||
│
|
||||
@@ -49,10 +49,11 @@ useful due to the complexities introduced by the compressed attention variants.
|
||||
necessary attention data is organized into a `PackedContext` object (directly consumed by attention
|
||||
layers), built from one `seq_lens` and carrying:
|
||||
|
||||
- `attention_mask`: causal, local-window, clipped at document boundaries.
|
||||
- `position_ids`: each token's position within its own document.
|
||||
- `tok_doc_idx`: which document each token belongs to.
|
||||
- `position_embeddings`: the RoPE tables, one per rope type, evaluated at `position_ids`.
|
||||
- `window_indices`: for each query, the indices of the tokens its local window covers, causal
|
||||
and clipped at document boundaries, with `IGNORE_SLOT` (-1) marking invalid/masked entries.
|
||||
- `compression_layouts`: one `CompressionLayout` per compress rate in the architecture.
|
||||
|
||||
The last of those characterizes the token-compression mechanism of DeepSeek V4. We start with it
|
||||
@@ -95,28 +96,65 @@ holds it once and shares it across rates.
|
||||
|
||||
Compression is only part of the story: every attention layer also reads a local sliding window of
|
||||
the most recent tokens directly, and the compressed entries are how it reaches anything older.
|
||||
That window needs a causal sliding-window mask applied per document, `attention_mask`, and every
|
||||
rotation in the block needs `position_ids` together with the RoPE tables evaluated at them,
|
||||
`position_embeddings`. None of those belongs to any single compress rate.
|
||||
That window is enumerated per document by `window_indices`, and every rotation in the block needs
|
||||
`position_ids` together with the RoPE tables evaluated at them, `position_embeddings`. None of
|
||||
those belongs to any single compress rate.
|
||||
|
||||
`PackedContext.build` takes `seq_lens` and derives every one of its fields from it. Nothing else is
|
||||
an input, so a position that disagrees with a document boundary, a mask that spans one, or a RoPE
|
||||
table evaluated at positions other than the ones the causal thresholds count in, cannot be
|
||||
constructed. It runs once per model forward, since none of this depends on depth.
|
||||
an input, so a position that disagrees with a document boundary, a window slot that spans one, or a
|
||||
RoPE table evaluated at positions other than the ones the causal thresholds count in, cannot be
|
||||
constructed. It runs once per model forward.
|
||||
|
||||
Context parallelism splits the queries across ranks and leaves everything else alone: every field
|
||||
above has one entry per query token and so covers this rank's `n_queries` tokens, while
|
||||
`compression_layouts` covers all `total_tokens` of the sequence. Token indices always count from
|
||||
the start of the whole sequence.
|
||||
|
||||
[The Index Contract]
|
||||
|
||||
All three layer types reach their keys the same way. `SparseAttnInputs` lays out one KV buffer,
|
||||
|
||||
kv_buf[b, n, 0, d]: the packed token stream, then this layer's compressed entries, and
|
||||
nothing else: an absent key needs no position of its own
|
||||
|
||||
and one int32 index tensor addressing that position axis, `sliding_window + picks` slots per
|
||||
query: the local window first, the picks after. `picks` is the indexer's `index_topk` for CSA,
|
||||
`max_entries_per_doc` for HCA, and zero for a sliding layer, which reads its window alone. A slot
|
||||
with nothing to read holds `IGNORE_SLOT` (-1), which the kernel masks on, so a short window and a
|
||||
surplus pick cost only their loads.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
import torch.distributed as dist
|
||||
from torch import Tensor, nn
|
||||
|
||||
from prime_rl.trainer.models.deepseek_v4.configuration_deepseek_v4 import DeepseekV4Config
|
||||
from prime_rl.trainer.models.deepseek_v4.hyperconnections import DeepseekV4UnweightedRMSNorm
|
||||
from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding, apply_rotary_pos_emb_interleaved
|
||||
from prime_rl.trainer.models.kernels.deepseek_v4 import IGNORE_SLOT
|
||||
from prime_rl.trainer.models.kernels.fp8_indexer import fp8_indexer
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.utils.cp import CPContext, gather_for_cp
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
|
||||
|
||||
# Guarded because tilelang ships in the linux-gated `gpu` extra, so some installs lack it.
|
||||
try:
|
||||
from prime_rl.trainer.models.kernels.deepseek_v4.dsv4_sparse_attn import dsv4_sparse_attn, sparse_attn_shape_error
|
||||
except ImportError:
|
||||
dsv4_sparse_attn = None # type: ignore
|
||||
sparse_attn_shape_error = None # type: ignore
|
||||
|
||||
|
||||
def _kernel_blocker(num_heads: int, head_dim: int) -> str | None:
|
||||
"""Why the fused kernel cannot run at this shape, or ``None`` if it can."""
|
||||
if dsv4_sparse_attn is None:
|
||||
return "the tilelang sparse-attention kernel failed to import; install the `gpu` extra"
|
||||
# CSA gives every query head the same single KV head, so the kernel's `kv_group` is 1. The
|
||||
# shape constraints themselves are stated once, next to the kernels they come from.
|
||||
return sparse_attn_shape_error(num_heads, 1, head_dim)
|
||||
|
||||
|
||||
class DeepseekV4GroupedLinear(nn.Linear):
|
||||
"""Block-diagonal grouped linear, the first half of the output projection.
|
||||
@@ -142,53 +180,6 @@ class DeepseekV4GroupedLinear(nn.Linear):
|
||||
return y.reshape(*input_shape, self.n_groups, -1)
|
||||
|
||||
|
||||
def eager_attention_with_sinks(
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
sinks: torch.Tensor,
|
||||
attention_mask: torch.Tensor,
|
||||
scaling: float,
|
||||
dropout: float = 0.0,
|
||||
training: bool = False,
|
||||
) -> torch.Tensor:
|
||||
attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
|
||||
attn_weights = attn_weights + attention_mask
|
||||
|
||||
sink_logits = sinks.reshape(1, -1, 1, 1).expand(query.shape[0], -1, query.shape[-2], -1)
|
||||
combined_logits = torch.cat([attn_weights, sink_logits], dim=-1)
|
||||
# Row-max subtraction is not free here: without it the exponentials overflow in bf16.
|
||||
combined_logits = combined_logits - combined_logits.max(dim=-1, keepdim=True).values
|
||||
probs = F.softmax(combined_logits, dim=-1, dtype=combined_logits.dtype)
|
||||
|
||||
scores = F.dropout(probs[..., :-1], p=dropout, training=training).to(value.dtype)
|
||||
attn_output = torch.matmul(scores, value)
|
||||
return attn_output.transpose(1, 2).contiguous()
|
||||
|
||||
|
||||
def build_sliding_window_mask(*, tok_doc_idx: Tensor, sliding_window: int, dtype: torch.dtype) -> Tensor:
|
||||
"""Additive `(1, 1, seq_len, seq_len)` mask over query rows and key columns.
|
||||
|
||||
A key is readable when it lies in the query's own document and within the `sliding_window`
|
||||
tokens up to and including the query.
|
||||
|
||||
A padded micro-batch folds its padding into the last document, so the padding is masked as a
|
||||
continuation of the last document. Causality already keeps it away from every real token, and it
|
||||
is loss-masked.
|
||||
"""
|
||||
seq_len = tok_doc_idx.shape[0]
|
||||
device = tok_doc_idx.device
|
||||
tok_idx = torch.arange(seq_len, device=device)
|
||||
|
||||
distance = tok_idx[:, None] - tok_idx[None, :]
|
||||
in_causal_window = (distance >= 0) & (distance < sliding_window)
|
||||
same_document = tok_doc_idx[:, None] == tok_doc_idx[None, :]
|
||||
readable = in_causal_window & same_document
|
||||
|
||||
mask = torch.zeros(seq_len, seq_len, dtype=dtype, device=device)
|
||||
return mask.masked_fill_(~readable, torch.finfo(dtype).min)[None, None]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CompressionLayout:
|
||||
"""Per-document compressed-entry layout for one compress rate.
|
||||
@@ -202,6 +193,8 @@ class CompressionLayout:
|
||||
entry_tok_idx: Tensor # (n_entries, compress_rate) int64 - token index in the packed sequence, per entry
|
||||
entry_doc_idx: Tensor # (n_entries,) int64 - which document each entry belongs to
|
||||
entry_local_idx: Tensor # (n_entries,) int64 - entry index within its own document
|
||||
first_entry_of_doc: Tensor # (n_docs,) int64 - sequence-global index of each document's first entry
|
||||
max_entries_per_doc: int # largest entry count any single document contributes
|
||||
|
||||
@classmethod
|
||||
def build(cls, *, cu_seqlens: Tensor, compress_rate: int) -> "CompressionLayout":
|
||||
@@ -232,6 +225,8 @@ class CompressionLayout:
|
||||
entry_tok_idx=entry_tok_idx,
|
||||
entry_doc_idx=entry_doc_idx,
|
||||
entry_local_idx=entry_local_idx,
|
||||
first_entry_of_doc=first_entry_of_doc,
|
||||
max_entries_per_doc=int(counts.max()),
|
||||
)
|
||||
|
||||
|
||||
@@ -239,31 +234,26 @@ class CompressionLayout:
|
||||
class PackedContext:
|
||||
"""Everything an attention layer needs to know about the packed row it is running on.
|
||||
|
||||
The mask, the positions, the RoPE tables and the layouts all encode the same document
|
||||
boundaries and are only correct together. As separate arguments they can contradict each
|
||||
other: a mask built without document boundaries spans documents while a layout does not, a
|
||||
sequence-global `position_ids` feeds `causal_threshold` a count that a per-document
|
||||
`entry_local_idx` cannot be compared against, and a RoPE table evaluated at one set of
|
||||
positions rotates queries the thresholds were not counted at. `build` derives every field
|
||||
from one `seq_lens`, so none of those is reachable. It runs once per model forward, since
|
||||
none of this depends on depth.
|
||||
The window indices, the positions, the RoPE tables and the layouts all encode the same
|
||||
document boundaries and are only correct together. As separate arguments they can contradict
|
||||
each other: a window enumerated without document boundaries spans documents while a layout
|
||||
does not, a sequence-global `position_ids` feeds `causal_threshold` a count that a
|
||||
per-document `entry_local_idx` cannot be compared against, and a RoPE table evaluated at one
|
||||
set of positions rotates queries the thresholds were not counted at. `build` derives every
|
||||
field from one `seq_lens`, so none of those is reachable. It runs once per model forward.
|
||||
|
||||
Context parallelism gives each rank a contiguous run of `n_queries` tokens to use as queries
|
||||
and a full copy of the keys, so every field but `compression_layouts` has one entry per query
|
||||
token and covers this rank's run alone, while `compression_layouts` covers the whole sequence.
|
||||
Token indices always count from the start of the whole sequence, never from this rank's run.
|
||||
"""
|
||||
|
||||
attention_mask: Tensor # (1, 1, seq_len, seq_len) additive - causal, local window, document-clipped
|
||||
position_ids: Tensor # (1, seq_len) int64 - token position within its own document
|
||||
tok_doc_idx: Tensor # (seq_len,) int64 - which document each packed token belongs to
|
||||
position_embeddings: dict[str, tuple[Tensor, Tensor]] # (cos, sin) keyed by rope type
|
||||
position_ids: Tensor # (1, n_queries) int64 - token position within its own document
|
||||
tok_doc_idx: Tensor # (n_queries,) int64 - which document each query token belongs to
|
||||
position_embeddings: dict[str, tuple[Tensor, Tensor]] # (cos, sin) keyed by rope type, at `position_ids`
|
||||
window_indices: Tensor # (n_queries, sliding_window) int32 - global token per window slot, IGNORE_SLOT if unused
|
||||
compression_layouts: dict[int, CompressionLayout] # keyed by compress rate
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
# Only reachable by constructing the dataclass directly; `build` cannot violate it.
|
||||
total_tokens = self.tok_doc_idx.shape[0]
|
||||
if self.attention_mask.shape[-2] != total_tokens or self.position_ids.shape[-1] != total_tokens:
|
||||
raise ValueError(
|
||||
f"attention_mask covers {self.attention_mask.shape[-2]} query rows and position_ids "
|
||||
f"{self.position_ids.shape[-1]} tokens, but the row has {total_tokens}"
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def build(
|
||||
cls,
|
||||
@@ -272,41 +262,62 @@ class PackedContext:
|
||||
seq_lens: Tensor,
|
||||
dtype: torch.dtype,
|
||||
device: torch.device,
|
||||
cp_rank: int = 0,
|
||||
cp_world_size: int = 1,
|
||||
) -> "PackedContext":
|
||||
"""Derive every field from one `seq_lens`, ensuring mutual consistency.
|
||||
|
||||
`rotary_emb` supplies the RoPE tables and, through the config it was built from, the
|
||||
sliding window and the compress rates in use. Taking the config from it rather than
|
||||
alongside it keeps them from naming different architectures. `dtype` must be the dtype
|
||||
attention runs at, since the mask is additive. The row is as wide as `seq_lens` says,
|
||||
attention runs at, since it types the RoPE tables. The sequence is as long as `seq_lens` says,
|
||||
padding included: both packers fold their padding into the last document.
|
||||
|
||||
`seq_lens` always describes the whole sequence. `cp_rank` and `cp_world_size` say which
|
||||
contiguous shard of it this rank holds the queries of; the keys, the entries and the index
|
||||
values addressing them stay global, so only the query side narrows.
|
||||
"""
|
||||
config = rotary_emb.config
|
||||
# Read the width before `seq_lens` moves: on a CPU `seq_lens` that costs no device sync.
|
||||
total_tokens = int(seq_lens.sum())
|
||||
assert total_tokens % cp_world_size == 0, (
|
||||
f"{total_tokens} tokens do not split evenly across {cp_world_size} CP ranks"
|
||||
)
|
||||
n_queries = total_tokens // cp_world_size
|
||||
q_start = cp_rank * n_queries
|
||||
|
||||
cu_seqlens, _ = get_cu_seqlens_from_seq_lens(seq_lens.to(device=device))
|
||||
tok_idx = torch.arange(total_tokens, device=device)
|
||||
tok_doc_idx = torch.searchsorted(cu_seqlens[1:].to(tok_idx.dtype), tok_idx, right=True)
|
||||
# Document-local by construction: a token's position is its distance from its own
|
||||
# document's start, which is what `causal_threshold` and the entry rotation count in.
|
||||
position_ids = (tok_idx - cu_seqlens[tok_doc_idx])[None]
|
||||
compress_rates = {
|
||||
config.compress_rates[layer_type]
|
||||
for layer_type in set(config.layer_types)
|
||||
if layer_type in config.compress_rates
|
||||
}
|
||||
|
||||
# These fields have one entry per query token, so they cover this rank's tokens only.
|
||||
# `cu_seqlens` still spans the whole sequence, so document boundaries stay available.
|
||||
tok_idx = torch.arange(q_start, q_start + n_queries, device=device)
|
||||
tok_doc_idx = torch.searchsorted(cu_seqlens[1:].to(tok_idx.dtype), tok_idx, right=True)
|
||||
# Document-local by construction: a token's position is its distance from its own
|
||||
# document's start, which is what `causal_threshold` and the entry rotation count in.
|
||||
position_ids = (tok_idx - cu_seqlens[tok_doc_idx])[None]
|
||||
position_embeddings = {
|
||||
rope_type: rotary_emb(position_ids, rope_type, dtype=dtype) for rope_type in rotary_emb.layer_types
|
||||
}
|
||||
|
||||
# A token attends the last `sliding_window` positions (itself included), clipped to its own
|
||||
# document.
|
||||
window_base = torch.maximum(tok_idx - position_ids[0], tok_idx - config.sliding_window + 1)
|
||||
slots = window_base[:, None] + torch.arange(config.sliding_window, device=device)[None, :]
|
||||
window_indices = torch.where(slots <= tok_idx[:, None], slots, IGNORE_SLOT).to(torch.int32)
|
||||
|
||||
return cls(
|
||||
attention_mask=build_sliding_window_mask(
|
||||
tok_doc_idx=tok_doc_idx, sliding_window=config.sliding_window, dtype=dtype
|
||||
),
|
||||
position_ids=position_ids,
|
||||
tok_doc_idx=tok_doc_idx,
|
||||
position_embeddings={
|
||||
rope_type: rotary_emb(position_ids, rope_type, dtype=dtype) for rope_type in rotary_emb.layer_types
|
||||
},
|
||||
position_embeddings=position_embeddings,
|
||||
compression_layouts={
|
||||
rate: CompressionLayout.build(cu_seqlens=cu_seqlens, compress_rate=rate) for rate in compress_rates
|
||||
},
|
||||
window_indices=window_indices,
|
||||
)
|
||||
|
||||
def check_position_ids(self, position_ids: Tensor) -> None:
|
||||
@@ -316,7 +327,9 @@ class PackedContext:
|
||||
caller's positions vanish there too. A padded micro-batch restarts `position_ids` at 0
|
||||
inside its last document, which this permits: padding sits mid-document, never at a start.
|
||||
A sequence-global `arange` over a packed row never restarts, and a 1-based one never
|
||||
reaches zero at all; both are rejected.
|
||||
reaches zero at all; both are rejected. Under CP the comparison is against this rank's
|
||||
queries alone, which lines up because the trainer shards the caller's `position_ids` the
|
||||
same way.
|
||||
"""
|
||||
disagrees = (self.position_ids == 0) & (position_ids != 0)
|
||||
if disagrees.any():
|
||||
@@ -328,26 +341,68 @@ class PackedContext:
|
||||
"substitutes (see `prime_rl.trainer.models.layers.lm_head`), which this rejects."
|
||||
)
|
||||
|
||||
def token_entry_causal_mask(self, compress_rate: int, threshold: Tensor) -> Tensor:
|
||||
"""`(1, seq_len, n_entries)` bool: which compressed entries each query token may read.
|
||||
|
||||
Element `[0, t, e]` is true when query token `t` may read entry `e` of the rate's layout.
|
||||
Both of these have to hold:
|
||||
@dataclass(frozen=True)
|
||||
class SparseAttnInputs:
|
||||
"""The KV buffer one attention layer gathers from, and the gather indices addressing it.
|
||||
|
||||
- `e` belongs to `t`'s own document, so no query reads another document's history;
|
||||
- `e` closed before `t` arrived, i.e. its index within that document is below
|
||||
`threshold[0, t]`, the count of entries the query's position has completed.
|
||||
`build` constructs the two together so they stay mutually consistent and cannot drift apart.
|
||||
|
||||
One `seq_lens` describes one packed row, so the leading axis is 1 and broadcasts over the
|
||||
batch, as `threshold` does.
|
||||
With `S` tokens in the packed row and `E` compressed entries for this layer's rate, `E` being
|
||||
zero for a layer that reads no entries at all:
|
||||
|
||||
`threshold` counts per document, so it is compared against `entry_local_idx` and not
|
||||
against the sequence-global entry number; those two coordinate systems disagree for every
|
||||
document after the first.
|
||||
kv_buf[b, n, 0, d]: n in [0, S) -> local token stream
|
||||
n in [S, S + E) -> compressed entry (n - S)
|
||||
|
||||
Every index must be a real key in `[0, n_positions)` or `IGNORE_SLOT` (-1), which marks an absent
|
||||
key, which `build` enforces.
|
||||
|
||||
Under context parallelism the token half of `kv_buf` is still the whole global stream, `S`
|
||||
being every token of the packed row, while `indices` has one entry per query token this rank
|
||||
holds.
|
||||
"""
|
||||
|
||||
kv_buf: Tensor # (batch, n_positions, 1, head_dim)
|
||||
indices: Tensor # (batch, n_queries, 1, n_slots) int32 into kv_buf's position axis
|
||||
|
||||
@classmethod
|
||||
def build(
|
||||
cls,
|
||||
*,
|
||||
kv: Tensor, # (batch, 1, n_tokens, head_dim), the rotated token stream
|
||||
compressed_kv: Tensor | None = None, # (batch, 1, n_entries, head_dim)
|
||||
top_k_indices: Tensor | None = None, # (batch, n_queries, n_picks) int64, IGNORE_SLOT (-1) marks a surplus pick
|
||||
window_indices: Tensor, # (n_queries, sliding_window) int32, IGNORE_SLOT marks an invalid slot
|
||||
) -> "SparseAttnInputs":
|
||||
"""Lay out one layer's gather slots: the local window first, then any compressed picks.
|
||||
|
||||
A layer with no entries passes neither `compressed_kv` nor `top_k_indices`, receiving only
|
||||
the local sliding window.
|
||||
"""
|
||||
layout = self.compression_layouts[compress_rate]
|
||||
same_document = self.tok_doc_idx[None, :, None] == layout.entry_doc_idx[None, None, :]
|
||||
return same_document & (threshold.unsqueeze(-1) > layout.entry_local_idx[None, None, :])
|
||||
assert (compressed_kv is None) == (top_k_indices is None), (
|
||||
"compressed_kv and top_k_indices describe the same entries: pass both or neither"
|
||||
)
|
||||
# The two counts differ under CP: the keys are global and the queries are this rank's.
|
||||
batch, _, n_tokens, _ = kv.shape
|
||||
n_queries = window_indices.shape[0]
|
||||
assert top_k_indices is None or top_k_indices.shape[1] == n_queries, (
|
||||
f"top_k_indices covers {top_k_indices.shape[1]} query tokens and window_indices {n_queries}"
|
||||
)
|
||||
|
||||
positions = kv if compressed_kv is None else torch.cat([kv, compressed_kv], dim=2)
|
||||
kv_buf = positions.transpose(1, 2).contiguous() # (b, S + E, 1, d)
|
||||
|
||||
window = window_indices[None, :, None, :].expand(batch, n_queries, 1, -1)
|
||||
if top_k_indices is None:
|
||||
return cls(kv_buf=kv_buf, indices=window.contiguous())
|
||||
|
||||
# A surplus pick is `IGNORE_SLOT` (-1) and stays `IGNORE_SLOT`; a real one names an entry,
|
||||
# which sits past the token stream in `kv_buf`, hence the shift by `n_tokens`.
|
||||
# NOTE: the attention kernel recompiles for every unique `indices.shape[-1]` value. If
|
||||
# recompilation becomes a bottleneck, consider padding to fixed length with `IGNORE_SLOT` values.
|
||||
picks = torch.where(top_k_indices >= 0, top_k_indices + n_tokens, IGNORE_SLOT)
|
||||
indices = torch.cat([window, picks[:, :, None, :].to(torch.int32)], dim=-1)
|
||||
return cls(kv_buf=kv_buf, indices=indices)
|
||||
|
||||
|
||||
class DeepseekV4Compressor(nn.Module):
|
||||
@@ -360,8 +415,8 @@ class DeepseekV4Compressor(nn.Module):
|
||||
source tokens of entry `e`'s pooling window, and `d` runs over `head_dim`. Each entry is
|
||||
RMSNormed and rotated with the `compress` RoPE at its window's first source position, which
|
||||
is what makes it comparable with the attention block's locally rotated KV stream. `forward`
|
||||
returns the entries alongside an additive `block_bias` saying which query may read which, for
|
||||
`DeepseekV4Attention` to concatenate onto its local sliding window.
|
||||
returns the entries alongside this layer's entry selection: the per-query entry indices the
|
||||
attention block gathers, with `IGNORE_SLOT` (-1) marking a slot the query has nothing to read into.
|
||||
|
||||
`n_series` sets the slots `s` the gate ranges over. With `1` a token joins only its own
|
||||
window, so windows are disjoint. With `2` the projections emit two `head_dim`-wide series
|
||||
@@ -405,16 +460,25 @@ class DeepseekV4Compressor(nn.Module):
|
||||
torch.cat([previous_gate, gate[..., self.head_dim :]], dim=2),
|
||||
)
|
||||
|
||||
def compress(self, hidden_states: torch.Tensor, packed: PackedContext) -> torch.Tensor:
|
||||
"""Compress `(batch, seq_len, hidden_size)` to `(batch, n_entries, head_dim)`.
|
||||
|
||||
The layout at this compressor's own rate decides which source tokens each entry pools.
|
||||
"""
|
||||
def compress(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
packed: PackedContext,
|
||||
cp_group: dist.ProcessGroup | None = None,
|
||||
cp_world_size: int = 1,
|
||||
) -> torch.Tensor:
|
||||
"""Compress `(batch, seq_len, hidden_size)` to `(batch, n_entries, head_dim)`."""
|
||||
batch = hidden_states.shape[0]
|
||||
layout = packed.compression_layouts[self.compress_rate]
|
||||
|
||||
kv = self.kv_proj(hidden_states)[:, layout.entry_tok_idx]
|
||||
gate = self.gate_proj(hidden_states)[:, layout.entry_tok_idx] + self.position_bias
|
||||
width = self.n_series * self.head_dim
|
||||
proj = torch.cat([self.kv_proj(hidden_states), self.gate_proj(hidden_states)], dim=-1)
|
||||
if cp_world_size > 1:
|
||||
proj = gather_for_cp(proj, cp_group)
|
||||
kv, gate = proj.split(width, dim=-1)
|
||||
|
||||
kv = kv[:, layout.entry_tok_idx]
|
||||
gate = gate[:, layout.entry_tok_idx] + self.position_bias
|
||||
if self.n_series == 2:
|
||||
kv, gate = self._overlap_with_previous_window(kv, gate, layout)
|
||||
|
||||
@@ -442,41 +506,12 @@ class DeepseekV4Compressor(nn.Module):
|
||||
nn.init.zeros_(self.position_bias)
|
||||
|
||||
|
||||
class DeepseekV4IndexerScorer(nn.Module):
|
||||
"""Lightning-Indexer score `score[t,e] = sum_h w[t,h] * ReLU(q[t,h,d] * k[e,d])`.
|
||||
|
||||
Query token `t` against compressed entry `e`, over indexer heads `h` and `index_head_dim`
|
||||
channels `d`. The per-head weights `w[t,h]` come off the hidden state directly rather than
|
||||
from a query-key interaction, which keeps the scorer one matmul deep. It runs in fp32: the
|
||||
scores only feed a top-k, so the width costs little and near-ties are not decided by bf16
|
||||
rounding.
|
||||
"""
|
||||
|
||||
def __init__(self, config: DeepseekV4Config):
|
||||
super().__init__()
|
||||
self.softmax_scale = config.index_head_dim**-0.5
|
||||
self.weights_scaling = config.index_n_heads**-0.5
|
||||
self.weights_proj = nn.Linear(config.hidden_size, config.index_n_heads, bias=False)
|
||||
|
||||
def forward(self, q: torch.Tensor, compressed_kv: torch.Tensor, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
"""Score `q` `(batch, seq, heads, dim)` against `compressed_kv` `(batch, entries, dim)`."""
|
||||
scores = torch.matmul(q.float(), compressed_kv.transpose(-1, -2).float().unsqueeze(1))
|
||||
scores = F.relu(scores) * self.softmax_scale
|
||||
weights = self.weights_proj(hidden_states).float() * self.weights_scaling
|
||||
return (scores * weights.unsqueeze(-1)).sum(dim=2)
|
||||
|
||||
|
||||
class DeepseekV4Indexer(nn.Module):
|
||||
"""Lightning Indexer: picks the `index_topk` compressed entries each query may read.
|
||||
|
||||
It owns a compressor at the narrow `index_head_dim` and scores each query against its
|
||||
entries. The indices it returns address the entries of the compressor that owns it: both
|
||||
share `compress_rate` and the `compress` RoPE base, so entry `e` in one covers the same
|
||||
source tokens as entry `e` in the other, and the scores depend only on the query-key
|
||||
distance.
|
||||
|
||||
Each query gets `min(index_topk, entries)` picks. An early query has fewer entries whose
|
||||
source tokens all lie at or before it, and its surplus picks come back as `-1`.
|
||||
Every query gets `index_topk` picks, the width the kernel pads to. An early query has fewer
|
||||
entries whose source tokens all lie at or before it, and its surplus picks come back as
|
||||
`IGNORE_SLOT` (-1).
|
||||
"""
|
||||
|
||||
def __init__(self, config: DeepseekV4Config):
|
||||
@@ -488,31 +523,38 @@ class DeepseekV4Indexer(nn.Module):
|
||||
config, self.head_dim, config.compress_rates["compressed_sparse_attention"], n_series=2
|
||||
)
|
||||
self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.head_dim, bias=False)
|
||||
self.scorer = DeepseekV4IndexerScorer(config)
|
||||
self.weights_proj = nn.Linear(config.hidden_size, self.num_heads, bias=False)
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor, q_residual: torch.Tensor, packed: PackedContext) -> torch.Tensor:
|
||||
@torch.no_grad() # Returns non-differentiable integer indices.
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
q_residual: torch.Tensor,
|
||||
packed: PackedContext,
|
||||
cp_group: dist.ProcessGroup | None = None,
|
||||
cp_world_size: int = 1,
|
||||
) -> torch.Tensor:
|
||||
batch, seq_len, _ = hidden_states.shape
|
||||
compressed_kv = self.compressor.compress(hidden_states, packed)
|
||||
compressed_len = compressed_kv.shape[1]
|
||||
top_k = min(self.index_topk, compressed_len)
|
||||
assert batch == 1, f"the indexer needs a packed batch of size 1, got {batch}"
|
||||
compressed_kv = self.compressor.compress(hidden_states, packed, cp_group=cp_group, cp_world_size=cp_world_size)
|
||||
n_entries = compressed_kv.shape[1]
|
||||
|
||||
# The token-position table for this rope type is already on `packed`; the compressor's own
|
||||
# rotary is only ever evaluated at entry positions.
|
||||
cos, sin = packed.position_embeddings[self.compressor.rope_layer_type]
|
||||
q = self.q_b_proj(q_residual).view(batch, seq_len, -1, self.head_dim).transpose(1, 2)
|
||||
q = apply_rotary_pos_emb_interleaved(q, cos, sin).transpose(1, 2)
|
||||
w = self.weights_proj(hidden_states)
|
||||
|
||||
scores = self.scorer(q, compressed_kv, hidden_states)
|
||||
if compressed_len == 0:
|
||||
return scores.topk(top_k, dim=-1).indices
|
||||
layout = packed.compression_layouts[self.compressor.compress_rate]
|
||||
entry_start = layout.first_entry_of_doc[packed.tok_doc_idx].int()
|
||||
entry_stop = (entry_start + self.compressor.causal_threshold(packed.position_ids)[0]).int()
|
||||
|
||||
threshold = self.compressor.causal_threshold(packed.position_ids)
|
||||
readable = packed.token_entry_causal_mask(self.compressor.compress_rate, threshold).expand_as(scores)
|
||||
scores = scores.masked_fill(~readable, float("-inf"))
|
||||
top_k_indices = scores.topk(top_k, dim=-1).indices
|
||||
# An early query has fewer than `top_k` readable entries, so top-k still hands back
|
||||
# masked-out ones. Mark those `-1` rather than letting them leak into attention.
|
||||
return torch.where(readable.gather(-1, top_k_indices), top_k_indices, torch.full_like(top_k_indices, -1))
|
||||
# fp8_indexer has no batch axis
|
||||
top_k_indices = fp8_indexer(q[0], compressed_kv[0], w[0], entry_start, entry_stop, self.index_topk).unsqueeze(0)
|
||||
|
||||
# Mark indices-to-ignore with IGNORE_SLOT
|
||||
in_range = top_k_indices < n_entries
|
||||
top_k_indices = torch.where(in_range, top_k_indices, torch.full_like(top_k_indices, IGNORE_SLOT))
|
||||
return top_k_indices.long()
|
||||
|
||||
def init_weights(self, init_std: float) -> None:
|
||||
self.compressor.init_weights(init_std)
|
||||
@@ -522,10 +564,9 @@ class DeepseekV4CSACompressor(DeepseekV4Compressor):
|
||||
"""Compressed Sparse Attention compressor: the sparse long-range half of a CSA layer.
|
||||
|
||||
Two series at a fine compress rate, with overlapping windows. A Lightning Indexer scores
|
||||
the entries and keeps the `index_topk` best per query, and the returned `block_bias` is
|
||||
that selection: `0` on the selected entries, `-inf` everywhere else. It needs no separate
|
||||
causal term, because the indexer only selects entries whose source tokens all lie at or
|
||||
before the query.
|
||||
the entries and keeps the `index_topk` best per query, and the returned `top_k_indices` is
|
||||
that selection, with `IGNORE_SLOT` (-1) marking a surplus pick. It needs no separate causal term,
|
||||
because the indexer only selects entries whose source tokens all lie at or before the query.
|
||||
"""
|
||||
|
||||
def __init__(self, config: DeepseekV4Config):
|
||||
@@ -533,20 +574,18 @@ class DeepseekV4CSACompressor(DeepseekV4Compressor):
|
||||
self.indexer = DeepseekV4Indexer(config)
|
||||
|
||||
def forward(
|
||||
self, hidden_states: torch.Tensor, q_residual: torch.Tensor, packed: PackedContext
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
q_residual: torch.Tensor,
|
||||
packed: PackedContext,
|
||||
cp_group: dist.ProcessGroup | None = None,
|
||||
cp_world_size: int = 1,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
batch, seq_len, _ = hidden_states.shape
|
||||
compressed_kv = self.compress(hidden_states, packed).unsqueeze(1)
|
||||
compressed_len = compressed_kv.shape[2]
|
||||
|
||||
compressed_kv = self.compress(hidden_states, packed, cp_group=cp_group, cp_world_size=cp_world_size)
|
||||
# The indexer reads the same layout: it compresses the same source windows at a narrower
|
||||
# head dim, so its entry `e` and this compressor's entry `e` are the same window.
|
||||
top_k_indices = self.indexer(hidden_states, q_residual, packed)
|
||||
# The `-1` sentinels are scattered into one throwaway column that is sliced back off.
|
||||
safe_indices = torch.where(top_k_indices >= 0, top_k_indices, torch.full_like(top_k_indices, compressed_len))
|
||||
block_bias = compressed_kv.new_full((batch, 1, seq_len, compressed_len + 1), float("-inf"))
|
||||
block_bias.scatter_(-1, safe_indices.unsqueeze(1), 0.0)
|
||||
return compressed_kv, block_bias[..., :compressed_len]
|
||||
picks = self.indexer(hidden_states, q_residual, packed, cp_group=cp_group, cp_world_size=cp_world_size)
|
||||
return compressed_kv.unsqueeze(1), picks
|
||||
|
||||
def init_weights(self, init_std: float) -> None:
|
||||
super().init_weights(init_std)
|
||||
@@ -557,25 +596,36 @@ class DeepseekV4HCACompressor(DeepseekV4Compressor):
|
||||
"""Heavily Compressed Attention compressor: the dense long-range half of an HCA layer.
|
||||
|
||||
One series at a coarse compress rate, with disjoint windows. There is no indexer: a query
|
||||
reads every entry whose source tokens all lie at or before it, and the returned
|
||||
`block_bias` carries that rule.
|
||||
reads every entry whose source tokens all lie at or before it. A document's entries are
|
||||
numbered consecutively, so that set is the contiguous range starting at the document's first
|
||||
entry, and the picks the layer gathers are arithmetic rather than learned. Every document is
|
||||
afforded `max_entries_per_doc` picks; a query that has completed fewer entries than that pads
|
||||
the rest with `IGNORE_SLOT` (-1), as the indexer's surplus picks do.
|
||||
"""
|
||||
|
||||
def __init__(self, config: DeepseekV4Config):
|
||||
super().__init__(config, config.head_dim, config.compress_rates["heavily_compressed_attention"], n_series=1)
|
||||
|
||||
def forward(
|
||||
self, hidden_states: torch.Tensor, q_residual: torch.Tensor, packed: PackedContext
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
q_residual: torch.Tensor,
|
||||
packed: PackedContext,
|
||||
cp_group: dist.ProcessGroup | None = None,
|
||||
cp_world_size: int = 1,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""`q_residual` is part of the compressor contract but unused: HCA has no indexer."""
|
||||
batch, seq_len, _ = hidden_states.shape
|
||||
compressed_kv = self.compress(hidden_states, packed).unsqueeze(1)
|
||||
compressed_len = compressed_kv.shape[2]
|
||||
batch = hidden_states.shape[0]
|
||||
compressed_kv = self.compress(hidden_states, packed, cp_group=cp_group, cp_world_size=cp_world_size)
|
||||
|
||||
threshold = self.causal_threshold(packed.position_ids)
|
||||
readable = packed.token_entry_causal_mask(self.compress_rate, threshold).unsqueeze(1)
|
||||
block_bias = compressed_kv.new_zeros((batch, 1, seq_len, compressed_len))
|
||||
return compressed_kv, block_bias.masked_fill_(~readable, float("-inf"))
|
||||
layout = packed.compression_layouts[self.compress_rate]
|
||||
# `threshold` counts entries within the query's own document, so it selects how far into
|
||||
# that document's range to read, and the document's own base turns that into an entry index.
|
||||
threshold = self.causal_threshold(packed.position_ids).unsqueeze(-1) # (1, seq_len, 1)
|
||||
base = layout.first_entry_of_doc[packed.tok_doc_idx][None, :, None] # (1, seq_len, 1)
|
||||
offsets = torch.arange(layout.max_entries_per_doc, device=hidden_states.device)
|
||||
picks = torch.where(offsets < threshold, base + offsets, IGNORE_SLOT)
|
||||
return compressed_kv.unsqueeze(1), picks.expand(batch, -1, -1)
|
||||
|
||||
|
||||
COMPRESSOR_CLASSES = {
|
||||
@@ -631,15 +681,24 @@ class DeepseekV4Attention(nn.Module):
|
||||
)
|
||||
self.o_b_proj = nn.Linear(config.o_groups * config.o_lora_rank, config.hidden_size, bias=False)
|
||||
self.sinks = nn.Parameter(torch.zeros(self.num_heads))
|
||||
# Raised here rather than from the first forward, where it would surface as an ImportError
|
||||
# or a tilelang compile failure a long way from the config that caused it.
|
||||
blocker = _kernel_blocker(self.num_heads, self.head_dim)
|
||||
if blocker is not None:
|
||||
raise ValueError(f"DeepSeek V4 cannot run the fused sparse-attention kernel: {blocker}")
|
||||
assert config.attention_dropout == 0.0, "the fused sparse attention kernel implements no dropout"
|
||||
compressor_class = COMPRESSOR_CLASSES[self.layer_type]
|
||||
self.compressor = compressor_class(config) if compressor_class is not None else None
|
||||
|
||||
self.cp_context = CPContext()
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor, packed: PackedContext) -> tuple[torch.Tensor, None]:
|
||||
"""`packed` carries the document boundaries every pathway below is clipped at."""
|
||||
# Shape keys in the comments below:
|
||||
#
|
||||
# - `b`: batch
|
||||
# - `t`: token in the packed row
|
||||
# - `t`: token in this rank's query shard
|
||||
# - `T`: token in the whole packed row, which is `t` unless CP is on
|
||||
# - `h`: attention head
|
||||
# - `d`: head_dim
|
||||
# - `e`: compressed entry
|
||||
@@ -650,38 +709,44 @@ class DeepseekV4Attention(nn.Module):
|
||||
# `hidden_states` is (b, t, hidden_size).
|
||||
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
hidden_shape = (*input_shape, -1, self.head_dim) # (b, t, -1, d): the -1 is h for q, 1 for kv
|
||||
hidden_shape = (*input_shape, -1, self.head_dim) # (b, t, h, d), the query view
|
||||
cos, sin = packed.position_embeddings[self.rope_layer_type] # (1, t, qk_rope_head_dim // 2) each
|
||||
|
||||
q_residual = self.q_a_norm(self.q_a_proj(hidden_states)) # (b, t, r)
|
||||
q = self.q_b_proj(q_residual).view(*hidden_shape).transpose(1, 2) # (b, h, t, d)
|
||||
q = apply_rotary_pos_emb_interleaved(self.q_b_norm(q), cos, sin)
|
||||
|
||||
kv = self.kv_norm(self.kv_proj(hidden_states)).view(*hidden_shape).transpose(1, 2) # (b, 1, t, d)
|
||||
kv = apply_rotary_pos_emb_interleaved(kv, cos, sin)
|
||||
kv = self.kv_norm(self.kv_proj(hidden_states)) # (b, t, d)
|
||||
kv = kv.view(*kv.shape[:2], 1, self.head_dim) # (b, t, 1, d)
|
||||
kv = apply_rotary_pos_emb_interleaved(kv, cos, sin, unsqueeze_dim=2)
|
||||
if self.cp_context.cp_enabled:
|
||||
kv = gather_for_cp(kv, self.cp_context.cp_group) # (b, T, 1, d)
|
||||
kv = kv.transpose(1, 2) # (b, 1, T, d)
|
||||
|
||||
attention_mask = packed.attention_mask # (1, 1, t, t)
|
||||
|
||||
if self.compressor is not None:
|
||||
# (b, 1, e, d), (b, 1, t, e)
|
||||
compressed_kv, block_bias = self.compressor(hidden_states, q_residual, packed)
|
||||
kv = torch.cat([kv, compressed_kv], dim=2) # (b, 1, t + e, d)
|
||||
# The compressed entries live outside the local window, so the sliding mask says
|
||||
# nothing about them; `block_bias` carries their per-query causality and the
|
||||
# indexer's selection. Zero-padding instead would let every query read every one.
|
||||
attention_mask = torch.cat(
|
||||
[attention_mask.expand(*block_bias.shape[:-1], -1), block_bias.to(attention_mask.dtype)], dim=-1
|
||||
) # (b, 1, t, t + e)
|
||||
|
||||
attn_output = eager_attention_with_sinks(
|
||||
q,
|
||||
kv,
|
||||
kv,
|
||||
compressed = (
|
||||
self.compressor(
|
||||
hidden_states,
|
||||
q_residual,
|
||||
packed,
|
||||
cp_group=self.cp_context.cp_group,
|
||||
cp_world_size=self.cp_context.cp_world_size,
|
||||
)
|
||||
if self.compressor is not None
|
||||
else None
|
||||
)
|
||||
compressed_kv, top_k_indices = compressed if compressed is not None else (None, None)
|
||||
inputs = SparseAttnInputs.build(
|
||||
kv=kv,
|
||||
compressed_kv=compressed_kv,
|
||||
top_k_indices=top_k_indices,
|
||||
window_indices=packed.window_indices,
|
||||
)
|
||||
attn_output, _ = dsv4_sparse_attn(
|
||||
q.transpose(1, 2).contiguous(),
|
||||
inputs.kv_buf,
|
||||
inputs.indices,
|
||||
self.sinks,
|
||||
attention_mask,
|
||||
scaling=self.scaling,
|
||||
dropout=self.attention_dropout,
|
||||
training=self.training,
|
||||
self.scaling,
|
||||
) # (b, t, h, d)
|
||||
|
||||
# The value stream is the key stream, so it arrived rotated. Rotating the output
|
||||
@@ -707,8 +772,6 @@ __all__ = [
|
||||
"DeepseekV4GroupedLinear",
|
||||
"DeepseekV4HCACompressor",
|
||||
"DeepseekV4Indexer",
|
||||
"DeepseekV4IndexerScorer",
|
||||
"PackedContext",
|
||||
"build_sliding_window_mask",
|
||||
"eager_attention_with_sinks",
|
||||
"SparseAttnInputs",
|
||||
]
|
||||
|
||||
@@ -320,7 +320,7 @@ class DeepseekV4Config(PretrainedConfig):
|
||||
self.rope_parameters = rope_parameters_dict
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""Drop the derived `mlp_layer_types` duck-typing shim before serializing.
|
||||
"""Drop the in-memory-only field before serializing.
|
||||
|
||||
`num_hash_layers` is the on-disk source of truth (matching the real checkpoint);
|
||||
`mlp_layer_types` only exists in memory so HF's real `DeepseekV4SparseMoeBlock`
|
||||
|
||||
@@ -77,7 +77,7 @@ def _layer_ops(layer_idx: int, layer_type: str) -> list[ConvOp]:
|
||||
idx, prime_idx = f"{attn}.indexer", f"{prime_attn}.compressor.indexer"
|
||||
ops += [
|
||||
Rename(f"{idx}.wq_b.weight", f"{prime_idx}.q_b_proj.weight"),
|
||||
Rename(f"{idx}.weights_proj.weight", f"{prime_idx}.scorer.weights_proj.weight"),
|
||||
Rename(f"{idx}.weights_proj.weight", f"{prime_idx}.weights_proj.weight"),
|
||||
Rename(f"{idx}.compressor.wkv.weight", f"{prime_idx}.compressor.kv_proj.weight"),
|
||||
Rename(f"{idx}.compressor.wgate.weight", f"{prime_idx}.compressor.gate_proj.weight"),
|
||||
Rename(f"{idx}.compressor.norm.weight", f"{prime_idx}.compressor.kv_norm.weight"),
|
||||
|
||||
@@ -20,7 +20,7 @@ from torch import Tensor
|
||||
|
||||
from prime_rl.trainer.models.conversion_ops import StateDict
|
||||
|
||||
_FP4_E2M1_LUT = torch.tensor(
|
||||
FP4_E2M1_LUT = torch.tensor(
|
||||
[0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0],
|
||||
dtype=torch.float32,
|
||||
)
|
||||
@@ -28,7 +28,7 @@ _FP4_E2M1_LUT = torch.tensor(
|
||||
|
||||
def _unpack_mxfp4(packed: Tensor) -> Tensor:
|
||||
"""Two packed e2m1 nibbles per `int8` byte -> `float32`, doubling the last dim."""
|
||||
lut = _FP4_E2M1_LUT.to(packed.device)
|
||||
lut = FP4_E2M1_LUT.to(packed.device)
|
||||
u8 = packed.contiguous().view(torch.uint8)
|
||||
low_nibble = (u8 & 0xF).long()
|
||||
high_nibble = ((u8 >> 4) & 0xF).long()
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
"""Naive DeepSeek V4 attention reference.
|
||||
|
||||
Nothing in the production path calls these. They exist for the tests, where a dense, obviously
|
||||
correct implementation is the standard the fused kernel is measured against, and where it is the
|
||||
only implementation that runs at shapes the kernel cannot tile. The dependency runs one way only:
|
||||
this module reads `attention.py`, which is kernel-only and never reads back.
|
||||
"""
|
||||
|
||||
import types
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import Tensor, nn
|
||||
|
||||
from prime_rl.trainer.models.deepseek_v4 import attention as dsv4_attention
|
||||
from prime_rl.trainer.models.deepseek_v4.attention import DeepseekV4Attention, PackedContext, SparseAttnInputs
|
||||
from prime_rl.trainer.models.deepseek_v4.rotary import apply_rotary_pos_emb_interleaved
|
||||
|
||||
|
||||
def eager_attention_with_sinks(
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
sinks: torch.Tensor,
|
||||
attention_mask: torch.Tensor,
|
||||
scaling: float,
|
||||
dropout: float = 0.0,
|
||||
training: bool = False,
|
||||
) -> torch.Tensor:
|
||||
attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
|
||||
attn_weights = attn_weights + attention_mask
|
||||
|
||||
sink_logits = sinks.reshape(1, -1, 1, 1).expand(query.shape[0], -1, query.shape[-2], -1)
|
||||
combined_logits = torch.cat([attn_weights, sink_logits], dim=-1)
|
||||
# Row-max subtraction is not free here: without it the exponentials overflow in bf16.
|
||||
combined_logits = combined_logits - combined_logits.max(dim=-1, keepdim=True).values
|
||||
probs = F.softmax(combined_logits, dim=-1, dtype=combined_logits.dtype)
|
||||
|
||||
scores = F.dropout(probs[..., :-1], p=dropout, training=training).to(value.dtype)
|
||||
attn_output = torch.matmul(scores, value)
|
||||
return attn_output.transpose(1, 2).contiguous()
|
||||
|
||||
|
||||
def build_sliding_window_mask(*, tok_doc_idx: Tensor, sliding_window: int, dtype: torch.dtype) -> Tensor:
|
||||
"""Additive `(1, 1, seq_len, seq_len)` mask over query rows and key columns.
|
||||
|
||||
A key is readable when it lies in the query's own document and within the `sliding_window`
|
||||
tokens up to and including the query.
|
||||
|
||||
A padded micro-batch folds its padding into the last document, so the padding is masked as a
|
||||
continuation of the last document. Causality already keeps it away from every real token, and it
|
||||
is loss-masked.
|
||||
"""
|
||||
seq_len = tok_doc_idx.shape[0]
|
||||
device = tok_doc_idx.device
|
||||
tok_idx = torch.arange(seq_len, device=device)
|
||||
|
||||
distance = tok_idx[:, None] - tok_idx[None, :]
|
||||
in_causal_window = (distance >= 0) & (distance < sliding_window)
|
||||
same_document = tok_doc_idx[:, None] == tok_doc_idx[None, :]
|
||||
readable = in_causal_window & same_document
|
||||
|
||||
mask = torch.zeros(seq_len, seq_len, dtype=dtype, device=device)
|
||||
return mask.masked_fill_(~readable, torch.finfo(dtype).min)[None, None]
|
||||
|
||||
|
||||
def block_bias_from_indices(top_k_indices: Tensor, n_entries: int, dtype: torch.dtype) -> Tensor:
|
||||
"""Render the indexer's picks as the dense additive `(batch, 1, seq_len, n_entries)` bias.
|
||||
|
||||
`0` on the selected entries, `-inf` everywhere else. The dense and sparse attention paths
|
||||
both start from the same index tensor, so they cannot disagree about which entries a query
|
||||
reads.
|
||||
"""
|
||||
batch, seq_len, _ = top_k_indices.shape
|
||||
# The `IGNORE_SLOT` (-1) sentinels are scattered into one throwaway column that is sliced back off.
|
||||
safe_indices = torch.where(top_k_indices >= 0, top_k_indices, torch.full_like(top_k_indices, n_entries))
|
||||
block_bias = torch.full((batch, 1, seq_len, n_entries + 1), float("-inf"), dtype=dtype, device=top_k_indices.device)
|
||||
block_bias.scatter_(-1, safe_indices.unsqueeze(1), 0.0)
|
||||
return block_bias[..., :n_entries]
|
||||
|
||||
|
||||
def dense_mask_from_indices(indices: Tensor, n_positions: int, dtype: torch.dtype) -> Tensor:
|
||||
"""Render a gather-index tensor as the dense additive `(batch, 1, seq_len, n_positions)` mask.
|
||||
|
||||
`indices` is the `(batch, seq_len, 1, n_slots)` int32 tensor addressing the position axis of a
|
||||
`kv_buf` with `n_positions` positions. The mask is `0` on every position at least one of a
|
||||
query's slots names and `-inf` everywhere else. A slot holding `IGNORE_SLOT` (-1) marks an absent
|
||||
key and names no position, so it admits nothing.
|
||||
|
||||
This is the fused kernel's oracle. Rendering the index tensor dense and running naive eager
|
||||
attention over the whole `kv_buf` exercises the index contract and the attention math together.
|
||||
"""
|
||||
batch, seq_len, _, _ = indices.shape
|
||||
slots = indices[:, :, 0, :].to(torch.int64).unsqueeze(1)
|
||||
# `scatter_` has no negative indexing, so `IGNORE_SLOT` (-1) goes into one throwaway column that
|
||||
# is sliced back off. Clamping it to a real position instead would admit a key the query cannot read.
|
||||
safe = torch.where(slots >= 0, slots, n_positions)
|
||||
mask = torch.full((batch, 1, seq_len, n_positions + 1), float("-inf"), dtype=dtype, device=indices.device)
|
||||
mask.scatter_(-1, safe, 0.0)
|
||||
return mask[..., :n_positions].contiguous()
|
||||
|
||||
|
||||
def eager_attention_forward(
|
||||
module: DeepseekV4Attention, hidden_states: Tensor, packed: PackedContext
|
||||
) -> tuple[Tensor, None]:
|
||||
"""`DeepseekV4Attention.forward` with a dense softmax where the fused kernel goes.
|
||||
|
||||
The projections and the RoPE are reimplemented rather than called through, so a change to that
|
||||
method has to be mirrored here. The slot layout is not: both consumers read the same
|
||||
`SparseAttnInputs`, which is what makes a disagreement between them one about attention math.
|
||||
"""
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
hidden_shape = (*input_shape, -1, module.head_dim)
|
||||
cos, sin = packed.position_embeddings[module.rope_layer_type]
|
||||
|
||||
q_residual = module.q_a_norm(module.q_a_proj(hidden_states))
|
||||
q = module.q_b_proj(q_residual).view(*hidden_shape).transpose(1, 2)
|
||||
q = apply_rotary_pos_emb_interleaved(module.q_b_norm(q), cos, sin)
|
||||
|
||||
kv = module.kv_norm(module.kv_proj(hidden_states))
|
||||
kv = kv.view(*kv.shape[:2], 1, module.head_dim)
|
||||
kv = apply_rotary_pos_emb_interleaved(kv, cos, sin, unsqueeze_dim=2)
|
||||
if module.cp_context.cp_enabled:
|
||||
kv = dsv4_attention.gather_for_cp(kv, module.cp_context.cp_group)
|
||||
kv = kv.transpose(1, 2)
|
||||
|
||||
compressed = (
|
||||
module.compressor(
|
||||
hidden_states,
|
||||
q_residual,
|
||||
packed,
|
||||
cp_group=module.cp_context.cp_group,
|
||||
cp_world_size=module.cp_context.cp_world_size,
|
||||
)
|
||||
if module.compressor is not None
|
||||
else None
|
||||
)
|
||||
compressed_kv, top_k_indices = compressed if compressed is not None else (None, None)
|
||||
inputs = SparseAttnInputs.build(
|
||||
kv=kv,
|
||||
compressed_kv=compressed_kv,
|
||||
top_k_indices=top_k_indices,
|
||||
window_indices=packed.window_indices,
|
||||
)
|
||||
|
||||
attention_mask = dense_mask_from_indices(inputs.indices, inputs.kv_buf.shape[1], q.dtype)
|
||||
keys = inputs.kv_buf.transpose(1, 2)
|
||||
attn_output = eager_attention_with_sinks(
|
||||
q,
|
||||
keys,
|
||||
keys,
|
||||
module.sinks,
|
||||
attention_mask,
|
||||
scaling=module.scaling,
|
||||
dropout=module.attention_dropout,
|
||||
training=module.training,
|
||||
)
|
||||
|
||||
attn_output = apply_rotary_pos_emb_interleaved(attn_output, cos, -sin, unsqueeze_dim=2)
|
||||
grouped = module.o_a_proj(attn_output.reshape(*input_shape, module.config.o_groups, -1)).flatten(2)
|
||||
return module.o_b_proj(grouped), None
|
||||
|
||||
|
||||
def use_eager_attention(module: nn.Module) -> None:
|
||||
"""Rebind every `DeepseekV4Attention` under `module` to the dense reference consumer.
|
||||
|
||||
`modules()` yields `module` itself, so this covers a lone attention layer as well as a model
|
||||
holding several of them.
|
||||
"""
|
||||
for submodule in module.modules():
|
||||
if isinstance(submodule, DeepseekV4Attention):
|
||||
submodule.forward = types.MethodType(eager_attention_forward, submodule)
|
||||
@@ -78,7 +78,7 @@ class DeepseekV4DecoderLayer(GradientCheckpointingLayer):
|
||||
# Mirrors HF's `_keep_in_fp32_modules_strict`, with `e_score_correction_bias` renamed to
|
||||
# the `selection_bias` prime-rl's router keeps it under. The bare `norm` entry subsumes the
|
||||
# named norms; both are kept so the list stays a one-to-one image of HF's.
|
||||
_KEEP_IN_FP32_MODULES = (
|
||||
KEEP_IN_FP32_MODULES = (
|
||||
"attn_hc",
|
||||
"ffn_hc",
|
||||
"hc_head",
|
||||
@@ -100,11 +100,7 @@ class DeepseekV4PreTrainedModel(PreTrainedModelPrimeRL):
|
||||
supports_gradient_checkpointing = True
|
||||
_no_split_modules = ["DeepseekV4DecoderLayer"]
|
||||
_skip_keys_device_placement = ["past_key_values"]
|
||||
# V4 attention is eager-only, as in HF: FlashAttention caps the head dim at 256 while
|
||||
# V4 uses 512, SDPA carries no per-head sink logit, and FlexAttention's BlockMask
|
||||
# cannot grow to cover the compressed entries the block concatenates onto the KV axis.
|
||||
# `DeepseekV4Attention` reads no dispatch table, so `config._attn_implementation` is
|
||||
# inert here; these flags only keep transformers from advertising a backend we lack.
|
||||
# V4 attention runs its own fused kernel; no transformers backend can serve it.
|
||||
_supports_flash_attn = False
|
||||
_supports_sdpa = False
|
||||
_supports_flex_attn = False
|
||||
@@ -116,9 +112,9 @@ class DeepseekV4PreTrainedModel(PreTrainedModelPrimeRL):
|
||||
@classmethod
|
||||
def cp_support(cls, config) -> CPSupport:
|
||||
return CPSupport(
|
||||
frozenset(),
|
||||
"its sliding window is a dense local mask built from post-shard document boundaries, "
|
||||
"which CP's global (pre-shard) boundaries cannot address",
|
||||
frozenset({"ring"}),
|
||||
"currently only supporting the minimal ring strategy where all keys, or tensors "
|
||||
"required to form the keys are all-gathered in the CP region.",
|
||||
)
|
||||
|
||||
def _init_weights(self, module: nn.Module) -> None:
|
||||
@@ -133,7 +129,7 @@ class DeepseekV4PreTrainedModel(PreTrainedModelPrimeRL):
|
||||
|
||||
@classmethod
|
||||
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
|
||||
return any(module_name in name for module_name in _KEEP_IN_FP32_MODULES)
|
||||
return any(module_name in name for module_name in KEEP_IN_FP32_MODULES)
|
||||
|
||||
@classmethod
|
||||
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
@@ -233,20 +229,27 @@ class DeepseekV4Model(DeepseekV4PreTrainedModel):
|
||||
sliding window at document boundaries and lays out the compressors' entries per
|
||||
document, so a packed row gives every document what running it alone would.
|
||||
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
|
||||
Whether `seq_lens` holds pre-CP-shard (global) document boundaries. Rejected: the
|
||||
window mask is dense and local, so global boundaries cannot address it.
|
||||
Whether `seq_lens` holds pre-CP-shard (global) document boundaries. V4 shards the
|
||||
queries alone and keeps every key, entry and index value global, so it needs the
|
||||
whole row's boundaries: this must be set exactly when context parallelism is on.
|
||||
"""
|
||||
if (input_ids is None) ^ (inputs_embeds is not None):
|
||||
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
||||
if seq_lens_are_pre_shard:
|
||||
raise NotImplementedError(
|
||||
"DeepSeek V4 does not support context parallelism: pre-shard document boundaries "
|
||||
"do not address the local sliding-window mask."
|
||||
)
|
||||
assert (input_ids is None) != (inputs_embeds is None), "pass exactly one of input_ids or inputs_embeds"
|
||||
|
||||
cp_rank, cp_world_size = self.cp_context.cp_rank, self.cp_context.cp_world_size
|
||||
assert seq_lens_are_pre_shard == (cp_world_size > 1), (
|
||||
f"seq_lens_are_pre_shard={seq_lens_are_pre_shard} disagrees with cp_world_size={cp_world_size}"
|
||||
)
|
||||
|
||||
if inputs_embeds is None:
|
||||
inputs_embeds = self.embed_tokens(input_ids)
|
||||
|
||||
# `seq_lens` describes the whole row and `inputs_embeds` carries this rank's shard of it.
|
||||
total_tokens = int(seq_lens.sum())
|
||||
assert total_tokens == inputs_embeds.shape[1] * cp_world_size, (
|
||||
f"seq_lens covers {total_tokens} tokens, but {cp_world_size} CP rank(s) holding "
|
||||
f"{inputs_embeds.shape[1]} tokens each"
|
||||
)
|
||||
|
||||
# Every layer type attends over the same local window; the compressed variants add their
|
||||
# own out-of-window entries and the per-query bias that gates them. One layout per distinct
|
||||
# compress rate, shared by every layer that pools at that rate; sliding layers own no
|
||||
@@ -256,6 +259,8 @@ class DeepseekV4Model(DeepseekV4PreTrainedModel):
|
||||
seq_lens=seq_lens,
|
||||
dtype=inputs_embeds.dtype,
|
||||
device=inputs_embeds.device,
|
||||
cp_rank=cp_rank,
|
||||
cp_world_size=cp_world_size,
|
||||
)
|
||||
if position_ids is not None:
|
||||
packed.check_position_ids(position_ids)
|
||||
|
||||
@@ -9,7 +9,7 @@ from prime_rl.trainer.models.deepseek_v4.configuration_deepseek_v4 import Deepse
|
||||
# The rope types whose inverse frequencies are fixed once computed. The two left out,
|
||||
# `dynamic` and `longrope`, rescale theirs per forward against the running sequence length,
|
||||
# which the buffers below, written once in `__init__`, never do.
|
||||
_SUPPORTED_ROPE_TYPES = frozenset({"default", "linear", "llama3", "proportional", "yarn"})
|
||||
SUPPORTED_ROPE_TYPES = frozenset({"default", "linear", "llama3", "proportional", "yarn"})
|
||||
|
||||
|
||||
def rotate_half_interleaved(x: torch.Tensor) -> torch.Tensor:
|
||||
@@ -63,7 +63,7 @@ class DeepseekV4RotaryEmbedding(nn.Module):
|
||||
|
||||
`rope_type` is checkpoint data rather than architecture: V4 ships `default` on `main` and
|
||||
`default` or `yarn` on `compress`, but the config reads whatever the file says. Anything
|
||||
outside `_SUPPORTED_ROPE_TYPES` is refused at construction, rather than rotating at
|
||||
outside `SUPPORTED_ROPE_TYPES` is refused at construction, rather than rotating at
|
||||
frequencies that were meant to be rescaled and never were.
|
||||
"""
|
||||
|
||||
@@ -78,10 +78,10 @@ class DeepseekV4RotaryEmbedding(nn.Module):
|
||||
self.rope_type: dict[str, str] = {}
|
||||
for layer_type in self.layer_types:
|
||||
self.rope_type[layer_type] = config.rope_parameters[layer_type]["rope_type"]
|
||||
if self.rope_type[layer_type] not in _SUPPORTED_ROPE_TYPES:
|
||||
if self.rope_type[layer_type] not in SUPPORTED_ROPE_TYPES:
|
||||
raise ValueError(
|
||||
f"rope type {self.rope_type[layer_type]!r} on {layer_type!r} is not supported; "
|
||||
f"the supported types are {sorted(_SUPPORTED_ROPE_TYPES)}, whose inverse "
|
||||
f"the supported types are {sorted(SUPPORTED_ROPE_TYPES)}, whose inverse "
|
||||
"frequencies are computed once here and never rescaled per forward"
|
||||
)
|
||||
inv_freq, attention_scaling = self._rope_init_fn(layer_type)(config, device, layer_type=layer_type)
|
||||
|
||||
@@ -0,0 +1,312 @@
|
||||
from collections.abc import Callable, Iterator, Sequence
|
||||
from typing import Any, NamedTuple
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from torch.distributed.tensor import Shard
|
||||
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.weights import resolve_fqn
|
||||
|
||||
# Replaces some of a module's parameters with a packed one. Advertised by modules
|
||||
# through their ``supported_fusions``.
|
||||
RuntimeFusion = Callable[[nn.Module], None]
|
||||
|
||||
|
||||
class PackedParameterSpec:
|
||||
"""One physical parameter packing several logical parameters along a dimension.
|
||||
|
||||
Training allocates, computes on, and optimizes the packed parameter. The logical
|
||||
parameters keep their canonical names in checkpoints. They alias the packed storage
|
||||
unless the parameter is a DTensor sharded along the packing dimension, where a split
|
||||
has to redistribute and yields copies instead.
|
||||
|
||||
``name`` and ``logical_names`` are relative to the module the packing is registered
|
||||
on, and may name parameters of its children. ``dim`` is a non-negative dimension
|
||||
index into the packed parameter.
|
||||
"""
|
||||
|
||||
def __init__(self, name: str, logical_names: Sequence[str], sizes: Sequence[int], dim: int):
|
||||
self.name = name
|
||||
self.logical_names = tuple(logical_names)
|
||||
self.sizes = tuple(sizes)
|
||||
self.dim = dim
|
||||
|
||||
def split_into_logical_views(self, tensor: torch.Tensor) -> tuple[torch.Tensor, ...]:
|
||||
"""The logical parameters, in ``logical_names`` order, as views of ``tensor``."""
|
||||
return tensor.split(self.sizes, dim=self.dim)
|
||||
|
||||
def pack_logical_tensors(self, tensors: Sequence[torch.Tensor]) -> torch.Tensor:
|
||||
return torch.cat(list(tensors), dim=self.dim)
|
||||
|
||||
def muon_matrix_partitions(self, parameter: torch.Tensor) -> tuple[int, ...] | None:
|
||||
"""Muon's partition sizes, or None when the packing is not on the output dimension."""
|
||||
return self.sizes if self.dim == parameter.ndim - 2 else None
|
||||
|
||||
|
||||
def register_packed_parameter_state_dict_hooks(module: nn.Module, spec: PackedParameterSpec) -> None:
|
||||
"""Record a packed parameter and keep the module's state dict in canonical form.
|
||||
|
||||
The hooks below trade the packed entry for its canonical ones on the way out and
|
||||
back again on the way in, so checkpoints never see the packed layout. Torch stamps
|
||||
an attribute onto every hook it registers, so these have to be plain functions.
|
||||
"""
|
||||
|
||||
def split_packed_entry_into_logical_entries(module, state_dict, prefix, local_metadata) -> None:
|
||||
views = spec.split_into_logical_views(state_dict.pop(f"{prefix}{spec.name}"))
|
||||
for logical_name, view in zip(spec.logical_names, views):
|
||||
state_dict[f"{prefix}{logical_name}"] = view
|
||||
|
||||
def join_logical_entries_into_packed_entry(module, state_dict, prefix, *load_state_dict_args) -> None:
|
||||
state_dict[f"{prefix}{spec.name}"] = spec.pack_logical_tensors(
|
||||
[state_dict.pop(f"{prefix}{logical_name}") for logical_name in spec.logical_names]
|
||||
)
|
||||
|
||||
module.packed_parameter_specs = (*getattr(module, "packed_parameter_specs", ()), spec)
|
||||
module.register_state_dict_post_hook(split_packed_entry_into_logical_entries)
|
||||
module.register_load_state_dict_pre_hook(join_logical_entries_into_packed_entry)
|
||||
|
||||
|
||||
def fuse_gate_up_projections(module: nn.Module) -> None:
|
||||
"""Pack a gated expert's gate and up projections into one grouped-GEMM weight.
|
||||
|
||||
The packed weight is ``[num_experts, 2 * hidden_dim, dim]``, so the forward path is a
|
||||
single grouped GEMM whose transpose and chunk are views.
|
||||
"""
|
||||
spec = PackedParameterSpec("gate_up_proj", ("gate_proj", "up_proj"), (module.hidden_dim, module.hidden_dim), dim=1)
|
||||
module.gate_up_proj = nn.Parameter(
|
||||
spec.pack_logical_tensors([module.gate_proj, module.up_proj]),
|
||||
requires_grad=module.gate_proj.requires_grad,
|
||||
)
|
||||
module.gate_proj = None
|
||||
module.up_proj = None
|
||||
register_packed_parameter_state_dict_hooks(module, spec)
|
||||
|
||||
|
||||
def fuse_qkv_projections(module: nn.Module) -> None:
|
||||
"""Pack an attention module's query, key and value projections into one linear layer.
|
||||
|
||||
The packed weight is ``[q_size + k_size + v_size, hidden_size]``, so the projections
|
||||
become a single GEMM whose output is split along the last dimension.
|
||||
"""
|
||||
projections = {"q_proj": module.q_proj, "k_proj": module.k_proj, "v_proj": module.v_proj}
|
||||
sizes = tuple(projection.out_features for projection in projections.values())
|
||||
has_bias = module.q_proj.bias is not None
|
||||
|
||||
# Built on meta so the packed parameters assigned below are the only allocation
|
||||
qkv_proj = nn.Linear(module.q_proj.in_features, sum(sizes), bias=has_bias, device="meta")
|
||||
for parameter_name in ("weight", "bias") if has_bias else ("weight",):
|
||||
spec = PackedParameterSpec(
|
||||
f"qkv_proj.{parameter_name}",
|
||||
[f"{name}.{parameter_name}" for name in projections],
|
||||
sizes,
|
||||
dim=0,
|
||||
)
|
||||
tensors = [getattr(projection, parameter_name) for projection in projections.values()]
|
||||
setattr(
|
||||
qkv_proj,
|
||||
parameter_name,
|
||||
nn.Parameter(spec.pack_logical_tensors(tensors), requires_grad=tensors[0].requires_grad),
|
||||
)
|
||||
register_packed_parameter_state_dict_hooks(module, spec)
|
||||
|
||||
module.qkv_proj = qkv_proj
|
||||
# The projections stay in place, emptied. DCP resolves every checkpoint key by
|
||||
# attribute traversal, so the canonical q/k/v names still need a module to land on.
|
||||
for projection in projections.values():
|
||||
projection.weight = None
|
||||
projection.bias = None
|
||||
|
||||
|
||||
def apply_model_fusions(
|
||||
model: nn.Module, requested_fusions: Sequence[str], raise_on_fail: bool = True
|
||||
) -> 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:
|
||||
num_fused_modules = 0
|
||||
for module in model.modules():
|
||||
fusion: RuntimeFusion | None = getattr(module, "supported_fusions", {}).get(fusion_name)
|
||||
if fusion is None:
|
||||
continue
|
||||
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")
|
||||
continue
|
||||
fused_module_counts[fusion_name] = num_fused_modules
|
||||
return fused_module_counts
|
||||
|
||||
|
||||
def join_module_path(module_path: str, name: str) -> str:
|
||||
"""Join a module path and a name, tolerating the empty path of the root module."""
|
||||
return f"{module_path}.{name}" if module_path else name
|
||||
|
||||
|
||||
class PackedParameterInfo(NamedTuple):
|
||||
fqn: str
|
||||
"""Fully qualified name of the packed parameter."""
|
||||
|
||||
logical_fqns: tuple[str, ...]
|
||||
"""Fully qualified canonical names of the parameters it packs, in packing order."""
|
||||
|
||||
parameter: nn.Parameter
|
||||
spec: PackedParameterSpec
|
||||
|
||||
|
||||
def get_model_packed_parameters(model: nn.Module) -> Iterator[PackedParameterInfo]:
|
||||
"""Yield every packed parameter in the model with the canonical names it stands in for."""
|
||||
for module_path, module in model.named_modules():
|
||||
for spec in getattr(module, "packed_parameter_specs", ()):
|
||||
fqn = resolve_fqn(model, join_module_path(module_path, spec.name))
|
||||
prefix = fqn.removesuffix(spec.name)
|
||||
yield PackedParameterInfo(
|
||||
fqn=fqn,
|
||||
logical_fqns=tuple(f"{prefix}{logical_name}" for logical_name in spec.logical_names),
|
||||
parameter=module.get_parameter(spec.name),
|
||||
spec=spec,
|
||||
)
|
||||
|
||||
|
||||
def get_fsdp_shard_placement_fn(model: nn.Module) -> Callable[[nn.Parameter], Shard | None]:
|
||||
"""FSDP placement that keeps every packed parameter's packing dimension unsharded.
|
||||
|
||||
Splitting a DTensor along an unsharded dimension is a local view, so the canonical
|
||||
state-dict entries alias the packed storage instead of being replicated copies. FSDP's
|
||||
default ``Shard(0)`` is kept for everything else, including parameters packed along
|
||||
dim 0 that have no other dimension to shard.
|
||||
"""
|
||||
packing_dim_by_param_id = {
|
||||
id(packed_info.parameter): packed_info.spec.dim for packed_info in get_model_packed_parameters(model)
|
||||
}
|
||||
|
||||
def shard_placement_fn(parameter: nn.Parameter) -> Shard | None:
|
||||
if packing_dim_by_param_id.get(id(parameter)) == 0 and parameter.ndim > 1:
|
||||
return Shard(1)
|
||||
return None
|
||||
|
||||
return shard_placement_fn
|
||||
|
||||
|
||||
def write_back_loaded_packed_parameters(model: nn.Module, state_dict: dict[str, torch.Tensor]) -> None:
|
||||
"""Write the logical entries of a state dict loaded in place back into the packed parameters.
|
||||
|
||||
Loading into ``model.state_dict()`` in place only reaches a packed parameter through
|
||||
entries that alias it, so the entries that are copies are packed and written back here.
|
||||
"""
|
||||
with torch.no_grad():
|
||||
for packed_info in get_model_packed_parameters(model):
|
||||
packed_info.parameter.copy_(
|
||||
packed_info.spec.pack_logical_tensors([state_dict[fqn] for fqn in packed_info.logical_fqns])
|
||||
)
|
||||
|
||||
|
||||
def split_packed_optimizer_state_for_checkpoint(model: nn.Module, state_dict: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Expose packed optimizer tensors under their logical names for DCP."""
|
||||
# DCP returns {} when no optimizers are supplied, including model-only loads.
|
||||
if not state_dict:
|
||||
return state_dict
|
||||
packed_infos = list(get_model_packed_parameters(model))
|
||||
if not packed_infos:
|
||||
return state_dict
|
||||
|
||||
checkpoint_state_dict = dict(state_dict)
|
||||
checkpoint_state_dict["state"] = dict(state_dict["state"])
|
||||
checkpoint_state_dict["param_groups"] = [
|
||||
{**group, "params": list(group["params"])} for group in state_dict["param_groups"]
|
||||
]
|
||||
|
||||
for packed_info in packed_infos:
|
||||
if packed_info.fqn in checkpoint_state_dict["state"]:
|
||||
packed_param_state = checkpoint_state_dict["state"].pop(packed_info.fqn)
|
||||
logical_param_states: dict[str, dict[str, Any]] = {fqn: {} for fqn in packed_info.logical_fqns}
|
||||
for state_key, value in packed_param_state.items():
|
||||
if isinstance(value, torch.Tensor) and value.shape == packed_info.parameter.shape:
|
||||
for fqn, logical_view in zip(
|
||||
packed_info.logical_fqns, packed_info.spec.split_into_logical_views(value)
|
||||
):
|
||||
logical_param_states[fqn][state_key] = logical_view
|
||||
else:
|
||||
for logical_param_state in logical_param_states.values():
|
||||
logical_param_state[state_key] = value
|
||||
checkpoint_state_dict["state"].update(logical_param_states)
|
||||
|
||||
for group in checkpoint_state_dict["param_groups"]:
|
||||
param_fqns = []
|
||||
for param_fqn in group["params"]:
|
||||
param_fqns.extend(packed_info.logical_fqns if param_fqn == packed_info.fqn else [param_fqn])
|
||||
group["params"] = param_fqns
|
||||
|
||||
return checkpoint_state_dict
|
||||
|
||||
|
||||
def write_back_loaded_packed_optimizer_state(
|
||||
model: nn.Module, optimizers: Sequence[torch.optim.Optimizer], checkpoint_state_dict: dict[str, Any]
|
||||
) -> None:
|
||||
"""Pack the logical optimizer state DCP loaded in place into the optimizers' live state."""
|
||||
packed_infos = {id(packed_info.parameter): packed_info for packed_info in get_model_packed_parameters(model)}
|
||||
with torch.no_grad():
|
||||
for optimizer in optimizers:
|
||||
for parameter, state in optimizer.state.items():
|
||||
packed_info = packed_infos.get(id(parameter))
|
||||
if packed_info is None:
|
||||
continue
|
||||
logical_param_states = [checkpoint_state_dict["state"][fqn] for fqn in packed_info.logical_fqns]
|
||||
for state_key, value in state.items():
|
||||
loaded_value = logical_param_states[0][state_key]
|
||||
if isinstance(value, torch.Tensor) and value.shape == packed_info.parameter.shape:
|
||||
loaded_value = packed_info.spec.pack_logical_tensors(
|
||||
[logical_param_state[state_key] for logical_param_state in logical_param_states]
|
||||
)
|
||||
if isinstance(value, torch.Tensor):
|
||||
value.copy_(loaded_value)
|
||||
else:
|
||||
state[state_key] = loaded_value
|
||||
|
||||
|
||||
def join_loaded_optimizer_state_for_runtime(
|
||||
model: nn.Module,
|
||||
checkpoint_state_dict: dict[str, Any],
|
||||
runtime_state_dict: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""Pack the logical optimizer state DCP loaded back into the runtime optimizer state."""
|
||||
if not checkpoint_state_dict:
|
||||
return checkpoint_state_dict
|
||||
packed_infos = list(get_model_packed_parameters(model))
|
||||
if not packed_infos:
|
||||
return checkpoint_state_dict
|
||||
|
||||
restored_state_dict = dict(runtime_state_dict)
|
||||
restored_state_dict["state"] = dict(runtime_state_dict["state"])
|
||||
restored_state_dict["param_groups"] = [
|
||||
{**group, "params": list(group["params"])} for group in checkpoint_state_dict["param_groups"]
|
||||
]
|
||||
|
||||
for packed_info in packed_infos:
|
||||
if packed_info.fqn in restored_state_dict["state"]:
|
||||
packed_param_state = restored_state_dict["state"][packed_info.fqn]
|
||||
logical_param_states = [checkpoint_state_dict["state"][fqn] for fqn in packed_info.logical_fqns]
|
||||
first_logical_view = packed_info.spec.split_into_logical_views(packed_info.parameter)[0]
|
||||
for state_key, value in logical_param_states[0].items():
|
||||
if isinstance(value, torch.Tensor) and value.shape == first_logical_view.shape:
|
||||
with torch.no_grad():
|
||||
packed_param_state[state_key].copy_(
|
||||
packed_info.spec.pack_logical_tensors(
|
||||
[logical_param_state[state_key] for logical_param_state in logical_param_states]
|
||||
)
|
||||
)
|
||||
else:
|
||||
packed_param_state[state_key] = value
|
||||
|
||||
for group in restored_state_dict["param_groups"]:
|
||||
param_fqns = group["params"]
|
||||
if packed_info.logical_fqns[0] not in param_fqns:
|
||||
continue
|
||||
first_logical_index = min(param_fqns.index(fqn) for fqn in packed_info.logical_fqns)
|
||||
group["params"] = [fqn for fqn in param_fqns if fqn not in packed_info.logical_fqns]
|
||||
group["params"].insert(first_logical_index, packed_info.fqn)
|
||||
|
||||
return restored_state_dict
|
||||
@@ -90,12 +90,6 @@ class GlmMoeDsaDecoderLayer(GradientCheckpointingLayer):
|
||||
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
|
||||
def set_context_parallel_attributes(self, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
|
||||
self._cp_group = cp_group
|
||||
self._cp_rank = cp_rank
|
||||
self._cp_world_size = cp_world_size
|
||||
self.self_attn.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
|
||||
|
||||
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
||||
def forward(
|
||||
self,
|
||||
@@ -192,13 +186,6 @@ class GlmMoeDsaModel(GlmMoeDsaPreTrainedModel):
|
||||
|
||||
self.post_init()
|
||||
|
||||
def _context_parallel_state(self) -> tuple[dist.ProcessGroup | None, int, int]:
|
||||
if len(self.layers) == 0:
|
||||
return None, 0, 1
|
||||
|
||||
layer = self.layers[0]
|
||||
return getattr(layer, "_cp_group", None), getattr(layer, "_cp_rank", 0), getattr(layer, "_cp_world_size", 1)
|
||||
|
||||
def _gather_position_ids_for_cp(
|
||||
self,
|
||||
position_ids: torch.LongTensor,
|
||||
@@ -234,9 +221,9 @@ class GlmMoeDsaModel(GlmMoeDsaPreTrainedModel):
|
||||
if inputs_embeds is None:
|
||||
inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
|
||||
|
||||
cp_group, cp_rank, cp_world_size = self._context_parallel_state()
|
||||
if cp_group is not None and cp_world_size > 1:
|
||||
position_ids_full = self._gather_position_ids_for_cp(position_ids, cp_group, cp_world_size)
|
||||
cp_rank, cp_world_size = self.cp_context.cp_rank, self.cp_context.cp_world_size
|
||||
if self.cp_context.cp_enabled:
|
||||
position_ids_full = self._gather_position_ids_for_cp(position_ids, self.cp_context.cp_group, cp_world_size)
|
||||
else:
|
||||
position_ids_full = position_ids
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ from torch import nn
|
||||
from prime_rl.trainer.models.kernels.fp8_indexer import fp8_indexer
|
||||
from prime_rl.trainer.models.layers.norms import LayerNorm, RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import rotate_half
|
||||
from prime_rl.utils.cp import gather_for_cp
|
||||
from prime_rl.utils.cp import CPContext, gather_for_cp
|
||||
|
||||
try:
|
||||
from prime_rl.trainer.models.kernels.sparse_mla_fwd import sparse_mla
|
||||
@@ -145,18 +145,7 @@ class GlmMoeDsaAttention(nn.Module):
|
||||
self.skip_topk = args.skip_topk
|
||||
self.scaling = self.qk_head_dim ** (-0.5)
|
||||
|
||||
self._cp_group: dist.ProcessGroup | None = None
|
||||
self._cp_rank: int = 0
|
||||
self._cp_world_size: int = 1
|
||||
|
||||
def set_context_parallel_attributes(self, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
|
||||
self._cp_group = cp_group
|
||||
self._cp_rank = cp_rank
|
||||
self._cp_world_size = cp_world_size
|
||||
|
||||
@property
|
||||
def cp_enabled(self) -> bool:
|
||||
return self._cp_world_size > 1
|
||||
self.cp_context = CPContext()
|
||||
|
||||
def mla_latents(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
q_latent = self.q_a_layernorm(self.q_a_proj(hidden_states))
|
||||
@@ -178,9 +167,10 @@ class GlmMoeDsaAttention(nn.Module):
|
||||
q_nope, q_rope = q_full.split([self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
|
||||
|
||||
cos_full, sin_full = position_embeddings_full
|
||||
if self.cp_enabled:
|
||||
cos_local = cos_full[:, self._cp_rank * s_local : (self._cp_rank + 1) * s_local, :]
|
||||
sin_local = sin_full[:, self._cp_rank * s_local : (self._cp_rank + 1) * s_local, :]
|
||||
if self.cp_context.cp_enabled:
|
||||
cp_rank = self.cp_context.cp_rank
|
||||
cos_local = cos_full[:, cp_rank * s_local : (cp_rank + 1) * s_local, :]
|
||||
sin_local = sin_full[:, cp_rank * s_local : (cp_rank + 1) * s_local, :]
|
||||
else:
|
||||
cos_local, sin_local = cos_full, sin_full
|
||||
|
||||
@@ -215,9 +205,9 @@ class GlmMoeDsaAttention(nn.Module):
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
q_latent, k_compressed_normed, k_rope = self.mla_latents(hidden_states)
|
||||
|
||||
if self.cp_enabled:
|
||||
k_compressed_normed = gather_for_cp(k_compressed_normed, self._cp_group)
|
||||
k_rope = gather_for_cp(k_rope, self._cp_group)
|
||||
if self.cp_context.cp_enabled:
|
||||
k_compressed_normed = gather_for_cp(k_compressed_normed, self.cp_context.cp_group)
|
||||
k_rope = gather_for_cp(k_rope, self.cp_context.cp_group)
|
||||
|
||||
indices = cached_indices
|
||||
if not self.skip_topk:
|
||||
@@ -228,9 +218,9 @@ class GlmMoeDsaAttention(nn.Module):
|
||||
ke=ke,
|
||||
index_topk=self.args.index_topk,
|
||||
position_embeddings_full=position_embeddings,
|
||||
cp_group=self._cp_group,
|
||||
cp_world_size=self._cp_world_size,
|
||||
cp_rank=self._cp_rank,
|
||||
cp_group=self.cp_context.cp_group,
|
||||
cp_world_size=self.cp_context.cp_world_size,
|
||||
cp_rank=self.cp_context.cp_rank,
|
||||
)
|
||||
|
||||
sparse_q, sparse_kv, w_v = self.mla_up_proj(
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
"""GPT-OSS attention and context-parallel execution.
|
||||
|
||||
Learned sink logits are model parameters, not an attention-backend option. GPT-OSS
|
||||
therefore owns its FA4 call and shards each sink with the corresponding query heads
|
||||
in its ring and Ulysses paths.
|
||||
"""
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.trainer.models.fusions import fuse_qkv_projections
|
||||
from prime_rl.trainer.models.gpt_oss.configuration_gpt_oss import GptOssConfig
|
||||
from prime_rl.trainer.models.layers.attn import flash_attn_4_varlen_func
|
||||
from prime_rl.trainer.models.layers.rotary_emb import apply_rotary_pos_emb
|
||||
|
||||
|
||||
class GptOssAttention(nn.Module):
|
||||
supported_fusions = {"qkv": fuse_qkv_projections}
|
||||
|
||||
def __init__(self, config: GptOssConfig, layer_idx: int) -> None:
|
||||
super().__init__()
|
||||
self.head_dim = config.head_dim
|
||||
self.num_attention_heads = config.num_attention_heads
|
||||
self.num_key_value_heads = config.num_key_value_heads
|
||||
self.scaling = self.head_dim**-0.5
|
||||
self.sliding_window = config.sliding_window if config.layer_types[layer_idx] == "sliding_attention" else None
|
||||
|
||||
self.q_proj = nn.Linear(
|
||||
config.hidden_size,
|
||||
config.num_attention_heads * config.head_dim,
|
||||
bias=config.attention_bias,
|
||||
)
|
||||
self.k_proj = nn.Linear(
|
||||
config.hidden_size,
|
||||
config.num_key_value_heads * config.head_dim,
|
||||
bias=config.attention_bias,
|
||||
)
|
||||
self.v_proj = nn.Linear(
|
||||
config.hidden_size,
|
||||
config.num_key_value_heads * config.head_dim,
|
||||
bias=config.attention_bias,
|
||||
)
|
||||
self.qkv_sizes = (self.q_proj.out_features, self.k_proj.out_features, self.v_proj.out_features)
|
||||
self.register_module("qkv_proj", None)
|
||||
self.o_proj = nn.Linear(
|
||||
config.num_attention_heads * config.head_dim,
|
||||
config.hidden_size,
|
||||
bias=config.attention_bias,
|
||||
)
|
||||
self.sinks = nn.Parameter(torch.empty(config.num_attention_heads))
|
||||
nn.init.normal_(self.sinks, mean=0.0, std=config.initializer_range)
|
||||
self.flash_attn = flash_attn_4_varlen_func
|
||||
|
||||
def compute_attention(
|
||||
self,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
cu_seqlens: torch.Tensor,
|
||||
max_seqlen: int,
|
||||
) -> torch.Tensor:
|
||||
window_size = (self.sliding_window - 1, 0) if self.sliding_window is not None else (None, None)
|
||||
output, _ = self.flash_attn(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
cu_seqlens_q=cu_seqlens,
|
||||
cu_seqlens_k=cu_seqlens,
|
||||
max_seqlen_q=max_seqlen,
|
||||
max_seqlen_k=max_seqlen,
|
||||
softmax_scale=self.scaling,
|
||||
causal=True,
|
||||
window_size=window_size,
|
||||
learnable_sink=self.sinks,
|
||||
)
|
||||
return output
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
cu_seqlens: torch.Tensor,
|
||||
max_seqlen: int,
|
||||
) -> torch.Tensor:
|
||||
batch_size, sequence_length, _ = hidden_states.shape
|
||||
if self.qkv_proj is None:
|
||||
query, key, value = self.q_proj(hidden_states), self.k_proj(hidden_states), self.v_proj(hidden_states)
|
||||
else:
|
||||
query, key, value = self.qkv_proj(hidden_states).split(self.qkv_sizes, dim=-1)
|
||||
query = query.view(batch_size, sequence_length, self.num_attention_heads, self.head_dim)
|
||||
key = key.view(batch_size, sequence_length, self.num_key_value_heads, self.head_dim)
|
||||
value = value.view(batch_size, sequence_length, self.num_key_value_heads, self.head_dim)
|
||||
|
||||
cos, sin = position_embeddings
|
||||
query, key = apply_rotary_pos_emb(
|
||||
query.transpose(1, 2),
|
||||
key.transpose(1, 2),
|
||||
cos,
|
||||
sin,
|
||||
)
|
||||
query = query.transpose(1, 2)
|
||||
key = key.transpose(1, 2)
|
||||
|
||||
output = self.compute_attention(query[0], key[0], value[0], cu_seqlens, max_seqlen)
|
||||
return self.o_proj(output.contiguous().view(batch_size, sequence_length, -1))
|
||||
|
||||
|
||||
def substitute_gpt_oss_ring_attention(
|
||||
process_group: torch.distributed.ProcessGroup,
|
||||
heads_k_stride: int,
|
||||
) -> None:
|
||||
from ring_flash_attn.adapters.hf_adapter import DATA_PARAMS
|
||||
|
||||
from prime_rl.trainer.distributed.collectives import all_gather
|
||||
|
||||
def ring_attention(self, query, key, value, _cu_seqlens, _max_seqlen):
|
||||
key_value_groups = self.num_attention_heads // self.num_key_value_heads
|
||||
local_k_slice = DATA_PARAMS["local_k_slice"]
|
||||
window_size = (self.sliding_window - 1, 0) if self.sliding_window is not None else (None, None)
|
||||
outputs = []
|
||||
|
||||
for key_head_start in range(0, self.num_key_value_heads, heads_k_stride):
|
||||
key_head_stop = min(key_head_start + heads_k_stride, self.num_key_value_heads)
|
||||
query_head_start = key_head_start * key_value_groups
|
||||
query_head_stop = key_head_stop * key_value_groups
|
||||
|
||||
gathered_key = all_gather(key[:, key_head_start:key_head_stop], 0, process_group)[local_k_slice]
|
||||
gathered_value = all_gather(value[:, key_head_start:key_head_stop], 0, process_group)[local_k_slice]
|
||||
output, _ = self.flash_attn(
|
||||
query[:, query_head_start:query_head_stop],
|
||||
gathered_key,
|
||||
gathered_value,
|
||||
cu_seqlens_q=DATA_PARAMS["cu_seqlens_q"],
|
||||
cu_seqlens_k=DATA_PARAMS["cu_seqlens_k"],
|
||||
max_seqlen_q=DATA_PARAMS["max_seqlen_q"],
|
||||
max_seqlen_k=DATA_PARAMS["max_seqlen_k"],
|
||||
softmax_scale=self.scaling,
|
||||
causal=True,
|
||||
window_size=window_size,
|
||||
learnable_sink=self.sinks[query_head_start:query_head_stop],
|
||||
)
|
||||
outputs.append(output)
|
||||
|
||||
return torch.cat(outputs, dim=1)
|
||||
|
||||
GptOssAttention.compute_attention = ring_attention
|
||||
|
||||
|
||||
def substitute_gpt_oss_ulysses_attention(process_group: torch.distributed.ProcessGroup) -> None:
|
||||
from prime_rl.trainer.models.layers.ulysses_attn import ULYSSES_PARAMS, ulysses_flash_attn_varlen_func
|
||||
|
||||
cp_size = torch.distributed.get_world_size(process_group)
|
||||
|
||||
def ulysses_attention(self, query, key, value, _cu_seqlens, _max_seqlen):
|
||||
window_size = (self.sliding_window - 1, 0) if self.sliding_window is not None else (-1, -1)
|
||||
return ulysses_flash_attn_varlen_func(
|
||||
self.flash_attn,
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
cu_seqlens_q=ULYSSES_PARAMS["cu_seqlens"],
|
||||
cu_seqlens_k=ULYSSES_PARAMS["cu_seqlens"],
|
||||
max_seqlen_q=ULYSSES_PARAMS["max_seqlen"],
|
||||
max_seqlen_k=ULYSSES_PARAMS["max_seqlen"],
|
||||
causal=True,
|
||||
cp_group=process_group,
|
||||
cp_size=cp_size,
|
||||
flash_attn_version=4,
|
||||
window_size=window_size,
|
||||
softmax_scale=self.scaling,
|
||||
learnable_sink=self.sinks,
|
||||
)
|
||||
|
||||
GptOssAttention.compute_attention = ulysses_attention
|
||||
|
||||
|
||||
__all__ = [
|
||||
"GptOssAttention",
|
||||
"substitute_gpt_oss_ring_attention",
|
||||
"substitute_gpt_oss_ulysses_attention",
|
||||
]
|
||||
@@ -1,6 +1,112 @@
|
||||
# Re-export HF's GptOssConfig so the parameter naming and rope/sliding-window defaults
|
||||
# stay in sync with upstream. We don't need to subclass it: the only PrimeRL-specific
|
||||
# behavior lives in the model and checkpoint conversion modules.
|
||||
from transformers.models.gpt_oss.configuration_gpt_oss import GptOssConfig
|
||||
from transformers.configuration_utils import PretrainedConfig
|
||||
|
||||
|
||||
class GptOssConfig(PretrainedConfig):
|
||||
model_type = "gpt_oss"
|
||||
attribute_map = {"num_experts": "num_local_experts"}
|
||||
|
||||
base_model_tp_plan = {
|
||||
"layers.*.self_attn.q_proj": "colwise",
|
||||
"layers.*.self_attn.k_proj": "colwise",
|
||||
"layers.*.self_attn.v_proj": "colwise",
|
||||
"layers.*.self_attn.o_proj": "rowwise",
|
||||
"layers.*.mlp.experts.gate_proj": "colwise",
|
||||
"layers.*.mlp.experts.up_proj": "colwise",
|
||||
"layers.*.mlp.experts.down_proj": "rowwise",
|
||||
}
|
||||
base_model_pp_plan = {
|
||||
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
||||
"layers": (["hidden_states"], ["hidden_states"]),
|
||||
"norm": (["hidden_states"], ["hidden_states"]),
|
||||
}
|
||||
base_model_ep_plan = {
|
||||
"layers.*.mlp.router": "ep_router",
|
||||
"layers.*.mlp.experts.gate_proj": "grouped_gemm",
|
||||
"layers.*.mlp.experts.gate_proj_bias": "grouped_gemm",
|
||||
"layers.*.mlp.experts.up_proj": "grouped_gemm",
|
||||
"layers.*.mlp.experts.up_proj_bias": "grouped_gemm",
|
||||
"layers.*.mlp.experts.down_proj": "grouped_gemm",
|
||||
"layers.*.mlp.experts.down_proj_bias": "grouped_gemm",
|
||||
"layers.*.mlp.experts": "moe_tp_experts",
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vocab_size: int = 201088,
|
||||
hidden_size: int = 2880,
|
||||
intermediate_size: int = 2880,
|
||||
num_hidden_layers: int = 36,
|
||||
num_attention_heads: int = 64,
|
||||
num_key_value_heads: int = 8,
|
||||
head_dim: int = 64,
|
||||
num_local_experts: int = 128,
|
||||
num_experts_per_tok: int = 4,
|
||||
hidden_act: str = "silu",
|
||||
swiglu_limit: float = 7.0,
|
||||
max_position_embeddings: int = 131072,
|
||||
initial_context_length: int = 4096,
|
||||
sliding_window: int | None = 128,
|
||||
layer_types: list[str] | None = None,
|
||||
rope_theta: float = 150000.0,
|
||||
rope_scaling: dict | None = None,
|
||||
rope_parameters: dict | None = None,
|
||||
rms_norm_eps: float = 1e-5,
|
||||
attention_bias: bool = True,
|
||||
attention_dropout: float = 0.0,
|
||||
initializer_range: float = 0.02,
|
||||
router_aux_loss_coef: float = 0.001,
|
||||
output_router_logits: bool = False,
|
||||
use_cache: bool = True,
|
||||
pad_token_id: int | None = None,
|
||||
bos_token_id: int | None = None,
|
||||
eos_token_id: int | list[int] | None = None,
|
||||
tie_word_embeddings: bool = False,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
self.vocab_size = vocab_size
|
||||
self.hidden_size = hidden_size
|
||||
self.intermediate_size = intermediate_size
|
||||
self.num_hidden_layers = num_hidden_layers
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.num_key_value_heads = num_key_value_heads
|
||||
self.head_dim = head_dim
|
||||
self.num_local_experts = num_local_experts
|
||||
self.num_experts_per_tok = num_experts_per_tok
|
||||
self.hidden_act = hidden_act
|
||||
self.swiglu_limit = swiglu_limit
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
self.initial_context_length = initial_context_length
|
||||
self.sliding_window = sliding_window
|
||||
self.layer_types = layer_types or [
|
||||
"sliding_attention" if layer_idx % 2 == 0 else "full_attention" for layer_idx in range(num_hidden_layers)
|
||||
]
|
||||
|
||||
if rope_parameters is None:
|
||||
rope_parameters = rope_scaling
|
||||
if rope_parameters is None:
|
||||
rope_parameters = {
|
||||
"rope_type": "yarn",
|
||||
"factor": 32.0,
|
||||
"beta_fast": 32.0,
|
||||
"beta_slow": 1.0,
|
||||
"truncate": False,
|
||||
"original_max_position_embeddings": 4096,
|
||||
}
|
||||
self.rope_parameters = dict(rope_parameters)
|
||||
self.rope_parameters.setdefault("rope_theta", rope_theta)
|
||||
|
||||
self.rms_norm_eps = rms_norm_eps
|
||||
self.attention_bias = attention_bias
|
||||
self.attention_dropout = attention_dropout
|
||||
self.initializer_range = initializer_range
|
||||
self.router_aux_loss_coef = router_aux_loss_coef
|
||||
self.output_router_logits = output_router_logits
|
||||
self.use_cache = use_cache
|
||||
self.pad_token_id = pad_token_id
|
||||
self.bos_token_id = bos_token_id
|
||||
self.eos_token_id = eos_token_id
|
||||
|
||||
super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
|
||||
|
||||
|
||||
__all__ = ["GptOssConfig"]
|
||||
|
||||
@@ -11,6 +11,9 @@ class GptOssExperts(ConvOp):
|
||||
|
||||
def hf_to_prime(self, state_dict: dict[str, Tensor]) -> None:
|
||||
gate_up_name = f"{self.prefix}.gate_up_proj"
|
||||
if gate_up_name not in state_dict:
|
||||
return
|
||||
|
||||
gate_up = state_dict.pop(gate_up_name)
|
||||
gate_up_bias = state_dict.pop(f"{self.prefix}.gate_up_proj_bias")
|
||||
state_dict[f"{self.prefix}.gate_proj"] = gate_up[..., ::2].transpose(-2, -1)
|
||||
@@ -21,6 +24,9 @@ class GptOssExperts(ConvOp):
|
||||
|
||||
def prime_to_hf(self, state_dict: dict[str, Tensor]) -> None:
|
||||
gate_name = f"{self.prefix}.gate_proj"
|
||||
if gate_name not in state_dict:
|
||||
return
|
||||
|
||||
gate = state_dict.pop(gate_name).transpose(-2, -1)
|
||||
up = state_dict.pop(f"{self.prefix}.up_proj").transpose(-2, -1)
|
||||
gate_bias = state_dict.pop(f"{self.prefix}.gate_proj_bias")
|
||||
@@ -37,7 +43,7 @@ class GptOssExperts(ConvOp):
|
||||
|
||||
|
||||
def is_hf_state_dict(state_dict: dict[str, Tensor]) -> bool:
|
||||
return any("mlp.experts.gate_up_proj" in name for name in state_dict)
|
||||
return any(name.endswith("mlp.experts.gate_up_proj") for name in state_dict)
|
||||
|
||||
|
||||
def is_prime_state_dict(state_dict: dict[str, Tensor]) -> bool:
|
||||
|
||||
@@ -1,43 +1,40 @@
|
||||
# GPT-OSS model with PrimeRL grouped experts. Attention, rotary embedding, and
|
||||
# RMSNorm are reused from HuggingFace.
|
||||
|
||||
from typing import Union
|
||||
|
||||
import torch
|
||||
from torch import Tensor, nn
|
||||
from transformers.cache_utils import Cache
|
||||
from transformers.generation import GenerationMixin
|
||||
from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask
|
||||
from transformers.modeling_layers import GradientCheckpointingLayer
|
||||
from transformers.modeling_outputs import MoeModelOutputWithPast
|
||||
from transformers.models.gpt_oss.modeling_gpt_oss import (
|
||||
GptOssAttention,
|
||||
GptOssRMSNorm,
|
||||
GptOssRotaryEmbedding,
|
||||
)
|
||||
from transformers.processing_utils import Unpack
|
||||
from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple
|
||||
from transformers.modeling_outputs import BaseModelOutput
|
||||
|
||||
from prime_rl.trainer.models.base import CPSupport, PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.gpt_oss.attention import GptOssAttention
|
||||
from prime_rl.trainer.models.gpt_oss.configuration_gpt_oss import GptOssConfig
|
||||
from prime_rl.trainer.models.gpt_oss.converting_gpt_oss import (
|
||||
conversion_chain,
|
||||
is_hf_state_dict,
|
||||
is_prime_state_dict,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.moe import (
|
||||
GroupedExperts,
|
||||
MoE,
|
||||
TokenChoiceTopKRouter,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput, VanillaOutputLinear
|
||||
from prime_rl.trainer.models.layers.moe import GroupedExperts, MoE, TokenChoiceTopKRouter
|
||||
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
|
||||
|
||||
|
||||
class GptOssDecoderLayer(GradientCheckpointingLayer):
|
||||
def __init__(self, config: GptOssConfig, layer_idx: int):
|
||||
class GptOssRMSNorm(nn.Module):
|
||||
def __init__(self, hidden_size: int, eps: float) -> None:
|
||||
super().__init__()
|
||||
self.hidden_size = config.hidden_size
|
||||
self.self_attn = GptOssAttention(config=config, layer_idx=layer_idx)
|
||||
self.weight = nn.Parameter(torch.ones(hidden_size))
|
||||
self.variance_epsilon = eps
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
input_dtype = hidden_states.dtype
|
||||
hidden_states = hidden_states.float()
|
||||
variance = hidden_states.square().mean(dim=-1, keepdim=True)
|
||||
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
||||
return (self.weight * hidden_states).to(input_dtype)
|
||||
|
||||
|
||||
class GptOssDecoderLayer(nn.Module):
|
||||
def __init__(self, config: GptOssConfig, layer_idx: int) -> None:
|
||||
super().__init__()
|
||||
self.self_attn = GptOssAttention(config, layer_idx)
|
||||
|
||||
router = TokenChoiceTopKRouter(
|
||||
dim=config.hidden_size,
|
||||
num_experts=config.num_local_experts,
|
||||
@@ -55,6 +52,7 @@ class GptOssDecoderLayer(GradientCheckpointingLayer):
|
||||
activation="clamped_swiglu",
|
||||
bias=True,
|
||||
)
|
||||
experts.init_weights(config.initializer_range)
|
||||
self.mlp = MoE(
|
||||
router=router,
|
||||
experts=experts,
|
||||
@@ -62,63 +60,38 @@ class GptOssDecoderLayer(GradientCheckpointingLayer):
|
||||
score_before_experts=False,
|
||||
load_balance_coeff=None,
|
||||
)
|
||||
self.input_layernorm = GptOssRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.post_attention_layernorm = GptOssRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.input_layernorm = GptOssRMSNorm(config.hidden_size, config.rms_norm_eps)
|
||||
self.post_attention_layernorm = GptOssRMSNorm(config.hidden_size, config.rms_norm_eps)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
position_ids: torch.LongTensor | None = None,
|
||||
past_key_values: Cache | None = None,
|
||||
use_cache: bool | None = False,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
cu_seqlens: torch.Tensor,
|
||||
max_seqlen: int,
|
||||
routed_experts: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.input_layernorm(hidden_states)
|
||||
hidden_states, _ = self.self_attn(
|
||||
hidden_states=hidden_states,
|
||||
attention_mask=attention_mask,
|
||||
position_ids=position_ids,
|
||||
past_key_values=past_key_values,
|
||||
use_cache=use_cache,
|
||||
position_embeddings=position_embeddings,
|
||||
**kwargs,
|
||||
)
|
||||
hidden_states = self.self_attn(hidden_states, position_embeddings, cu_seqlens, max_seqlen)
|
||||
hidden_states = residual + hidden_states
|
||||
|
||||
residual = hidden_states
|
||||
hidden_states = self.post_attention_layernorm(hidden_states)
|
||||
hidden_states = self.mlp(hidden_states)
|
||||
hidden_states = residual + hidden_states
|
||||
return hidden_states
|
||||
hidden_states = self.mlp(hidden_states, routed_experts=routed_experts)
|
||||
return residual + hidden_states
|
||||
|
||||
|
||||
@auto_docstring
|
||||
class GptOssPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
config: GptOssConfig
|
||||
base_model_prefix = "model"
|
||||
supports_gradient_checkpointing = True
|
||||
_no_split_modules = ["GptOssDecoderLayer"]
|
||||
_skip_keys_device_placement = ["past_key_values"]
|
||||
_supports_flash_attn = True
|
||||
_supports_sdpa = False
|
||||
_supports_flex_attn = True
|
||||
_can_compile_fullgraph = False
|
||||
_supports_attention_backend = True
|
||||
_keep_in_fp32_modules = ["post_attention_layernorm", "input_layernorm", "norm"]
|
||||
_compatible_flash_implementations = ["kernels-community/vllm-flash-attn3", "flash_attention_4"]
|
||||
_can_record_outputs = {"hidden_states": GptOssDecoderLayer}
|
||||
|
||||
@classmethod
|
||||
def cp_support(cls, config) -> CPSupport:
|
||||
return CPSupport(
|
||||
frozenset(),
|
||||
"its attention is HuggingFace's GptOssAttention, which passes per-head sink logits as "
|
||||
"`s_aux`; neither the ring nor the ulysses path forwards them, so CP would silently drop "
|
||||
"the sinks",
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
@@ -129,169 +102,126 @@ class GptOssPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
return is_prime_state_dict(state_dict)
|
||||
|
||||
@classmethod
|
||||
def conversion_chain(cls, config):
|
||||
def conversion_chain(cls, config: GptOssConfig):
|
||||
return conversion_chain(config)
|
||||
|
||||
|
||||
@auto_docstring
|
||||
class GptOssModel(GptOssPreTrainedModel):
|
||||
_no_split_modules = ["GptOssDecoderLayer"]
|
||||
|
||||
def __init__(self, config: GptOssConfig):
|
||||
def __init__(self, config: GptOssConfig) -> None:
|
||||
super().__init__(config)
|
||||
self.padding_idx = config.pad_token_id
|
||||
self.vocab_size = config.vocab_size
|
||||
|
||||
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
||||
self.layers = nn.ModuleList(
|
||||
[GptOssDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
||||
GptOssDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)
|
||||
)
|
||||
self.norm = GptOssRMSNorm(config.hidden_size, config.rms_norm_eps)
|
||||
self.rotary_emb = RotaryEmbedding(
|
||||
RotaryEmbeddingConfig(
|
||||
max_position_embeddings=config.max_position_embeddings,
|
||||
rope_type=config.rope_parameters["rope_type"],
|
||||
model_config=config,
|
||||
)
|
||||
)
|
||||
self.norm = GptOssRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.rotary_emb = GptOssRotaryEmbedding(config=config)
|
||||
self.gradient_checkpointing = False
|
||||
|
||||
self.post_init()
|
||||
|
||||
@auto_docstring
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.LongTensor | None = None,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
position_ids: torch.LongTensor | None = None,
|
||||
past_key_values: Cache | None = None,
|
||||
inputs_embeds: torch.FloatTensor | None = None,
|
||||
use_cache: bool | None = None,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> MoeModelOutputWithPast:
|
||||
if (input_ids is None) ^ (inputs_embeds is not None):
|
||||
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
||||
|
||||
inputs_embeds: torch.Tensor | None = None,
|
||||
routed_experts: torch.LongTensor | None = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
) -> BaseModelOutput:
|
||||
if inputs_embeds is None:
|
||||
inputs_embeds = self.embed_tokens(input_ids)
|
||||
|
||||
if position_ids is None:
|
||||
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
||||
|
||||
if not isinstance(causal_mask_mapping := attention_mask, dict):
|
||||
mask_kwargs = {
|
||||
"config": self.config,
|
||||
"inputs_embeds": inputs_embeds,
|
||||
"attention_mask": attention_mask,
|
||||
"past_key_values": past_key_values,
|
||||
"position_ids": position_ids,
|
||||
}
|
||||
causal_mask_mapping = {
|
||||
"full_attention": create_causal_mask(**mask_kwargs),
|
||||
"sliding_attention": create_sliding_window_causal_mask(**mask_kwargs),
|
||||
}
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(
|
||||
seq_lens.to(device=inputs_embeds.device),
|
||||
total_tokens=None if seq_lens_are_pre_shard else inputs_embeds.shape[1],
|
||||
)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
|
||||
hidden_states = inputs_embeds
|
||||
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
||||
|
||||
for i, decoder_layer in enumerate(self.layers):
|
||||
for layer_idx, decoder_layer in enumerate(self.layers):
|
||||
layer_routed_experts = routed_experts[:, :, layer_idx] if routed_experts is not None else None
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
attention_mask=causal_mask_mapping[self.config.layer_types[i]],
|
||||
position_embeddings=position_embeddings,
|
||||
position_ids=position_ids,
|
||||
past_key_values=past_key_values,
|
||||
use_cache=use_cache,
|
||||
**kwargs,
|
||||
position_embeddings,
|
||||
cu_seqlens,
|
||||
max_seqlen,
|
||||
routed_experts=layer_routed_experts,
|
||||
)
|
||||
hidden_states = self.norm(hidden_states)
|
||||
return MoeModelOutputWithPast(last_hidden_state=hidden_states, past_key_values=past_key_values)
|
||||
return BaseModelOutput(last_hidden_state=self.norm(hidden_states))
|
||||
|
||||
|
||||
@auto_docstring
|
||||
class GptOssForCausalLM(GptOssPreTrainedModel, GenerationMixin):
|
||||
class GptOssForCausalLM(GptOssPreTrainedModel):
|
||||
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
||||
_tp_plan = {"lm_head": "colwise_gather_output"}
|
||||
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
||||
|
||||
def __init__(self, config: GptOssConfig):
|
||||
def __init__(self, config: GptOssConfig) -> None:
|
||||
super().__init__(config)
|
||||
self.model = GptOssModel(config)
|
||||
self.vocab_size = config.vocab_size
|
||||
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
||||
self.lm_head = VanillaOutputLinear(config.hidden_size, config.vocab_size)
|
||||
self.num_experts = config.num_local_experts
|
||||
self.num_experts_per_tok = config.num_experts_per_tok
|
||||
|
||||
self.post_init()
|
||||
|
||||
def set_decoder(self, decoder):
|
||||
self.model = decoder
|
||||
|
||||
def get_decoder(self):
|
||||
return self.model
|
||||
|
||||
@can_return_tuple
|
||||
@auto_docstring
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.LongTensor | None = None,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
position_ids: torch.LongTensor | None = None,
|
||||
past_key_values: Cache | None = None,
|
||||
inputs_embeds: torch.FloatTensor | None = None,
|
||||
inputs_embeds: torch.Tensor | None = None,
|
||||
labels: torch.LongTensor | None = None,
|
||||
use_cache: bool | None = None,
|
||||
logits_to_keep: Union[int, torch.Tensor] = 0,
|
||||
logits_to_keep: int | torch.Tensor = 0,
|
||||
temperature: torch.Tensor | None = None,
|
||||
# Document boundaries derive from position_ids (HF packed-sequence masks);
|
||||
# seq_lens is accepted to satisfy the trainer's universal contract.
|
||||
routed_experts: torch.LongTensor | None = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> PrimeLmOutput:
|
||||
r"""
|
||||
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
|
||||
Per-document lengths of the packed row (PrimeRL packed-batch contract).
|
||||
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
|
||||
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
|
||||
temperature (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
||||
Per-token temperatures for logprobs/entropy computation when `labels` are provided.
|
||||
"""
|
||||
assert use_cache is None or not use_cache, "use_cache is not supported for custom GPT-OSS"
|
||||
assert past_key_values is None, "past_key_values is not supported for custom GPT-OSS"
|
||||
|
||||
outputs: MoeModelOutputWithPast = self.model(
|
||||
outputs = self.model(
|
||||
input_ids=input_ids,
|
||||
attention_mask=attention_mask,
|
||||
position_ids=position_ids,
|
||||
past_key_values=past_key_values,
|
||||
inputs_embeds=inputs_embeds,
|
||||
use_cache=use_cache,
|
||||
**kwargs,
|
||||
routed_experts=routed_experts,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
)
|
||||
|
||||
hidden_states = outputs.last_hidden_state
|
||||
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
||||
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(
|
||||
hidden_states[:, slice_indices, :],
|
||||
hidden_states[:, slice_indices],
|
||||
labels[:, slice_indices] if labels is not None else None,
|
||||
temperature=temperature,
|
||||
temperature=temperature[:, slice_indices] if temperature is not None else None,
|
||||
)
|
||||
|
||||
def init_buffers_post_meta(self):
|
||||
buffer_names = [name for name, _ in self.named_buffers()]
|
||||
if "model.rotary_emb.inv_freq" in buffer_names:
|
||||
rotary_emb = self.model.rotary_emb
|
||||
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
|
||||
|
||||
rope_init_fn = (
|
||||
ROPE_INIT_FUNCTIONS[rotary_emb.rope_type]
|
||||
if rotary_emb.rope_type != "default"
|
||||
else rotary_emb.compute_default_rope_parameters
|
||||
)
|
||||
inv_freq, rotary_emb.attention_scaling = rope_init_fn(rotary_emb.config, rotary_emb.inv_freq.device)
|
||||
rotary_emb.inv_freq.copy_(inv_freq)
|
||||
if "model.rotary_emb.original_inv_freq" in buffer_names:
|
||||
rotary_emb.original_inv_freq.copy_(inv_freq)
|
||||
def init_buffers_post_meta(self) -> None:
|
||||
rotary_emb = self.model.rotary_emb
|
||||
inv_freq, rotary_emb.attention_scaling = rotary_emb.rope_init_fn(
|
||||
rotary_emb.config,
|
||||
rotary_emb.inv_freq.device,
|
||||
)
|
||||
rotary_emb.inv_freq.copy_(inv_freq)
|
||||
for module in self.modules():
|
||||
if isinstance(module, MoE):
|
||||
module.tokens_per_expert.zero_()
|
||||
module.routing_confidence_sum.zero_()
|
||||
|
||||
|
||||
__all__ = [
|
||||
"GptOssDecoderLayer",
|
||||
"GptOssForCausalLM",
|
||||
"GptOssModel",
|
||||
"GptOssPreTrainedModel",
|
||||
"GptOssRMSNorm",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
IGNORE_SLOT = -1
|
||||
"""A slot is one key a query may read. `IGNORE_SLOT` stands in a slot where the query has no key
|
||||
at all.
|
||||
|
||||
Every query is given the same maximum number of slots, so a query with fewer keys to read leaves
|
||||
the rest empty, and an empty slot contributes nothing to its attention.
|
||||
"""
|
||||
@@ -0,0 +1,222 @@
|
||||
# Torch-facing layer for the DeepSeek V4 sparse attention kernels: the `prime_rl::dsv4_sparse_attn`
|
||||
# and `prime_rl::dsv4_sparse_attn_backward` custom ops, their fake (meta) implementations, and the
|
||||
# autograd rule that ties them together and forms the attention-sink gradient in torch. The
|
||||
# TileLang kernels themselves live in `dsv4_sparse_attn_fwd.py` and `dsv4_sparse_attn_bwd.py`; this
|
||||
# module is the only place that knows both exist.
|
||||
|
||||
# TileLang ships a libcudart stub that proxies to the real CUDA runtime via
|
||||
# dlsym(RTLD_DEFAULT, ...). If the stub's own symbols are the first ones found
|
||||
# (because nothing loaded the real libcudart globally yet), the self-check fails
|
||||
# and the stub calls abort(). Pre-loading the real library with RTLD_GLOBAL
|
||||
# ensures dlsym finds it before the stub's own exports.
|
||||
import ctypes as _ctypes
|
||||
|
||||
try:
|
||||
_ctypes.CDLL("libcudart.so", mode=_ctypes.RTLD_GLOBAL)
|
||||
except Exception:
|
||||
# This is expected on CPU-only machines
|
||||
pass
|
||||
|
||||
import tilelang
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
from prime_rl.trainer.models.kernels.deepseek_v4 import IGNORE_SLOT
|
||||
from prime_rl.trainer.models.kernels.deepseek_v4.dsv4_sparse_attn_bwd import bwd, postprocess, preprocess
|
||||
from prime_rl.trainer.models.kernels.deepseek_v4.dsv4_sparse_attn_fwd import dsv4_sparse_attn_fwd
|
||||
|
||||
LOG2E = 1.44269504
|
||||
|
||||
# The forward tiles the gather-slot axis at `block_I = 64` and the backward at `block_size = 32`,
|
||||
# so the slot count must be a multiple of `lcm(64, 32) = 64`.
|
||||
SLOT_TILE = 64
|
||||
|
||||
|
||||
def _pad_slots_to_tile(indices: torch.Tensor) -> torch.Tensor:
|
||||
"""Widen the gather-slot axis to a multiple of the tile, marking the slots that adds absent.
|
||||
|
||||
Callers state the slots they mean and this covers the difference, so the tile stays a fact
|
||||
about these kernels rather than something the modeling code has to lay out for them. An
|
||||
`IGNORE_SLOT` (-1) slot is masked, so the padding changes no output. Production widths are
|
||||
usually aligned already (`sliding_window + index_topk = 128 + 512 = 640`), and then this
|
||||
returns its argument.
|
||||
"""
|
||||
remainder = indices.shape[-1] % SLOT_TILE
|
||||
if remainder == 0:
|
||||
return indices
|
||||
return F.pad(indices, (0, SLOT_TILE - remainder), value=IGNORE_SLOT).contiguous()
|
||||
|
||||
|
||||
def sparse_attn_shape_error(heads: int, kv_group: int, dim: int) -> str | None:
|
||||
"""The reason these kernels cannot serve this shape, or ``None`` if they can.
|
||||
|
||||
The forward, the backward and the constructor check in `deepseek_v4/attention.py` all need
|
||||
the same answer, so the constraints live here only.
|
||||
"""
|
||||
# The backward's `preprocess` tiles the channel axis at `block_ND = 32` and reads whole
|
||||
# tiles, so a `dim` below that (or not a multiple of it) over-reads into the next head and
|
||||
# silently corrupts `Delta`, hence every gradient. This subsumes `atomic_addx4`'s own
|
||||
# requirement that four channels be contiguous.
|
||||
if dim % 32 != 0:
|
||||
return f"the kernels tile the channel axis at 32 and read whole tiles, but head_dim is {dim}"
|
||||
# The kernels tile the head axis up to a power of two, at least 16, and index `Sinks`, `Q`,
|
||||
# `dO`, `Lse` and `dQ` over that padded block. A head count the tiler pads runs off the end
|
||||
# of all of them; `Q` and `Output` absorb the over-read into the next token's heads, but
|
||||
# `Sinks` is one row with nothing after it.
|
||||
head_kv = heads // kv_group
|
||||
padded_heads = max(tilelang.math.next_power_of_2(head_kv), 16)
|
||||
if padded_heads != head_kv:
|
||||
return (
|
||||
f"the kernels tile {padded_heads} heads per group but this shape has {head_kv}; "
|
||||
"a head count the tiler pads would read and write past the end of the head axis"
|
||||
)
|
||||
# The backward runs `block_H = min(64, padded_H)` rows through a GEMM that needs at least 32.
|
||||
# At 16 heads the forward compiles and runs, then the backward dies mid-step inside tilelang
|
||||
# with "warp_row_tiles must be greater than 16", so a forward-only test will not catch this.
|
||||
if head_kv < 32:
|
||||
return (
|
||||
f"the sparse attention backward needs at least 32 heads per group, got {head_kv}; "
|
||||
"its GEMM over min(64, heads) rows fails to compile below that"
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl::dsv4_sparse_attn", mutates_args=())
|
||||
def dsv4_sparse_attn(
|
||||
q: torch.Tensor,
|
||||
kv: torch.Tensor,
|
||||
indices: torch.Tensor,
|
||||
sinks: torch.Tensor,
|
||||
sm_scale: float | None = None,
|
||||
block_I: int = 64,
|
||||
num_stages: int = 2,
|
||||
threads: int = 256,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
assert q.is_contiguous(), "q must be contiguous"
|
||||
assert kv.is_contiguous(), "kv must be contiguous"
|
||||
assert indices.is_contiguous(), "indices must be contiguous"
|
||||
batch, seq_len, heads, dim = q.shape
|
||||
_, _, kv_group, _ = kv.shape
|
||||
|
||||
assert kv.shape[-1] == dim, "q and kv must share the full channel dim; DS V4 has no score-only tail"
|
||||
assert kv.shape[0] == batch
|
||||
assert q.dtype == torch.bfloat16, (
|
||||
f"the sparse attention kernel runs in bfloat16 only, but the queries are {q.dtype}"
|
||||
)
|
||||
shape_error = sparse_attn_shape_error(heads, kv_group, dim)
|
||||
assert shape_error is None, shape_error
|
||||
assert indices.shape[:3] == (batch, seq_len, kv_group)
|
||||
assert sinks.shape == (heads,)
|
||||
indices = _pad_slots_to_tile(indices)
|
||||
topk = indices.shape[-1]
|
||||
|
||||
kernel = dsv4_sparse_attn_fwd(
|
||||
heads,
|
||||
dim,
|
||||
topk,
|
||||
kv_group,
|
||||
sm_scale,
|
||||
True,
|
||||
block_I=block_I,
|
||||
num_stages=num_stages,
|
||||
threads=threads,
|
||||
)
|
||||
out, lse = kernel(q, kv, indices, sinks.float().contiguous())
|
||||
return out, lse
|
||||
|
||||
|
||||
# A fake must mirror the op's signature exactly, so it takes every argument even though only `q`,
|
||||
# the one argument that determines the output shapes, is read.
|
||||
@dsv4_sparse_attn.register_fake
|
||||
def _dsv4_sparse_attn_fake(
|
||||
q: torch.Tensor,
|
||||
kv: torch.Tensor,
|
||||
indices: torch.Tensor,
|
||||
sinks: torch.Tensor,
|
||||
sm_scale: float | None = None,
|
||||
block_I: int = 64,
|
||||
num_stages: int = 2,
|
||||
threads: int = 256,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
return torch.empty_like(q), q.new_empty(q.shape[:-1], dtype=torch.float32)
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl::dsv4_sparse_attn_backward", mutates_args=())
|
||||
def dsv4_sparse_attn_backward(
|
||||
q: torch.Tensor,
|
||||
kv: torch.Tensor,
|
||||
out: torch.Tensor,
|
||||
grad_out: torch.Tensor,
|
||||
indices: torch.Tensor,
|
||||
lse: torch.Tensor,
|
||||
sm_scale: float | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
assert q.is_contiguous(), "q must be contiguous"
|
||||
assert kv.is_contiguous(), "kv must be contiguous"
|
||||
assert indices.is_contiguous(), "indices must be contiguous"
|
||||
assert lse.is_contiguous(), "lse must be contiguous"
|
||||
grad_out = grad_out.contiguous()
|
||||
batch, seq_len, heads, dim = q.shape
|
||||
_, _, kv_group, _ = kv.shape
|
||||
assert kv.shape[-1] == dim, "q and kv must share the full channel dim; DS V4 has no score-only tail"
|
||||
assert kv.shape[0] == batch
|
||||
# This op is public, so it repeats the forward's shape checks rather than trusting autograd.
|
||||
shape_error = sparse_attn_shape_error(heads, kv_group, dim)
|
||||
assert shape_error is None, shape_error
|
||||
assert indices.shape[:3] == (batch, seq_len, kv_group)
|
||||
assert lse.shape == (batch, seq_len, heads)
|
||||
indices = _pad_slots_to_tile(indices)
|
||||
topk = indices.shape[-1]
|
||||
|
||||
preprocess_kernel = preprocess(heads, dim)
|
||||
bwd_kernel = bwd(heads, dim, topk, kv_group, sm_scale, True)
|
||||
postprocess_kernel = postprocess(dim, kv_group)
|
||||
|
||||
delta = preprocess_kernel(out, grad_out)
|
||||
dkv = torch.zeros_like(kv, dtype=torch.float32)
|
||||
dq = bwd_kernel(q, kv, grad_out, indices, lse, delta, dkv)
|
||||
dkv = postprocess_kernel(dkv)
|
||||
|
||||
return dq, dkv, delta
|
||||
|
||||
|
||||
@dsv4_sparse_attn_backward.register_fake
|
||||
def _dsv4_sparse_attn_backward_fake(
|
||||
q: torch.Tensor,
|
||||
kv: torch.Tensor,
|
||||
out: torch.Tensor,
|
||||
grad_out: torch.Tensor,
|
||||
indices: torch.Tensor,
|
||||
lse: torch.Tensor,
|
||||
sm_scale: float | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
return torch.empty_like(q), torch.empty_like(kv), torch.empty_like(lse)
|
||||
|
||||
|
||||
def _dsv4_sparse_attn_setup_context(ctx, inputs, output) -> None:
|
||||
q, kv, indices, sinks, sm_scale, _block_I, _num_stages, _threads = inputs
|
||||
out, lse = output
|
||||
ctx.save_for_backward(q, kv, out, indices, lse, sinks)
|
||||
ctx.sm_scale = sm_scale
|
||||
ctx.mark_non_differentiable(lse)
|
||||
|
||||
|
||||
def _dsv4_sparse_attn_autograd_backward(ctx, grad_out: torch.Tensor, _grad_lse: torch.Tensor | None):
|
||||
q, kv, out, indices, lse, sinks = ctx.saved_tensors
|
||||
dq, dkv, delta = dsv4_sparse_attn_backward(
|
||||
q.detach(),
|
||||
kv.detach(),
|
||||
out.detach(),
|
||||
grad_out,
|
||||
indices,
|
||||
lse.detach(),
|
||||
ctx.sm_scale,
|
||||
)
|
||||
# dp_k/dsink = -p_k * p_sink, so do[d]/dsink = -p_sink * o[d] and the head's sink gradient
|
||||
# contracts to -p_sink * Delta. The sink logit is unscaled, hence no sm_scale factor.
|
||||
p_sink = torch.exp2(sinks.float().view(1, 1, -1) * LOG2E - lse)
|
||||
dsink = -(p_sink * delta).sum(dim=(0, 1)).to(sinks.dtype)
|
||||
return dq, dkv, None, dsink, None, None, None, None
|
||||
|
||||
|
||||
dsv4_sparse_attn.register_autograd(_dsv4_sparse_attn_autograd_backward, setup_context=_dsv4_sparse_attn_setup_context)
|
||||
@@ -0,0 +1,326 @@
|
||||
"""
|
||||
[DeepSeek V4 Sparse Attention: Backward]
|
||||
|
||||
Gradients for the forward in `dsv4_sparse_attn_fwd.py`, whose shapes, index letters and masking
|
||||
rule carry over unchanged. Three kernels:
|
||||
|
||||
preprocess Delta, a per-query-head reduction over the channel axis
|
||||
bwd dQ, and dKV scattered into a float32 buffer
|
||||
postprocess casts that buffer back to bfloat16
|
||||
|
||||
Beyond the forward's tensors:
|
||||
|
||||
dO[b, s, h, d] (B, S, H, D) incoming output gradient, bfloat16
|
||||
Delta[b, s, h] (B, S, H) float32
|
||||
dQ[b, s, h, d] (B, S, H, D) bfloat16
|
||||
dKV[b, n, g, d] (B, N, G, D) float32 until `postprocess`
|
||||
|
||||
[What it computes]
|
||||
|
||||
With `key[b,s,k,d] = KV[b, Indices[b,s,0,k], 0, d]` and `scale = D ** -0.5` as in the forward:
|
||||
|
||||
Delta[b,s,h] = Output[b,s,h,d] dO[b,s,h,d]
|
||||
p[b,s,h,k] = exp2(scale * Q[b,s,h,d] key[b,s,k,d] * log2(e) - Lse[b,s,h])
|
||||
dp[b,s,h,k] = dO[b,s,h,d] key[b,s,k,d]
|
||||
ds[b,s,h,k] = scale * p[b,s,h,k] * (dp[b,s,h,k] - Delta[b,s,h])
|
||||
|
||||
dQ[b,s,h,d] = ds[b,s,h,k] key[b,s,k,d]
|
||||
dkey[b,s,k,d] = ds[b,s,h,k] Q[b,s,h,d] + p[b,s,h,k] dO[b,s,h,d]
|
||||
|
||||
`dkey` has two terms because `V == K`: a gathered position is read once as a key inside the logit
|
||||
and once as a value inside the output. Per tile of `block_size` slots the block runs five GEMMs,
|
||||
two rebuilding `p` and `dp`, one for `dQ`, and two accumulating into the `dkey` tile.
|
||||
|
||||
`p` is recovered from `Lse` with a single `exp2`, never by a second max pass. The sink needs no
|
||||
handling here: it is already inside the `Z` that `Lse` encodes, so this `p` is the shrunken
|
||||
probability the forward produced. No sink gradient is formed in this file; `Delta` is returned so a
|
||||
caller can build one from it.
|
||||
|
||||
[dQ is local, dKV is a scatter]
|
||||
|
||||
A block owns one query position, so that query's `dQ` accumulates in registers and is written once.
|
||||
`dKV` is the opposite: many queries gather the same KV position `n` and they live in different
|
||||
blocks, so the tile is scattered with `atomic_addx4`, four contiguous channels at a time. That is
|
||||
why `dKV` is float32 while everything else here is bfloat16, and why `postprocess` exists.
|
||||
|
||||
Masked slots skip the store rather than adding their exact zero, and no predicate is written for
|
||||
it: TileLang already guards the atomic on both bounds, `0 <= idx < N`, and a masked slot's index is
|
||||
negative.
|
||||
|
||||
[How the loop runs]
|
||||
|
||||
The grid is `(query position, batch, head block)`, the third axis also carrying the KV head when
|
||||
`G > 1`, and at `H <= 64` it is a single block covering every query head. The block walks the `K`
|
||||
slots in tiles of `block_size`, half the forward's tile, and per tile:
|
||||
|
||||
1. gather `KV_shared[k,d]`, and seed `acc_p` to `0` or `-inf` from the mask
|
||||
2. `acc_p[h,k] += Q_shared[h,d] KV_shared[k,d]` onto that seed, then `exp2(... - Lse)` in place,
|
||||
so a masked slot stays `-inf` and becomes exactly zero. This is `p`.
|
||||
3. `acc_dp[h,k] = dO_shared[h,d] KV_shared[k,d]`, then `p * (dp - Delta) * scale` in place: `ds`
|
||||
4. `acc_dq[h,d] += ds[h,k] KV_shared[k,d]`
|
||||
5. `acc_dkv[k,d] = ds[h,k] Q_shared[h,d] + p[h,k] dO_shared[h,d]`, two GEMMs into one tile
|
||||
6. scatter `acc_dkv` into `dKV`, in `split_store` passes through a staging buffer that holds
|
||||
`block_size // split_store` slots
|
||||
|
||||
`acc_dq` accumulates over every tile and is written once after the loop, while `acc_dkv` is cleared
|
||||
each tile because step 6 has already sent it to memory. Steps 2 and 3 leave float32 fragments,
|
||||
which are cast to bfloat16 and staged in shared memory before feeding the GEMMs of steps 4 and 5.
|
||||
|
||||
The TileLang scaffolding is vendored from tile-ai/tilelang (Apache 2.0) and modified for dynamic
|
||||
shapes. As in the forward there is no score-only channel tail, and `Delta` is exposed as an output
|
||||
rather than kept internal so the caller can form the per-head sink gradient from it.
|
||||
"""
|
||||
|
||||
# TileLang ships a libcudart stub that proxies to the real CUDA runtime via
|
||||
# dlsym(RTLD_DEFAULT, ...). If the stub's own symbols are the first ones found
|
||||
# (because nothing loaded the real libcudart globally yet), the self-check fails
|
||||
# and the stub calls abort(). Pre-loading the real library with RTLD_GLOBAL
|
||||
# ensures dlsym finds it before the stub's own exports.
|
||||
import ctypes as _ctypes
|
||||
|
||||
try:
|
||||
_ctypes.CDLL("libcudart.so", mode=_ctypes.RTLD_GLOBAL)
|
||||
except Exception:
|
||||
# This is expected on CPU-only machines
|
||||
pass
|
||||
|
||||
import tilelang
|
||||
from tilelang import language as T
|
||||
|
||||
|
||||
@tilelang.jit(out_idx=[-1])
|
||||
def preprocess(
|
||||
H,
|
||||
D,
|
||||
block_ND=32,
|
||||
num_stages=5,
|
||||
dtype=T.bfloat16,
|
||||
accum_dtype=T.float32,
|
||||
):
|
||||
assert dtype == T.bfloat16
|
||||
assert accum_dtype == T.float32
|
||||
B = T.dynamic("B")
|
||||
S = T.dynamic("S")
|
||||
shape = [B, S, H, D]
|
||||
|
||||
@T.prim_func
|
||||
def preprocess_kernel(
|
||||
O: T.Tensor(shape, dtype),
|
||||
dO: T.Tensor(shape, dtype),
|
||||
Delta: T.Tensor([B, S, H], accum_dtype),
|
||||
):
|
||||
with T.Kernel(H, T.ceildiv(S, block_ND), B) as (bx, by, bz):
|
||||
o = T.alloc_fragment([block_ND, block_ND], accum_dtype)
|
||||
do = T.alloc_fragment([block_ND, block_ND], accum_dtype)
|
||||
delta = T.alloc_fragment([block_ND], accum_dtype)
|
||||
acc = T.alloc_fragment([block_ND, block_ND], accum_dtype)
|
||||
T.clear(acc)
|
||||
for k in T.Pipelined(T.ceildiv(D, block_ND), num_stages=num_stages):
|
||||
T.copy(O[bz, by * block_ND : (by + 1) * block_ND, bx, k * block_ND : (k + 1) * block_ND], o)
|
||||
T.copy(dO[bz, by * block_ND : (by + 1) * block_ND, bx, k * block_ND : (k + 1) * block_ND], do)
|
||||
for i, j in T.Parallel(block_ND, block_ND):
|
||||
acc[i, j] += o[i, j] * do[i, j]
|
||||
T.reduce_sum(acc, delta, 1)
|
||||
T.copy(delta, Delta[bz, by * block_ND : (by + 1) * block_ND, bx])
|
||||
|
||||
return preprocess_kernel
|
||||
|
||||
|
||||
@tilelang.jit(out_idx=[-1])
|
||||
def postprocess(
|
||||
D,
|
||||
kv_group=1,
|
||||
block_N=64,
|
||||
threads=128,
|
||||
dtype=T.bfloat16,
|
||||
accum_dtype=T.float32,
|
||||
):
|
||||
assert dtype == T.bfloat16
|
||||
assert accum_dtype == T.float32
|
||||
B = T.dynamic("B")
|
||||
S_kv = T.dynamic("S_kv")
|
||||
dkv_shape = [B, S_kv, kv_group, D]
|
||||
|
||||
@T.prim_func
|
||||
def postprocess_kernel(
|
||||
dKV: T.Tensor(dkv_shape, accum_dtype),
|
||||
dKV_out: T.Tensor(dkv_shape, dtype),
|
||||
):
|
||||
with T.Kernel(T.ceildiv(S_kv, block_N), kv_group, B, threads=threads) as (bx, by, bz):
|
||||
T.copy(
|
||||
dKV[bz, bx * block_N : (bx + 1) * block_N, by, :],
|
||||
dKV_out[bz, bx * block_N : (bx + 1) * block_N, by, :],
|
||||
)
|
||||
|
||||
return postprocess_kernel
|
||||
|
||||
|
||||
@tilelang.jit(
|
||||
out_idx=[-2],
|
||||
pass_configs={
|
||||
tilelang.PassConfigKey.TL_DISABLE_TMA_LOWER: True,
|
||||
tilelang.PassConfigKey.TL_DISABLE_WARP_SPECIALIZED: True,
|
||||
# Avoid TileLang MLA backward NaNs: https://github.com/tile-ai/tilelang/issues/2199
|
||||
tilelang.PassConfigKey.TL_ENABLE_AGGRESSIVE_SHARED_MEMORY_MERGE: False,
|
||||
},
|
||||
)
|
||||
def bwd(
|
||||
H,
|
||||
D,
|
||||
topk,
|
||||
kv_group=1,
|
||||
sm_scale=None,
|
||||
is_causal=True,
|
||||
block_size=32,
|
||||
num_stages=0,
|
||||
threads=256,
|
||||
indices_dtype=T.int32,
|
||||
dtype=T.bfloat16,
|
||||
accum_dtype=T.float32,
|
||||
):
|
||||
assert is_causal is True, "non-casual is not supported now"
|
||||
assert topk % block_size == 0, "otherwise will load some index=0 thus causing wrong kv to be loaded"
|
||||
assert dtype == T.bfloat16
|
||||
assert accum_dtype == T.float32
|
||||
assert indices_dtype == T.int32
|
||||
|
||||
if sm_scale is None:
|
||||
sm_scale = D ** (-0.5)
|
||||
sm_scale_mul_reciprocal_log2 = sm_scale * 1.44269504 # log2(e)
|
||||
|
||||
B = T.dynamic("B")
|
||||
S = T.dynamic("S")
|
||||
S_kv = T.dynamic("S_kv")
|
||||
|
||||
H_kv = H // kv_group
|
||||
q_shape = [B, S, H, D]
|
||||
k_shape = [B, S_kv, kv_group, D]
|
||||
o_shape = [B, S, H, D]
|
||||
indices_shape = [B, S, kv_group, topk]
|
||||
delta_shape = [B, S, H]
|
||||
lse_shape = [B, S, H]
|
||||
|
||||
H = H_kv
|
||||
padded_H = max(tilelang.math.next_power_of_2(H_kv), 16)
|
||||
block_H = min(64, padded_H)
|
||||
assert padded_H % block_H == 0
|
||||
NH = padded_H // block_H
|
||||
BS = block_size
|
||||
NS = tilelang.cdiv(topk, block_size)
|
||||
|
||||
split_store = 2
|
||||
# The acc_dkv accumulator's per-thread layout (from the GEMMs that produce it) is only
|
||||
# injective at this chunk granularity. TileLang's LayoutInference pass would reject a smaller
|
||||
# chunk if the store loop below were written over its natural extent, but that loop instead
|
||||
# iterates the full BS extent and masks with `if bi_i < chunk`, which bypasses the check: an
|
||||
# invalid chunk silently emits an aliased address formula and corrupts dKV rather than
|
||||
# raising. Verified this holds independent of warp specialization/TMA.
|
||||
chunk = BS // split_store
|
||||
if chunk < 8 or chunk & (chunk - 1) != 0:
|
||||
raise ValueError(
|
||||
f"block_size // split_store must be a power of two >= 8, got block_size={BS}, "
|
||||
f"split_store={split_store} (chunk={chunk}); see comment above for why this silently "
|
||||
"corrupts dKV instead of failing loudly if violated."
|
||||
)
|
||||
|
||||
@T.prim_func
|
||||
def dsv4_sparse_attn_bwd_kernel(
|
||||
Q: T.Tensor(q_shape, dtype),
|
||||
KV: T.Tensor(k_shape, dtype),
|
||||
dO: T.Tensor(o_shape, dtype),
|
||||
Indices: T.Tensor(indices_shape, indices_dtype),
|
||||
Lse: T.Tensor(lse_shape, accum_dtype),
|
||||
Delta: T.Tensor(delta_shape, accum_dtype),
|
||||
dQ: T.Tensor(q_shape, dtype),
|
||||
dKV: T.Tensor(k_shape, accum_dtype),
|
||||
):
|
||||
with T.Kernel(S, B, kv_group * NH, threads=threads) as (s_i, by, bz):
|
||||
Q_shared = T.alloc_shared([block_H, D], dtype)
|
||||
KV_shared = T.alloc_shared([BS, D], dtype)
|
||||
dO_shared = T.alloc_shared([block_H, D], dtype)
|
||||
mask = T.alloc_fragment([BS], "bool")
|
||||
|
||||
P_shared_cast = T.alloc_shared([block_H, BS], dtype)
|
||||
dP_shared_cast = T.alloc_shared([block_H, BS], dtype)
|
||||
dQ_shared = T.alloc_shared([block_H, D], dtype)
|
||||
|
||||
acc_p = T.alloc_fragment([block_H, BS], accum_dtype)
|
||||
acc_dp = T.alloc_fragment([block_H, BS], accum_dtype)
|
||||
acc_dq = T.alloc_fragment([block_H, D], accum_dtype)
|
||||
acc_dkv = T.alloc_fragment([BS, D], accum_dtype)
|
||||
acc_dkv_shared = T.alloc_shared([BS // split_store, D], accum_dtype)
|
||||
|
||||
# See dsv4_sparse_attn_fwd: a negative index marks an absent key and is the only
|
||||
# thing masked on, which makes the kernel work for both full and CP-sharded Q
|
||||
# without needing a global Q offset. TileLang's guarded gather zero-fills the shared
|
||||
# tile for such a slot, so no clamp is needed here either.
|
||||
|
||||
T.copy(Q[by, s_i, bz * block_H : (bz + 1) * block_H, :], Q_shared)
|
||||
T.copy(dO[by, s_i, bz * block_H : (bz + 1) * block_H, :], dO_shared)
|
||||
|
||||
T.clear(acc_dq)
|
||||
|
||||
for i_i in T.Pipelined(NS, num_stages=num_stages):
|
||||
for bi_i in T.Parallel(BS):
|
||||
mask[bi_i] = Indices[by, s_i, bz // NH, i_i * BS + bi_i] >= 0
|
||||
|
||||
for h_i, bi_i in T.Parallel(block_H, BS):
|
||||
acc_p[h_i, bi_i] = T.if_then_else(mask[bi_i], 0, -T.infinity(acc_p.dtype))
|
||||
|
||||
for bi_i, d_i in T.Parallel(BS, D):
|
||||
KV_shared[bi_i, d_i] = KV[by, Indices[by, s_i, bz // NH, i_i * BS + bi_i], bz // NH, d_i]
|
||||
|
||||
T.gemm(Q_shared, KV_shared, acc_p, transpose_B=True, policy=T.GemmWarpPolicy.FullCol)
|
||||
|
||||
for h_i, bi_i in T.Parallel(block_H, BS):
|
||||
acc_p[h_i, bi_i] = T.exp2(
|
||||
acc_p[h_i, bi_i] * sm_scale_mul_reciprocal_log2 - Lse[by, s_i, bz * block_H + h_i]
|
||||
)
|
||||
|
||||
T.copy(acc_p, P_shared_cast)
|
||||
|
||||
T.gemm(
|
||||
dO_shared, KV_shared, acc_dp, transpose_B=True, policy=T.GemmWarpPolicy.FullCol, clear_accum=True
|
||||
)
|
||||
|
||||
for h_i, bi_i in T.Parallel(block_H, BS):
|
||||
acc_dp[h_i, bi_i] = (
|
||||
acc_p[h_i, bi_i] * (acc_dp[h_i, bi_i] - Delta[by, s_i, bz * block_H + h_i]) * sm_scale
|
||||
)
|
||||
|
||||
T.copy(acc_dp, dP_shared_cast)
|
||||
T.gemm(dP_shared_cast, KV_shared, acc_dq, policy=T.GemmWarpPolicy.FullCol)
|
||||
|
||||
T.gemm(
|
||||
dP_shared_cast,
|
||||
Q_shared,
|
||||
acc_dkv,
|
||||
transpose_A=True,
|
||||
policy=T.GemmWarpPolicy.FullCol,
|
||||
clear_accum=True,
|
||||
)
|
||||
T.gemm(P_shared_cast, dO_shared, acc_dkv, transpose_A=True, policy=T.GemmWarpPolicy.FullCol)
|
||||
|
||||
for s in range(split_store):
|
||||
for bi_i, d_i in T.Parallel(BS, D):
|
||||
if bi_i < BS // split_store:
|
||||
acc_dkv_shared[bi_i, d_i] = acc_dkv[bi_i + s * (BS // split_store), d_i]
|
||||
|
||||
# A masked slot accumulates exactly zero, and issuing its atomic would only
|
||||
# serialize the scatter. No predicate is written here because TileLang already
|
||||
# emits `if (0 <= idx)` and `if (idx < S_kv)` around the store, so a negative
|
||||
# index skips it for free and an out-of-range one cannot write past the end of
|
||||
# dKV. Do not add a predicate back: reading the `mask` fragment here compiles
|
||||
# cleanly but pins this loop to the four threads owning those elements.
|
||||
for bi_i, d_i in T.Parallel(BS // split_store, D // 4):
|
||||
slot_i = i_i * BS + bi_i + s * (BS // split_store)
|
||||
T.atomic_addx4(
|
||||
dKV[by, Indices[by, s_i, bz // NH, slot_i], bz // NH, d_i * 4],
|
||||
acc_dkv_shared[bi_i, d_i * 4],
|
||||
)
|
||||
|
||||
T.copy(acc_dq, dQ_shared)
|
||||
|
||||
T.copy(dQ_shared, dQ[by, s_i, bz * block_H : (bz + 1) * block_H, :])
|
||||
|
||||
return dsv4_sparse_attn_bwd_kernel
|
||||
@@ -0,0 +1,277 @@
|
||||
"""
|
||||
[DeepSeek V4 Sparse Attention: Forward]
|
||||
|
||||
Each query attends to an explicit list of `K` KV positions supplied by the caller, rather than to
|
||||
a contiguous causal span. This kernel only reads that list; it has no opinion on how the positions
|
||||
were chosen. Because every query carries a different list, the kernel runs one block per query
|
||||
position instead of tiling over a block of queries the way dense flash attention does.
|
||||
|
||||
Shapes, with the capital of an index letter naming that axis's size:
|
||||
|
||||
Q[b, s, h, d] (B, S, H, D) queries, bfloat16
|
||||
KV[b, n, g, d] (B, N, G, D) keys, bfloat16; V == K here, so one buffer is both
|
||||
Indices[b, s, g, k] (B, S, G, K) int32 positions into KV's `n` axis
|
||||
Sinks[h] (H,) float32, one learnable logit per query head
|
||||
Output[b, s, h, d] (B, S, H, D) bfloat16
|
||||
Lse[b, s, h] (B, S, H) float32
|
||||
|
||||
- `b` batch index
|
||||
- `s` query position
|
||||
- `n` KV position
|
||||
- `k` gather slot, one of the `K` a query reads
|
||||
- `d` head dimension
|
||||
- `h` query head index
|
||||
- `g` KV head index, always of size 1; see below
|
||||
|
||||
`G` is always 1: every query head reads the same single KV head. The axis survives from the
|
||||
vendored scaffolding, where `G > 1` would split the `H` query heads into `G` contiguous blocks of
|
||||
`H / G`, each reading its own KV head. Nothing exercises that path, and the head-padding case
|
||||
asserts `G == 1` outright, so the equations below fix `g = 0` and drop it. Note that the parameter
|
||||
is spelled `kv_group` but counts KV heads; the query heads per KV head are `H / G`, spelled
|
||||
`head_kv`.
|
||||
|
||||
[What it computes]
|
||||
|
||||
Write `key[b,s,k,d] = KV[b, Indices[b,s,0,k], 0, d]` for the gathered keys. Summing over repeated
|
||||
indices, and with `scale = D ** -0.5`:
|
||||
|
||||
logit[b,s,h,k] = scale * Q[b,s,h,d] key[b,s,k,d]
|
||||
Z[b,s,h] = exp(Sinks[h]) + sum_k exp(logit[b,s,h,k])
|
||||
p[b,s,h,k] = exp(logit[b,s,h,k]) / Z[b,s,h]
|
||||
Output[b,s,h,d] = p[b,s,h,k] key[b,s,k,d]
|
||||
Lse[b,s,h] = log2(Z[b,s,h])
|
||||
|
||||
Note: the sink logit is unscaled; `scale` multiplies the dot products and not `Sinks`. And `Lse`
|
||||
is a base-2 logarithm of a partition function built from natural exponentials, not `ln Z`; that is
|
||||
what lets the backward recover `p` as `exp2(logit * log2(e) - Lse)` with a single `exp2`.
|
||||
|
||||
The sink contributes to the denominator but owns no key, so `sum_k p[b,s,h,k] < 1` and `Output` is
|
||||
a shrunken combination of the gathered keys. That is how a head attends to nothing in particular.
|
||||
|
||||
[What the caller must guarantee]
|
||||
|
||||
`K` is fixed when the kernel compiles and is part of its compilation key, so it is sized for the
|
||||
most keys any query could need and a given query will often have fewer.
|
||||
|
||||
Every unused slot must hold a negative index, which is the masking condition:
|
||||
|
||||
Indices[b,s,0,k] < 0 .
|
||||
|
||||
This is the only masking the kernel performs. It applies no causality test and never compares
|
||||
`k` against `s`: whatever the caller means by a valid key is encoded entirely in the index values.
|
||||
That is also what keeps the kernel correct when `s` is a local index that does not correspond to a
|
||||
global KV position.
|
||||
|
||||
Every other entry must be a real position in `[0, N)`. Nothing checks that: a device-side check
|
||||
would cost a sync, so an out-of-range index silently corrupts that query's softmax.
|
||||
|
||||
[How the loop runs]
|
||||
|
||||
The grid is `(query position, batch, KV head)`, so with `G == 1` that is one block per query
|
||||
position per batch index, holding all `H` query heads of that query at once, or a 64-head chunk
|
||||
when `H > 64` (`REPLICATE_H`). The block walks the `K` slots in tiles of `block_I`,
|
||||
software-pipelined `num_stages` deep, and per tile:
|
||||
|
||||
1. gather `KV_shared[k,d] = KV[b, Indices[b,s,0,k], 0, d]` into one shared tile of keys
|
||||
2. `acc_s[h,k] = Q_shared[h,d] KV_shared[k,d]`, pre-seeded to `-inf` at masked slots
|
||||
3. rescale the running max, the denominator and `acc_o` (online softmax)
|
||||
4. `acc_o[h,d] += acc_s[h,k] KV_shared[k,d]`, reusing that same tile as values
|
||||
|
||||
Step 4 reusing step 1's tile is the `V == K` property: the gather is paid for once and feeds both
|
||||
GEMMs.
|
||||
|
||||
The online softmax is seeded from the sink rather than from an empty sum. `m_i` is carried in raw
|
||||
dot-product units, so seeding it with `Sinks[h] / scale` makes `m_i * scale * log2(e)` equal
|
||||
`Sinks[h] * log2(e)`, and seeding `sumexp` to `1` is exactly that term's own exponential relative
|
||||
to that max. `T.reduce_max(..., clear=False)` then keeps the sink as a floor on the running max. A
|
||||
query whose slots are all masked therefore emits `Output = 0` and a finite
|
||||
`Lse = Sinks[h] * log2(e)`, where a zero-seeded denominator would divide by zero.
|
||||
|
||||
The TileLang scaffolding is vendored from tile-ai/tilelang (Apache 2.0) and modified for dynamic
|
||||
shapes. The attention itself differs from tilelang's sparse MLA: there is no score-only channel
|
||||
tail (every channel feeds both the score and the output), and the per-head learnable sink logit is
|
||||
folded into the online softmax as described above.
|
||||
"""
|
||||
|
||||
# TileLang ships a libcudart stub that proxies to the real CUDA runtime via
|
||||
# dlsym(RTLD_DEFAULT, ...). If the stub's own symbols are the first ones found
|
||||
# (because nothing loaded the real libcudart globally yet), the self-check fails
|
||||
# and the stub calls abort(). Pre-loading the real library with RTLD_GLOBAL
|
||||
# ensures dlsym finds it before the stub's own exports.
|
||||
import ctypes as _ctypes
|
||||
|
||||
try:
|
||||
_ctypes.CDLL("libcudart.so", mode=_ctypes.RTLD_GLOBAL)
|
||||
except Exception:
|
||||
# This is expected on CPU-only machines
|
||||
pass
|
||||
|
||||
import tilelang
|
||||
from tilelang import language as T
|
||||
|
||||
LOG2E = 1.44269504
|
||||
|
||||
|
||||
@tilelang.jit(
|
||||
out_idx=[-2, -1],
|
||||
pass_configs={
|
||||
tilelang.PassConfigKey.TL_DISABLE_TMA_LOWER: True,
|
||||
tilelang.PassConfigKey.TL_DISABLE_WARP_SPECIALIZED: True,
|
||||
},
|
||||
)
|
||||
def dsv4_sparse_attn_fwd(
|
||||
heads,
|
||||
dim,
|
||||
topk,
|
||||
kv_group=1,
|
||||
sm_scale=None,
|
||||
is_causal=True,
|
||||
block_I=64,
|
||||
num_stages=2,
|
||||
threads=256,
|
||||
):
|
||||
assert dim == tilelang.math.next_power_of_2(dim), f"haven't check padding correctness yet, dim={dim}"
|
||||
assert is_causal is True, "non-casual is not supported"
|
||||
assert topk % block_I == 0, "otherwise will load some index=0 thus causing wrong kv to be loaded"
|
||||
if sm_scale is None:
|
||||
sm_scale = (1.0 / dim) ** 0.5
|
||||
# Both names are kept: the sink logit enters the softmax unscaled, so seeding the running max
|
||||
# with it means dividing by the raw scale that every `exp2` site below multiplies back in.
|
||||
sm_scale_mul_reciprocal_log2 = sm_scale * LOG2E
|
||||
|
||||
batch = T.dynamic("batch")
|
||||
seq_len = T.dynamic("seq_len")
|
||||
seq_len_kv = T.dynamic("seq_len_kv")
|
||||
|
||||
head_kv = heads // kv_group
|
||||
q_shape = [batch, seq_len, heads, dim]
|
||||
kv_shape = [batch, seq_len_kv, kv_group, dim]
|
||||
o_shape = [batch, seq_len, heads, dim]
|
||||
indices_shape = [batch, seq_len, kv_group, topk]
|
||||
sinks_shape = [heads]
|
||||
lse_shape = [batch, seq_len, heads]
|
||||
indices_dtype = T.int32
|
||||
dtype = T.bfloat16
|
||||
accum_dtype = T.float32
|
||||
|
||||
H = head_kv
|
||||
padded_H = max(tilelang.math.next_power_of_2(head_kv), 16)
|
||||
if padded_H != H:
|
||||
assert kv_group == 1, (
|
||||
"here we solve the H padding automatically, other wise you should handle Q copy and Output copy"
|
||||
" with your mask (when kv_group == 1, use g_i * padded_H:(g_i+1) * padded_H would be handled"
|
||||
" automatically)"
|
||||
)
|
||||
BI = block_I
|
||||
NI = tilelang.cdiv(topk, block_I)
|
||||
D = dim
|
||||
|
||||
if head_kv > 64:
|
||||
assert head_kv % 64 == 0, "head_kv should be a multiple of 64"
|
||||
REPLICATE_H = head_kv // 64
|
||||
else:
|
||||
REPLICATE_H = 1
|
||||
|
||||
H_per_block = padded_H if REPLICATE_H == 1 else 64
|
||||
|
||||
@T.prim_func
|
||||
def main(
|
||||
Q: T.Tensor(q_shape, dtype), # type: ignore
|
||||
KV: T.Tensor(kv_shape, dtype), # type: ignore
|
||||
Indices: T.Tensor(indices_shape, indices_dtype), # type: ignore
|
||||
Sinks: T.Tensor(sinks_shape, accum_dtype), # type: ignore
|
||||
Output: T.Tensor(o_shape, dtype), # type: ignore
|
||||
Lse: T.Tensor(lse_shape, accum_dtype), # type: ignore
|
||||
):
|
||||
with T.Kernel(seq_len * REPLICATE_H, batch, kv_group, threads=threads) as (
|
||||
bx,
|
||||
by,
|
||||
bz,
|
||||
):
|
||||
Q_shared = T.alloc_shared([H_per_block, D], dtype)
|
||||
KV_shared = T.alloc_shared([BI, D], dtype)
|
||||
mask = T.alloc_fragment([BI], "bool")
|
||||
|
||||
acc_o = T.alloc_fragment([H_per_block, D], accum_dtype)
|
||||
acc_s = T.alloc_fragment([H_per_block, BI], accum_dtype)
|
||||
S_shared = T.alloc_shared([H_per_block, BI], dtype)
|
||||
sumexp = T.alloc_fragment([H_per_block], accum_dtype)
|
||||
sumexp_i = T.alloc_fragment([H_per_block], accum_dtype)
|
||||
alpha = T.alloc_fragment([H_per_block], accum_dtype)
|
||||
m_i = T.alloc_fragment([H_per_block], accum_dtype)
|
||||
m_i_prev = T.alloc_fragment([H_per_block], accum_dtype)
|
||||
|
||||
b_i, g_i = by, bz
|
||||
s_i = bx if REPLICATE_H == 1 else (bx // REPLICATE_H)
|
||||
# A negative index marks an absent key, and it is the only thing this kernel masks
|
||||
# on. That preserves causality and varlen masking for both full and CP-sharded Q
|
||||
# (where local q_i no longer matches the global K position), because the caller has
|
||||
# already resolved all of it into the index values.
|
||||
#
|
||||
# No clamp guards the gather below. TileLang lowers it to `cp_async_gs_conditional`,
|
||||
# whose condition is `0 <= idx < seq_len_kv` and whose `cp.async` src-size operand is
|
||||
# 0 when that fails, so PTX zero-fills the shared tile. A masked slot therefore reads
|
||||
# as a zero key. The backward relies on the same guard; the sibling
|
||||
# `kernels/sparse_mla_{fwd,bwd}.py` still use a trailing zero sentinel row instead.
|
||||
|
||||
H0 = g_i * padded_H + (0 if REPLICATE_H == 1 else (bx % REPLICATE_H) * 64)
|
||||
H1 = H0 + H_per_block
|
||||
|
||||
T.fill(acc_o, 0)
|
||||
# The online softmax starts from the sink term alone rather than from an empty sum:
|
||||
# `m_i` carries raw dot-product units, so `m_i * sm_scale_mul_reciprocal_log2` equals
|
||||
# `sink * log2(e)` and the seed `sumexp` of 1 is exactly that term's own exponential.
|
||||
# `T.reduce_max(..., clear=False)` then keeps the sink as a floor on the running max.
|
||||
# A row whose slots are all masked therefore emits `out = 0` and a finite
|
||||
# `Lse = sink * log2(e)`, where a zero-seeded denominator would divide by zero.
|
||||
for h_i in T.Parallel(H_per_block):
|
||||
sumexp[h_i] = 1.0
|
||||
for h_i in T.Parallel(H_per_block):
|
||||
m_i[h_i] = Sinks[H0 + h_i] / sm_scale
|
||||
|
||||
T.copy(Q[b_i, s_i, H0:H1, :], Q_shared)
|
||||
|
||||
for i_i in T.Pipelined(NI, num_stages=num_stages):
|
||||
for bi_i in T.Parallel(BI):
|
||||
mask[bi_i] = Indices[b_i, s_i, g_i, i_i * BI + bi_i] >= 0
|
||||
|
||||
for bi_i, d_i in T.Parallel(BI, D):
|
||||
KV_shared[bi_i, d_i] = KV[b_i, Indices[b_i, s_i, g_i, i_i * BI + bi_i], g_i, d_i]
|
||||
|
||||
for h_i, bi_i in T.Parallel(H_per_block, BI):
|
||||
acc_s[h_i, bi_i] = T.if_then_else(mask[bi_i], 0, -T.infinity(acc_s.dtype))
|
||||
T.gemm(
|
||||
Q_shared,
|
||||
KV_shared,
|
||||
acc_s,
|
||||
transpose_B=True,
|
||||
policy=T.GemmWarpPolicy.FullRow,
|
||||
)
|
||||
T.copy(m_i, m_i_prev)
|
||||
T.reduce_max(acc_s, m_i, dim=1, clear=False)
|
||||
for h_i in T.Parallel(H_per_block):
|
||||
m_i[h_i] = T.max(m_i[h_i], m_i_prev[h_i])
|
||||
for h_i in T.Parallel(H_per_block):
|
||||
alpha[h_i] = T.exp2((m_i_prev[h_i] - m_i[h_i]) * sm_scale_mul_reciprocal_log2)
|
||||
for h_i, bi_i in T.Parallel(H_per_block, BI):
|
||||
acc_s[h_i, bi_i] = T.exp2(
|
||||
acc_s[h_i, bi_i] * sm_scale_mul_reciprocal_log2 - m_i[h_i] * sm_scale_mul_reciprocal_log2
|
||||
)
|
||||
T.reduce_sum(acc_s, sumexp_i, dim=1)
|
||||
for h_i in T.Parallel(H_per_block):
|
||||
sumexp[h_i] = sumexp[h_i] * alpha[h_i] + sumexp_i[h_i]
|
||||
for h_i, d_i in T.Parallel(H_per_block, D):
|
||||
acc_o[h_i, d_i] = acc_o[h_i, d_i] * alpha[h_i]
|
||||
|
||||
T.copy(acc_s, S_shared)
|
||||
T.gemm(S_shared, KV_shared, acc_o, policy=T.GemmWarpPolicy.FullRow)
|
||||
|
||||
for h_i, d_i in T.Parallel(H_per_block, D):
|
||||
acc_o[h_i, d_i] /= sumexp[h_i]
|
||||
for h_i in T.Parallel(H_per_block):
|
||||
sumexp[h_i] = T.log2(sumexp[h_i]) + m_i[h_i] * sm_scale_mul_reciprocal_log2
|
||||
|
||||
T.copy(acc_o, Output[b_i, s_i, H0:H1, :])
|
||||
T.copy(sumexp, Lse[b_i, s_i, H0:H1])
|
||||
|
||||
return main
|
||||
@@ -130,9 +130,7 @@ class LagunaFlashAttention(FlashAttention):
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
hidden_shape = (*input_shape, -1, self.head_dim)
|
||||
|
||||
query_states = self.q_proj(hidden_states)
|
||||
key_states = self.k_proj(hidden_states)
|
||||
value_states = self.v_proj(hidden_states)
|
||||
query_states, key_states, value_states = self.project_qkv(hidden_states)
|
||||
|
||||
if self.use_qk_norm and self.qk_norm_type == "per_layer":
|
||||
query_states = self.q_norm(query_states)
|
||||
|
||||
@@ -5,6 +5,8 @@ from typing import Literal
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.trainer.models.fusions import fuse_qkv_projections
|
||||
|
||||
from .norms import RMSNorm, RMSNormConfig
|
||||
from .rotary_emb import apply_rotary_pos_emb
|
||||
|
||||
@@ -48,6 +50,8 @@ class AttentionConfig:
|
||||
class FlashAttention(nn.Module):
|
||||
"""Flash Attention"""
|
||||
|
||||
supported_fusions = {"qkv": fuse_qkv_projections}
|
||||
|
||||
_funcs = {
|
||||
2: flash_attn_varlen_func,
|
||||
3: flash_attn_3_varlen_func,
|
||||
@@ -61,15 +65,15 @@ class FlashAttention(nn.Module):
|
||||
self.scaling = self.head_dim**-0.5
|
||||
self.is_causal = config.is_causal
|
||||
|
||||
self.q_proj = nn.Linear(
|
||||
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
|
||||
)
|
||||
self.k_proj = nn.Linear(
|
||||
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
||||
)
|
||||
self.v_proj = nn.Linear(
|
||||
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
||||
self.qkv_sizes = (
|
||||
config.num_attention_heads * self.head_dim,
|
||||
config.num_key_value_heads * self.head_dim,
|
||||
config.num_key_value_heads * self.head_dim,
|
||||
)
|
||||
self.q_proj = nn.Linear(config.hidden_size, self.qkv_sizes[0], bias=config.attention_bias)
|
||||
self.k_proj = nn.Linear(config.hidden_size, self.qkv_sizes[1], bias=config.attention_bias)
|
||||
self.v_proj = nn.Linear(config.hidden_size, self.qkv_sizes[2], bias=config.attention_bias)
|
||||
self.register_module("qkv_proj", None)
|
||||
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.output_bias)
|
||||
self.use_qk_norm = config.use_qk_norm
|
||||
self.qk_norm_type = config.qk_norm_type
|
||||
@@ -87,9 +91,12 @@ class FlashAttention(nn.Module):
|
||||
|
||||
self._flash_attn_version = flash_attn_version
|
||||
self.func = self._funcs[flash_attn_version]
|
||||
self._flash_attn_call = self.func
|
||||
if self._flash_attn_version == 4:
|
||||
self._flash_attn_call = torch._dynamo.disable(self.func)
|
||||
|
||||
def project_qkv(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""Query, key and value projections, from one packed GEMM when qkv is fused."""
|
||||
if self.qkv_proj is None:
|
||||
return self.q_proj(hidden_states), self.k_proj(hidden_states), self.v_proj(hidden_states)
|
||||
return self.qkv_proj(hidden_states).split(self.qkv_sizes, dim=-1)
|
||||
|
||||
def _compute_attention(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, cu_seqlens, max_seqlen):
|
||||
"""Run the flash attention kernel. q/k/v are [total_tokens, heads, dim]."""
|
||||
@@ -102,11 +109,9 @@ class FlashAttention(nn.Module):
|
||||
# so cu_seqlens must be passed as keyword args to avoid misalignment.
|
||||
kwargs["cu_seqlens_q"] = cu_seqlens
|
||||
kwargs["cu_seqlens_k"] = cu_seqlens
|
||||
out = self._flash_attn_call(q, k, v, **kwargs)
|
||||
out, _ = self.func(q, k, v, **kwargs)
|
||||
else:
|
||||
out = self._flash_attn_call(q, k, v, cu_seqlens, cu_seqlens, max_seqlen, max_seqlen, **kwargs)
|
||||
if isinstance(out, tuple):
|
||||
out = out[0]
|
||||
out = self.func(q, k, v, cu_seqlens, cu_seqlens, max_seqlen, max_seqlen, **kwargs)
|
||||
return out
|
||||
|
||||
def forward(
|
||||
@@ -119,9 +124,7 @@ class FlashAttention(nn.Module):
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
hidden_shape = (*input_shape, -1, self.head_dim)
|
||||
|
||||
query_states = self.q_proj(hidden_states)
|
||||
key_states = self.k_proj(hidden_states)
|
||||
value_states = self.v_proj(hidden_states)
|
||||
query_states, key_states, value_states = self.project_qkv(hidden_states)
|
||||
|
||||
if self.use_qk_norm and self.qk_norm_type == "per_layer":
|
||||
query_states = self.q_norm(query_states)
|
||||
@@ -200,10 +203,6 @@ def substitute_ring_attn(
|
||||
|
||||
AfmoeFlashAttention._compute_attention = _ring_compute_attention
|
||||
|
||||
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeGatedFlashAttention
|
||||
from prime_rl.trainer.models.gpt_oss.attention import substitute_gpt_oss_ring_attention
|
||||
|
||||
Qwen3_5MoeGatedFlashAttention._compute_attention = _ring_compute_attention
|
||||
|
||||
from prime_rl.trainer.models.qwen3_5.modeling_qwen3_5 import Qwen3_5GatedFlashAttention
|
||||
|
||||
Qwen3_5GatedFlashAttention._compute_attention = _ring_compute_attention
|
||||
substitute_gpt_oss_ring_attention(process_group, heads_k_stride)
|
||||
|
||||
@@ -1,221 +0,0 @@
|
||||
"""All-to-all context parallelism for Mamba-2 SSM layers.
|
||||
|
||||
Transposes between sequence-parallel and head-parallel layouts so that each
|
||||
CP rank processes the full sequence on a subset of heads, then transposes
|
||||
back. This avoids materializing the full [S, full_heads] tensor on any GPU.
|
||||
|
||||
Communication pattern per Mamba layer:
|
||||
1. in_proj (token-parallel, no comm)
|
||||
2. all-to-all: [B, S/cp, D] -> [B, S, D/cp] (seq-to-head)
|
||||
3. conv1d + SSM on full sequence, local heads
|
||||
4. all-to-all: [B, S, D/cp] -> [B, S/cp, D] (head-to-seq)
|
||||
5. out_proj (token-parallel, no comm)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from fla.modules.conv import causal_conv1d as fla_causal_conv1d
|
||||
from fla.ops.utils import prepare_sequence_ids
|
||||
|
||||
from prime_rl.trainer.distributed.collectives import all_to_all_single_equal
|
||||
|
||||
|
||||
def _all_to_all_seq_to_head(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
|
||||
"""Transpose [B, S_local, D] -> [B, S_global, D_local] via all-to-all.
|
||||
|
||||
Each rank sends its S_local tokens split into cp_size chunks along D,
|
||||
and receives one D_local chunk from each of the cp_size ranks.
|
||||
"""
|
||||
B, S_local, D = x.shape
|
||||
D_local = D // cp_size
|
||||
|
||||
# Split D into cp_size chunks, put cp dim first for all_to_all scatter
|
||||
# [B, S_local, D] -> [B, S_local, cp, D_local] -> [cp, B, S_local, D_local]
|
||||
x = x.reshape(B, S_local, cp_size, D_local).permute(2, 0, 1, 3).contiguous()
|
||||
output = all_to_all_single_equal(x, cp_group)
|
||||
# output[i] = data from rank i (its S_local tokens, our D_local slice)
|
||||
# [cp, B, S_local, D_local] -> [B, cp, S_local, D_local] -> [B, cp*S_local, D_local]
|
||||
return output.permute(1, 0, 2, 3).reshape(B, cp_size * S_local, D_local).contiguous()
|
||||
|
||||
|
||||
def _all_to_all_head_to_seq(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
|
||||
"""Transpose [B, S_global, D_local] -> [B, S_local, D] via all-to-all.
|
||||
|
||||
Inverse of _all_to_all_seq_to_head.
|
||||
"""
|
||||
B, S_global, D_local = x.shape
|
||||
S_local = S_global // cp_size
|
||||
|
||||
# Split S_global into cp_size chunks (one per rank), put cp dim first for scatter
|
||||
# [B, S_global, D_local] -> [B, cp, S_local, D_local] -> [cp, B, S_local, D_local]
|
||||
x = x.reshape(B, cp_size, S_local, D_local).permute(1, 0, 2, 3).contiguous()
|
||||
output = all_to_all_single_equal(x, cp_group)
|
||||
# Each rank now has cp chunks of [B, S_local, D_local] — one D_local slice from each rank
|
||||
# [cp, B, S_local, D_local] -> [B, S_local, cp, D_local] -> [B, S_local, D]
|
||||
return output.permute(1, 2, 0, 3).reshape(B, S_local, cp_size * D_local).contiguous()
|
||||
|
||||
|
||||
def seq_to_head_parallel(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
|
||||
"""[B, S/cp, D] -> [B, S, D/cp] with correct backward."""
|
||||
return _all_to_all_seq_to_head(x, cp_group, cp_size)
|
||||
|
||||
|
||||
def head_to_seq_parallel(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
|
||||
"""[B, S, D/cp] -> [B, S/cp, D] with correct backward."""
|
||||
return _all_to_all_head_to_seq(x, cp_group, cp_size)
|
||||
|
||||
|
||||
def mamba_cp_forward(
|
||||
mixer,
|
||||
hidden_states: torch.Tensor,
|
||||
cp_group: dist.ProcessGroup,
|
||||
cp_rank: int,
|
||||
cp_size: int,
|
||||
cu_seqlens: torch.Tensor,
|
||||
):
|
||||
"""CP-aware Mamba-2 forward: in_proj -> all-to-all -> conv+SSM(local heads) -> all-to-all -> out_proj.
|
||||
|
||||
Replaces the mixer's cuda_kernels_forward when CP > 1. Parameters are
|
||||
sliced at runtime so FSDP / checkpoint shapes are unchanged.
|
||||
"""
|
||||
from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined
|
||||
|
||||
batch_size, seq_len, _ = hidden_states.shape # seq_len = S/cp here
|
||||
|
||||
# ── 1. in_proj (token-parallel, no communication needed) ──
|
||||
projected_states = mixer.in_proj(hidden_states)
|
||||
A = -torch.exp(mixer.A_log.float())
|
||||
|
||||
gate, hidden_states_B_C, time_step = torch.split(
|
||||
projected_states,
|
||||
[mixer.intermediate_size, mixer.conv_dim, mixer.num_heads],
|
||||
dim=-1,
|
||||
)
|
||||
|
||||
# ── 2. All-to-all: seq-parallel -> head-parallel ──
|
||||
# gate: [B, S/cp, nheads * hdim] -> [B, S, (nheads/cp) * hdim]
|
||||
# hidden_states_B_C: [B, S/cp, nheads*hdim + 2*ngroups*dstate] -> [B, S, ...]
|
||||
# time_step: [B, S/cp, nheads] -> [B, S, nheads/cp]
|
||||
gate = seq_to_head_parallel(gate, cp_group, cp_size)
|
||||
time_step = seq_to_head_parallel(time_step, cp_group, cp_size)
|
||||
|
||||
# hidden_states_B_C needs special handling: x part shards by heads, B/C parts shard by groups
|
||||
# conv_dim = intermediate_size + 2 * ngroups * dstate
|
||||
groups_time_state_size = mixer.n_groups * mixer.ssm_state_size
|
||||
x_part, B_part, C_part = torch.split(
|
||||
hidden_states_B_C,
|
||||
[mixer.intermediate_size, groups_time_state_size, groups_time_state_size],
|
||||
dim=-1,
|
||||
)
|
||||
x_part = seq_to_head_parallel(x_part, cp_group, cp_size)
|
||||
B_part = seq_to_head_parallel(B_part, cp_group, cp_size)
|
||||
C_part = seq_to_head_parallel(C_part, cp_group, cp_size)
|
||||
hidden_states_B_C = torch.cat([x_part, B_part, C_part], dim=-1)
|
||||
|
||||
full_seq_len = hidden_states_B_C.shape[1] # S (full sequence)
|
||||
seq_idx = prepare_sequence_ids(cu_seqlens).to(torch.int32).unsqueeze(0)
|
||||
|
||||
# ── 3. Local head dimensions ──
|
||||
local_num_heads = mixer.num_heads // cp_size
|
||||
local_intermediate_size = local_num_heads * mixer.head_dim
|
||||
local_n_groups = mixer.n_groups // cp_size
|
||||
|
||||
# Slice parameters for local heads
|
||||
head_start = cp_rank * local_num_heads
|
||||
head_end = head_start + local_num_heads
|
||||
|
||||
local_A = A[head_start:head_end]
|
||||
local_D = mixer.D[head_start:head_end]
|
||||
local_dt_bias = mixer.dt_bias[head_start:head_end]
|
||||
|
||||
# Slice conv1d weight/bias for local channels
|
||||
# conv1d channels = intermediate_size + 2 * ngroups * dstate (same as conv_dim)
|
||||
# After all-to-all, we have local channels: local_intermediate + 2 * local_ngroups * dstate
|
||||
conv_x_start = cp_rank * local_intermediate_size
|
||||
conv_x_end = conv_x_start + local_intermediate_size
|
||||
conv_b_start = mixer.intermediate_size + cp_rank * local_n_groups * mixer.ssm_state_size
|
||||
conv_b_end = conv_b_start + local_n_groups * mixer.ssm_state_size
|
||||
conv_c_start = mixer.intermediate_size + groups_time_state_size + cp_rank * local_n_groups * mixer.ssm_state_size
|
||||
conv_c_end = conv_c_start + local_n_groups * mixer.ssm_state_size
|
||||
|
||||
conv_indices = torch.cat(
|
||||
[
|
||||
torch.arange(conv_x_start, conv_x_end, device=mixer.conv1d.weight.device),
|
||||
torch.arange(conv_b_start, conv_b_end, device=mixer.conv1d.weight.device),
|
||||
torch.arange(conv_c_start, conv_c_end, device=mixer.conv1d.weight.device),
|
||||
]
|
||||
)
|
||||
local_conv_weight = mixer.conv1d.weight[conv_indices]
|
||||
local_conv_bias = mixer.conv1d.bias[conv_indices] if mixer.conv1d.bias is not None else None
|
||||
|
||||
# ── 4. Causal conv1d on the full sequence, local heads ──
|
||||
# Must reset at sequence boundaries for packed batches, otherwise the
|
||||
# kernel-1 left pad leaks state across sequences.
|
||||
hidden_states_B_C, _ = fla_causal_conv1d(
|
||||
x=hidden_states_B_C,
|
||||
weight=local_conv_weight.squeeze(1),
|
||||
bias=local_conv_bias,
|
||||
activation=mixer.activation,
|
||||
cu_seqlens=cu_seqlens,
|
||||
)
|
||||
|
||||
local_groups_time_state_size = local_n_groups * mixer.ssm_state_size
|
||||
hidden_states_local, B_local, C_local = torch.split(
|
||||
hidden_states_B_C,
|
||||
[local_intermediate_size, local_groups_time_state_size, local_groups_time_state_size],
|
||||
dim=-1,
|
||||
)
|
||||
|
||||
# ── 5. SSM scan on full sequence, local heads ──
|
||||
dt_limit_kwargs = {} if mixer.time_step_limit is None else {"dt_limit": mixer.time_step_limit}
|
||||
|
||||
scan_output = mamba_chunk_scan_combined(
|
||||
hidden_states_local.view(batch_size, full_seq_len, local_num_heads, mixer.head_dim),
|
||||
time_step,
|
||||
local_A,
|
||||
B_local.view(batch_size, full_seq_len, local_n_groups, -1),
|
||||
C_local.view(batch_size, full_seq_len, local_n_groups, -1),
|
||||
chunk_size=mixer.chunk_size,
|
||||
D=local_D,
|
||||
z=None,
|
||||
seq_idx=seq_idx,
|
||||
return_final_states=False,
|
||||
dt_bias=local_dt_bias,
|
||||
dt_softplus=True,
|
||||
**dt_limit_kwargs,
|
||||
)
|
||||
scan_output = scan_output.view(batch_size, full_seq_len, local_intermediate_size)
|
||||
|
||||
# ── 6. Gated RMSNorm with local weights ──
|
||||
# Zamba2RMSNormGated normalizes within groups of size `group_size`.
|
||||
# In head-parallel mode, we have local_intermediate_size features.
|
||||
# The group_size stays the same, but group_count is reduced.
|
||||
local_norm_weight = mixer.norm.weight[cp_rank * local_intermediate_size : (cp_rank + 1) * local_intermediate_size]
|
||||
scan_output = _gated_rms_norm(
|
||||
scan_output, gate, local_norm_weight, mixer.norm.variance_epsilon, mixer.norm.group_size
|
||||
)
|
||||
|
||||
# ── 7. All-to-all: head-parallel -> seq-parallel ──
|
||||
scan_output = head_to_seq_parallel(scan_output, cp_group, cp_size)
|
||||
|
||||
# ── 8. out_proj (token-parallel, no communication needed) ──
|
||||
return mixer.out_proj(scan_output)
|
||||
|
||||
|
||||
def _gated_rms_norm(
|
||||
x: torch.Tensor, gate: torch.Tensor, weight: torch.Tensor, eps: float, group_size: int
|
||||
) -> torch.Tensor:
|
||||
"""Gated RMSNorm matching Zamba2RMSNormGated: gate -> group-wise RMSNorm -> weight."""
|
||||
input_dtype = x.dtype
|
||||
x = x.to(torch.float32)
|
||||
if gate is not None:
|
||||
x = x * torch.nn.functional.silu(gate.to(torch.float32))
|
||||
*prefix_dims, last_dim = x.shape
|
||||
group_count = last_dim // group_size
|
||||
x_grouped = x.view(*prefix_dims, group_count, group_size)
|
||||
variance = x_grouped.pow(2).mean(-1, keepdim=True)
|
||||
x_grouped = x_grouped * torch.rsqrt(variance + eps)
|
||||
x = x_grouped.view(*prefix_dims, last_dim)
|
||||
return (weight * x).to(input_dtype)
|
||||
@@ -13,6 +13,7 @@ from torch import nn
|
||||
from torch.distributed.tensor import DTensor
|
||||
|
||||
from prime_rl.trainer.distributed.token_dispatcher import LocalTokenDispatcher, TokenDispatcher
|
||||
from prime_rl.trainer.models.fusions import fuse_gate_up_projections
|
||||
from prime_rl.trainer.models.layers.activations import ActivationDispatch, ActivationType
|
||||
from prime_rl.trainer.models.layers.grouped_gemm import BF16GroupedGemm, GroupedGemm
|
||||
from prime_rl.trainer.models.layers.mlp import ExpertType, FeedForward
|
||||
@@ -82,6 +83,8 @@ def broadcast_expert_bias(
|
||||
|
||||
|
||||
class GroupedExperts(nn.Module):
|
||||
supported_fusions = {"gate_up": fuse_gate_up_projections}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dim: int,
|
||||
@@ -98,6 +101,7 @@ class GroupedExperts(nn.Module):
|
||||
self.hidden_dim = hidden_dim
|
||||
self.gate_proj = nn.Parameter(torch.empty(num_experts, hidden_dim, dim)) if expert_type == "gated" else None
|
||||
self.up_proj = nn.Parameter(torch.empty(num_experts, hidden_dim, dim))
|
||||
self.register_parameter("gate_up_proj", None)
|
||||
self.down_proj = nn.Parameter(torch.empty(num_experts, dim, hidden_dim))
|
||||
self.gate_proj_bias = (
|
||||
nn.Parameter(torch.empty(num_experts, hidden_dim)) if bias and self.gate_proj is not None else None
|
||||
@@ -107,6 +111,8 @@ class GroupedExperts(nn.Module):
|
||||
|
||||
self.grouped_gemm = grouped_gemm or BF16GroupedGemm()
|
||||
self.activation = ActivationDispatch[activation]
|
||||
if expert_type == "non_gated":
|
||||
self.supported_fusions = {}
|
||||
|
||||
@property
|
||||
def token_group_alignment(self) -> int:
|
||||
@@ -128,19 +134,26 @@ class GroupedExperts(nn.Module):
|
||||
offsets = torch.cumsum(num_tokens_per_expert, dim=0, dtype=torch.int32)
|
||||
x_bf16 = x.bfloat16()
|
||||
|
||||
up_proj = to_local(self.up_proj).transpose(-2, -1)
|
||||
up = self.grouped_gemm(x_bf16, up_proj.bfloat16(), offs=offsets)
|
||||
if self.gate_up_proj is None:
|
||||
up_proj = to_local(self.up_proj).transpose(-2, -1)
|
||||
up = self.grouped_gemm(x_bf16, up_proj.bfloat16(), offs=offsets)
|
||||
|
||||
gate = None
|
||||
if self.gate_proj is not None:
|
||||
gate_proj = to_local(self.gate_proj).transpose(-2, -1)
|
||||
gate = self.grouped_gemm(x_bf16, gate_proj.bfloat16(), offs=offsets)
|
||||
else:
|
||||
gate_up_proj = to_local(self.gate_up_proj).transpose(-2, -1)
|
||||
gate_up = self.grouped_gemm(x_bf16, gate_up_proj.bfloat16(), offs=offsets)
|
||||
gate, up = gate_up.chunk(2, dim=-1)
|
||||
|
||||
if self.up_proj_bias is not None:
|
||||
up_proj_bias = to_local(self.up_proj_bias)
|
||||
up = up + broadcast_expert_bias(up_proj_bias, num_tokens_per_expert, up.shape[0]).bfloat16()
|
||||
|
||||
gate = None
|
||||
if self.gate_proj is not None:
|
||||
gate_proj = to_local(self.gate_proj).transpose(-2, -1)
|
||||
gate = self.grouped_gemm(x_bf16, gate_proj.bfloat16(), offs=offsets)
|
||||
if self.gate_proj_bias is not None:
|
||||
gate_proj_bias = to_local(self.gate_proj_bias)
|
||||
gate = gate + broadcast_expert_bias(gate_proj_bias, num_tokens_per_expert, gate.shape[0]).bfloat16()
|
||||
if gate is not None and self.gate_proj_bias is not None:
|
||||
gate_proj_bias = to_local(self.gate_proj_bias)
|
||||
gate = gate + broadcast_expert_bias(gate_proj_bias, num_tokens_per_expert, gate.shape[0]).bfloat16()
|
||||
|
||||
hidden = self.activation.apply(gate, up)
|
||||
down_proj = to_local(self.down_proj).transpose(-2, -1)
|
||||
@@ -151,9 +164,14 @@ class GroupedExperts(nn.Module):
|
||||
return output.type_as(x)
|
||||
|
||||
def init_weights(self, init_std: float):
|
||||
first_projection = self.gate_proj if self.gate_proj is not None else self.up_proj
|
||||
nn.init.trunc_normal_(first_projection, mean=0.0, std=0.02)
|
||||
remaining = (self.up_proj, self.down_proj) if self.gate_proj is not None else (self.down_proj,)
|
||||
if self.gate_up_proj is None:
|
||||
first_projection = self.gate_proj if self.gate_proj is not None else self.up_proj
|
||||
nn.init.trunc_normal_(first_projection, mean=0.0, std=0.02)
|
||||
remaining = (self.up_proj, self.down_proj) if self.gate_proj is not None else (self.down_proj,)
|
||||
else:
|
||||
gate_proj, up_proj = self.gate_up_proj.chunk(2, dim=1)
|
||||
nn.init.trunc_normal_(gate_proj, mean=0.0, std=0.02)
|
||||
remaining = (up_proj, self.down_proj)
|
||||
for weight in remaining:
|
||||
nn.init.trunc_normal_(weight, mean=0.0, std=init_std)
|
||||
for bias in (self.gate_proj_bias, self.up_proj_bias, self.down_proj_bias):
|
||||
|
||||
@@ -15,9 +15,8 @@ Ulysses is the simpler alternative to ring attention for context parallelism:
|
||||
[S/cp, H, D] ◀── all-to-all ── [S, H/cp, D]
|
||||
(seq ↔ heads)
|
||||
|
||||
Key benefit: the attention kernel itself does not need to be CP-aware. The
|
||||
all-to-all is purely on Q/K/V tensors, so this works out of the box with
|
||||
softmax flash-attn, linear attention, mamba, etc., without rewriting kernels.
|
||||
The softmax-attention kernel itself does not need to be CP-aware. Hybrid models
|
||||
use the same sequence/head redistribution in their owned recurrent modules.
|
||||
|
||||
GQA models with fewer KV heads than cp_size (e.g. NemotronH: 32 query heads, 2
|
||||
KV heads) are handled by replicating each KV head cp_size / num_key_value_heads
|
||||
@@ -120,6 +119,7 @@ def ulysses_flash_attn_varlen_func(
|
||||
softmax_scale: float | None = None,
|
||||
dropout_p: float = 0.0,
|
||||
deterministic: bool | None = None,
|
||||
learnable_sink: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Run varlen flash attention under Ulysses CP.
|
||||
|
||||
@@ -146,17 +146,20 @@ def ulysses_flash_attn_varlen_func(
|
||||
kwargs["dropout_p"] = dropout_p
|
||||
if deterministic is not None:
|
||||
kwargs["deterministic"] = deterministic
|
||||
if learnable_sink is not None:
|
||||
local_heads = q.shape[1]
|
||||
rank = dist.get_rank(cp_group)
|
||||
kwargs["learnable_sink"] = learnable_sink[rank * local_heads : (rank + 1) * local_heads]
|
||||
|
||||
if flash_attn_version == 4:
|
||||
# FA4 takes cu_seqlens as keyword args (qv positional collides otherwise).
|
||||
kwargs["cu_seqlens_q"] = cu_seqlens_q
|
||||
kwargs["cu_seqlens_k"] = cu_seqlens_k
|
||||
out = flash_fn(q, k, v, **kwargs)
|
||||
kwargs["max_seqlen_q"] = max_seqlen_q
|
||||
kwargs["max_seqlen_k"] = max_seqlen_k
|
||||
out, _ = flash_fn(q, k, v, **kwargs)
|
||||
else:
|
||||
out = flash_fn(q, k, v, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, **kwargs)
|
||||
if isinstance(out, tuple):
|
||||
out = out[0]
|
||||
|
||||
return _all_to_all_head_to_seq(out, cp_size, cp_group)
|
||||
|
||||
|
||||
@@ -176,7 +179,6 @@ def substitute_ulysses_attn(
|
||||
from flash_attn.cute import flash_attn_varlen_func as flash_fn
|
||||
|
||||
flash_attn_version = 4
|
||||
flash_fn = torch._dynamo.disable(flash_fn)
|
||||
elif attn_impl == "flash_attention_3":
|
||||
from flash_attn_interface import flash_attn_varlen_func as flash_fn
|
||||
|
||||
@@ -221,13 +223,9 @@ def substitute_ulysses_attn(
|
||||
|
||||
AfmoeFlashAttention._compute_attention = _ulysses_compute_attention
|
||||
|
||||
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeGatedFlashAttention
|
||||
from prime_rl.trainer.models.gpt_oss.attention import substitute_gpt_oss_ulysses_attention
|
||||
|
||||
Qwen3_5MoeGatedFlashAttention._compute_attention = _ulysses_compute_attention
|
||||
|
||||
from prime_rl.trainer.models.qwen3_5.modeling_qwen3_5 import Qwen3_5GatedFlashAttention
|
||||
|
||||
Qwen3_5GatedFlashAttention._compute_attention = _ulysses_compute_attention
|
||||
substitute_gpt_oss_ulysses_attention(process_group)
|
||||
|
||||
|
||||
def substitute_hf_ulysses_attn(process_group: dist.ProcessGroup) -> None:
|
||||
|
||||
@@ -2,217 +2,142 @@ from transformers.configuration_utils import PretrainedConfig
|
||||
|
||||
|
||||
class NemotronHConfig(PretrainedConfig):
|
||||
"""Configuration for NemotronH (Nemotron-3-Super-120B-A12B) hybrid Mamba-Transformer-MoE model.
|
||||
|
||||
The model architecture is defined by `layers_block_type`, a list where each element is
|
||||
one of "mamba", "attention", or "moe". The 120B model uses a pattern like MEMEMEM*EMEMEMEM*...
|
||||
(M=Mamba-2, E=MoE with latent projections, *=Attention) repeated across 88 layers.
|
||||
|
||||
Args:
|
||||
vocab_size: Vocabulary size.
|
||||
hidden_size: Dimension of the hidden representations.
|
||||
layers_block_type: Explicit list of layer types. Determines num_hidden_layers.
|
||||
tie_word_embeddings: Whether to tie input/output embeddings.
|
||||
pad_token_id: Padding token id.
|
||||
bos_token_id: Beginning of sequence token id.
|
||||
eos_token_id: End of sequence token id.
|
||||
num_attention_heads: Number of attention heads.
|
||||
num_key_value_heads: Number of key/value heads for GQA.
|
||||
head_dim: Dimension of each attention head.
|
||||
max_position_embeddings: Maximum sequence length.
|
||||
attention_bias: Whether to use bias in attention layers.
|
||||
intermediate_size: MLP intermediate dimension (for shared expert).
|
||||
mlp_hidden_act: Activation function for MLP layers.
|
||||
mlp_bias: Whether to use bias in MLP layers.
|
||||
use_mamba_kernels: Whether to use fast mamba CUDA kernels.
|
||||
ssm_state_size: Mamba state space dimension.
|
||||
mamba_num_heads: Number of mamba heads.
|
||||
mamba_n_groups: Number of groups in mamba.
|
||||
mamba_head_dim: Dimension per mamba head.
|
||||
mamba_d_conv: Convolution kernel size.
|
||||
mamba_expand: Expansion factor.
|
||||
mamba_hidden_act: Activation for mamba layers.
|
||||
mamba_dt_min: Time step minimum.
|
||||
mamba_dt_max: Time step maximum.
|
||||
mamba_dt_limit: Time step limits.
|
||||
mamba_dt_init_floor: Floor for time step initialization.
|
||||
mamba_conv_bias: Whether to use bias in mamba convolution.
|
||||
mamba_proj_bias: Whether to use bias in mamba projections.
|
||||
mamba_chunk_size: Chunk size for mamba processing.
|
||||
n_routed_experts: Number of routed experts.
|
||||
n_shared_experts: Number of shared experts.
|
||||
moe_intermediate_size: Expert intermediate dimension.
|
||||
moe_shared_expert_intermediate_size: Shared expert intermediate dimension.
|
||||
moe_latent_size: Latent projection size (None means use hidden_size).
|
||||
num_experts_per_tok: Top-k routing parameter.
|
||||
routed_scaling_factor: Scaling factor for routed expert outputs.
|
||||
norm_topk_prob: Whether to normalize top-k probabilities.
|
||||
use_bias: Global bias setting.
|
||||
initializer_range: Standard deviation for weight initialization.
|
||||
layer_norm_epsilon: Epsilon for layer normalization.
|
||||
residual_in_fp32: Whether to keep residuals in fp32.
|
||||
rescale_prenorm_residual: Whether to rescale pre-norm residuals.
|
||||
load_balance_coeff: Auxiliary-loss-free load balancing coefficient.
|
||||
"""
|
||||
|
||||
model_type = "nemotron_h"
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
|
||||
PATTERN_MAP = {"M": "mamba", "E": "moe", "*": "attention"}
|
||||
REVERSE_PATTERN_MAP = {"mamba": "M", "moe": "E", "attention": "*"}
|
||||
PATTERN_TO_LAYER_TYPE = {
|
||||
"M": "mamba",
|
||||
"E": "moe",
|
||||
"*": "attention",
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
# General
|
||||
vocab_size=131072,
|
||||
hidden_size=4096,
|
||||
layers_block_type=None,
|
||||
num_hidden_layers=None,
|
||||
tie_word_embeddings=False,
|
||||
pad_token_id=0,
|
||||
bos_token_id=1,
|
||||
eos_token_id=2,
|
||||
# Attention
|
||||
num_attention_heads=32,
|
||||
num_key_value_heads=8,
|
||||
head_dim=128,
|
||||
max_position_embeddings=4096,
|
||||
attention_bias=False,
|
||||
# MLP
|
||||
intermediate_size=21504,
|
||||
mlp_hidden_act="relu2",
|
||||
mlp_bias=False,
|
||||
# Mamba
|
||||
use_mamba_kernels=True,
|
||||
ssm_state_size=128,
|
||||
mamba_num_heads=128,
|
||||
mamba_n_groups=8,
|
||||
mamba_head_dim=64,
|
||||
mamba_d_conv=4,
|
||||
mamba_expand=2,
|
||||
mamba_hidden_act="silu",
|
||||
mamba_dt_min=0.001,
|
||||
mamba_dt_max=0.1,
|
||||
mamba_dt_limit=(0.0, float("inf")),
|
||||
mamba_dt_init_floor=1e-4,
|
||||
mamba_conv_bias=True,
|
||||
mamba_proj_bias=False,
|
||||
mamba_chunk_size=128,
|
||||
# MoE
|
||||
n_routed_experts=8,
|
||||
n_shared_experts=1,
|
||||
moe_intermediate_size=7688,
|
||||
moe_shared_expert_intermediate_size=7688,
|
||||
moe_latent_size=None,
|
||||
num_experts_per_tok=2,
|
||||
routed_scaling_factor=1.0,
|
||||
norm_topk_prob=True,
|
||||
# General training
|
||||
use_bias=False,
|
||||
initializer_range=0.02,
|
||||
layer_norm_epsilon=1e-5,
|
||||
residual_in_fp32=False,
|
||||
rescale_prenorm_residual=True,
|
||||
# PrimeRL training features
|
||||
load_balance_coeff=None,
|
||||
# RoPE
|
||||
rope_theta=10000.0,
|
||||
rope_scaling=None,
|
||||
vocab_size: int = 131072,
|
||||
hidden_size: int = 4096,
|
||||
num_hidden_layers: int | None = None,
|
||||
hybrid_override_pattern: str | None = None,
|
||||
layers_block_type: list[str] | None = None,
|
||||
num_attention_heads: int = 32,
|
||||
num_key_value_heads: int = 8,
|
||||
head_dim: int = 128,
|
||||
max_position_embeddings: int = 4096,
|
||||
attention_bias: bool = False,
|
||||
attention_dropout: float = 0.0,
|
||||
intermediate_size: int = 21504,
|
||||
mlp_hidden_act: str = "relu2",
|
||||
mlp_bias: bool = False,
|
||||
ssm_state_size: int = 128,
|
||||
mamba_num_heads: int = 128,
|
||||
mamba_head_dim: int = 64,
|
||||
mamba_hidden_act: str = "silu",
|
||||
n_groups: int = 8,
|
||||
conv_kernel: int = 4,
|
||||
expand: int = 2,
|
||||
time_step_min: float = 0.001,
|
||||
time_step_max: float = 0.1,
|
||||
time_step_limit: tuple[float, float] | list[float] | None = (0.0, float("inf")),
|
||||
time_step_floor: float = 1e-4,
|
||||
use_conv_bias: bool = True,
|
||||
chunk_size: int = 128,
|
||||
mamba_proj_bias: bool = False,
|
||||
n_routed_experts: int = 8,
|
||||
n_shared_experts: int = 1,
|
||||
moe_intermediate_size: int = 7688,
|
||||
moe_shared_expert_intermediate_size: int = 7688,
|
||||
moe_latent_size: int | None = None,
|
||||
moe_shared_expert_overlap: bool = True,
|
||||
num_experts_per_tok: int = 2,
|
||||
routed_scaling_factor: float = 1.0,
|
||||
n_group: int = 1,
|
||||
topk_group: int = 1,
|
||||
norm_topk_prob: bool = True,
|
||||
use_bias: bool = False,
|
||||
initializer_range: float = 0.02,
|
||||
layer_norm_epsilon: float = 1e-5,
|
||||
residual_in_fp32: bool = False,
|
||||
hidden_dropout: float = 0.0,
|
||||
rescale_prenorm_residual: bool = True,
|
||||
load_balance_coeff: float | None = None,
|
||||
tie_word_embeddings: bool = False,
|
||||
pad_token_id: int | None = 0,
|
||||
bos_token_id: int | None = 1,
|
||||
eos_token_id: int | list[int] | None = 2,
|
||||
**kwargs,
|
||||
):
|
||||
# Handle hybrid_override_pattern for backward compatibility
|
||||
if "hybrid_override_pattern" in kwargs:
|
||||
pattern = kwargs.pop("hybrid_override_pattern")
|
||||
if layers_block_type is None:
|
||||
layers_block_type = [self.PATTERN_MAP[c] for c in pattern]
|
||||
|
||||
) -> None:
|
||||
if layers_block_type is None:
|
||||
layers_block_type = ["mamba", "moe", "attention", "moe"]
|
||||
|
||||
pattern = hybrid_override_pattern or "ME*E"
|
||||
layers_block_type = [self.PATTERN_TO_LAYER_TYPE[token] for token in pattern]
|
||||
self.vocab_size = vocab_size
|
||||
self.hidden_size = hidden_size
|
||||
self.layers_block_type = layers_block_type
|
||||
|
||||
# Attention config
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.num_key_value_heads = num_key_value_heads if num_key_value_heads is not None else num_attention_heads
|
||||
self.num_key_value_heads = num_key_value_heads
|
||||
self.head_dim = head_dim
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
self.attention_bias = attention_bias
|
||||
self.rope_theta = rope_theta
|
||||
self.rope_scaling = rope_scaling
|
||||
self.attention_dropout = attention_dropout
|
||||
|
||||
# MLP config
|
||||
self.intermediate_size = intermediate_size
|
||||
self.mlp_hidden_act = mlp_hidden_act
|
||||
self.mlp_bias = mlp_bias
|
||||
|
||||
# Mamba config - stored with HF-compatible attribute names used by NemotronHMamba2Mixer
|
||||
self.use_mamba_kernels = use_mamba_kernels
|
||||
self.ssm_state_size = ssm_state_size
|
||||
self.mamba_num_heads = mamba_num_heads
|
||||
self.n_groups = mamba_n_groups
|
||||
self.mamba_head_dim = mamba_head_dim
|
||||
self.conv_kernel = mamba_d_conv
|
||||
self.expand = mamba_expand
|
||||
self.mamba_hidden_act = mamba_hidden_act
|
||||
self.time_step_min = mamba_dt_min
|
||||
self.time_step_max = mamba_dt_max
|
||||
self.time_step_limit = mamba_dt_limit
|
||||
self.time_step_floor = mamba_dt_init_floor
|
||||
self.use_conv_bias = mamba_conv_bias
|
||||
self.n_groups = n_groups
|
||||
self.conv_kernel = conv_kernel
|
||||
self.expand = expand
|
||||
self.time_step_min = time_step_min
|
||||
self.time_step_max = time_step_max
|
||||
self.time_step_limit = time_step_limit
|
||||
self.time_step_floor = time_step_floor
|
||||
self.use_conv_bias = use_conv_bias
|
||||
self.chunk_size = chunk_size
|
||||
self.mamba_proj_bias = mamba_proj_bias
|
||||
self.chunk_size = mamba_chunk_size
|
||||
|
||||
# Zamba2MambaMixer compat aliases (read by parent __init__ before NemotronHMamba2Mixer overrides).
|
||||
# mamba_expand must give the correct intermediate_size = mamba_num_heads * mamba_head_dim
|
||||
# when Zamba2 computes int(mamba_expand * hidden_size); the config's raw "expand" field
|
||||
# does not satisfy this for all model sizes (e.g. Nemotron-3-Nano-30B).
|
||||
self.mamba_d_state = ssm_state_size
|
||||
self.mamba_d_conv = mamba_d_conv
|
||||
self.mamba_expand = (mamba_num_heads * mamba_head_dim) / hidden_size
|
||||
self.mamba_ngroups = mamba_n_groups
|
||||
self.mamba_headdim = mamba_head_dim
|
||||
self.n_mamba_heads = mamba_num_heads
|
||||
self.use_mem_eff_path = True
|
||||
self.add_bias_linear = use_bias
|
||||
|
||||
# MoE config
|
||||
self.n_routed_experts = n_routed_experts
|
||||
self.n_shared_experts = n_shared_experts
|
||||
self.moe_intermediate_size = moe_intermediate_size
|
||||
self.moe_shared_expert_intermediate_size = moe_shared_expert_intermediate_size
|
||||
self.moe_latent_size = moe_latent_size
|
||||
self.moe_shared_expert_overlap = moe_shared_expert_overlap
|
||||
self.num_experts_per_tok = num_experts_per_tok
|
||||
self.routed_scaling_factor = routed_scaling_factor
|
||||
self.n_group = n_group
|
||||
self.topk_group = topk_group
|
||||
self.norm_topk_prob = norm_topk_prob
|
||||
|
||||
# General training config
|
||||
self.use_bias = use_bias
|
||||
self.initializer_range = initializer_range
|
||||
self.layer_norm_epsilon = layer_norm_epsilon
|
||||
self.residual_in_fp32 = residual_in_fp32
|
||||
self.hidden_dropout = hidden_dropout
|
||||
self.rescale_prenorm_residual = rescale_prenorm_residual
|
||||
|
||||
# PrimeRL training features
|
||||
self.load_balance_coeff = load_balance_coeff
|
||||
|
||||
super().__init__(
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
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,
|
||||
)
|
||||
|
||||
@property
|
||||
def layer_types(self) -> list[str]:
|
||||
return self.layers_block_type
|
||||
|
||||
@property
|
||||
def num_hidden_layers(self) -> int:
|
||||
return len(self.layers_block_type)
|
||||
|
||||
@num_hidden_layers.setter
|
||||
def num_hidden_layers(self, value):
|
||||
if value is not None and value < len(self.layers_block_type):
|
||||
self.layers_block_type = self.layers_block_type[:value]
|
||||
def num_hidden_layers(self, value: int | None) -> None:
|
||||
if value is None or not hasattr(self, "layers_block_type"):
|
||||
return
|
||||
self.layers_block_type = self.layers_block_type[:value]
|
||||
|
||||
|
||||
__all__ = ["NemotronHConfig"]
|
||||
|
||||
@@ -1,100 +1,55 @@
|
||||
"""Declarative HF<->prime conversion chain for NemotronH.
|
||||
from torch import Tensor
|
||||
|
||||
NemotronH is the most involved conversion: a unified HF ``mixer`` namespace is
|
||||
split into prime's ``mamba`` / ``self_attn`` / ``mlp`` by layer type, the
|
||||
checkpoint uses a ``backbone.`` prefix, and the MoE router bias is shifted by
|
||||
its per-tensor min on the way in (and intentionally *not* restored on the way
|
||||
out — a lossy roundtrip the chain reproduces via a :class:`MapValue` whose
|
||||
backward is the identity). Experts are up/down only, with no gate projection.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from prime_rl.trainer.models.conversion_ops import (
|
||||
Conditional,
|
||||
ConvOp,
|
||||
Drop,
|
||||
MapValue,
|
||||
PrefixRename,
|
||||
Rename,
|
||||
Stack,
|
||||
key_present,
|
||||
)
|
||||
from prime_rl.trainer.models.conversion_ops import ConvOp, Drop, PrefixRename, Rename, Stack
|
||||
from prime_rl.trainer.models.nemotron_h.configuration_nemotron_h import NemotronHConfig
|
||||
|
||||
|
||||
def _moe_layer_ops(prefix: str) -> list[ConvOp]:
|
||||
return [
|
||||
# Router gate and selection bias.
|
||||
# plus the load-balancing bias which is shifted by its min on the way in
|
||||
# and not undone on the way out (MapValue backward = identity).
|
||||
Rename(f"{prefix}.mixer.gate.weight", f"{prefix}.mlp.router.gate.weight"),
|
||||
Rename(f"{prefix}.mixer.gate.e_score_correction_bias", f"{prefix}.mlp.router.selection_bias"),
|
||||
MapValue(
|
||||
f"{prefix}.mlp.router.selection_bias",
|
||||
forward=lambda x: x - x.min(),
|
||||
backward=lambda x: x,
|
||||
),
|
||||
# Experts are up/down only. HF is either per-expert weights or
|
||||
# a 3-D fused-at-experts-level up_proj/down_proj. Backward always emits
|
||||
# per-expert (the predicate's HF key is absent in prime -> else branch).
|
||||
Conditional(
|
||||
predicate=key_present(f"{prefix}.mixer.experts.up_proj"),
|
||||
then=[
|
||||
Rename(f"{prefix}.mixer.experts.up_proj", f"{prefix}.mlp.experts.up_proj"),
|
||||
Rename(f"{prefix}.mixer.experts.down_proj", f"{prefix}.mlp.experts.down_proj"),
|
||||
],
|
||||
else_=[
|
||||
Stack(
|
||||
stacked=f"{prefix}.mlp.experts.up_proj",
|
||||
item=f"{prefix}.mixer.experts.{{e}}.up_proj.weight",
|
||||
),
|
||||
Stack(
|
||||
stacked=f"{prefix}.mlp.experts.down_proj",
|
||||
item=f"{prefix}.mixer.experts.{{e}}.down_proj.weight",
|
||||
),
|
||||
],
|
||||
),
|
||||
PrefixRename(f"{prefix}.mixer.shared_experts.", f"{prefix}.mlp.shared_expert."),
|
||||
PrefixRename(f"{prefix}.mixer.fc1_latent_proj.", f"{prefix}.mlp.fc1_latent_proj."),
|
||||
PrefixRename(f"{prefix}.mixer.fc2_latent_proj.", f"{prefix}.mlp.fc2_latent_proj."),
|
||||
]
|
||||
def is_hf_state_dict(state_dict: dict[str, Tensor]) -> bool:
|
||||
return "backbone.embeddings.weight" in state_dict or any(".mixer." in name for name in state_dict)
|
||||
|
||||
|
||||
def _layer_op(prefix: str) -> ConvOp:
|
||||
"""One uniform op for any layer: detect its type from a signature key and
|
||||
dispatch. No ``layers_block_type`` needed — the unified HF ``mixer.``
|
||||
namespace is disambiguated by which sub-key is present (and, on the way
|
||||
back, by which prime namespace is present, so the predicates work both
|
||||
directions). Mamba/attention keep a bulk ``PrefixRename`` (robust to params
|
||||
we didn't enumerate); MoE needs its specific ops."""
|
||||
is_attention = lambda sd: ( # noqa: E731
|
||||
f"{prefix}.mixer.q_proj.weight" in sd or f"{prefix}.self_attn.q_proj.weight" in sd
|
||||
)
|
||||
is_moe = lambda sd: ( # noqa: E731
|
||||
f"{prefix}.mixer.gate.weight" in sd or f"{prefix}.mlp.router.gate.weight" in sd
|
||||
)
|
||||
return Conditional(
|
||||
is_attention,
|
||||
then=[PrefixRename(f"{prefix}.mixer.", f"{prefix}.self_attn.")],
|
||||
else_=[
|
||||
Conditional(
|
||||
is_moe,
|
||||
then=_moe_layer_ops(prefix),
|
||||
else_=[PrefixRename(f"{prefix}.mixer.", f"{prefix}.mamba.")],
|
||||
)
|
||||
],
|
||||
def is_prime_state_dict(state_dict: dict[str, Tensor]) -> bool:
|
||||
return "model.embed_tokens.weight" in state_dict or any(
|
||||
namespace in name for name in state_dict for namespace in (".mamba.", ".self_attn.", ".mlp.router.")
|
||||
)
|
||||
|
||||
|
||||
def conversion_chain(config) -> list[ConvOp]:
|
||||
"""Uniform per-layer dispatch — no ``layers_block_type`` required."""
|
||||
def conversion_chain(config: NemotronHConfig) -> list[ConvOp]:
|
||||
ops: list[ConvOp] = [
|
||||
# Global. Listed first so the backbone<->model swap is played LAST on the
|
||||
# way back (everything must be in model.* form before re-prefixing).
|
||||
PrefixRename("backbone.", "model."),
|
||||
Drop("mtp.", is_prefix=True),
|
||||
Rename("model.embeddings.weight", "model.embed_tokens.weight"),
|
||||
Rename("model.norm_f.weight", "model.norm.weight"),
|
||||
]
|
||||
ops.extend(_layer_op(f"model.layers.{i}") for i in range(config.num_hidden_layers))
|
||||
|
||||
for layer_idx, layer_type in enumerate(config.layer_types):
|
||||
prefix = f"model.layers.{layer_idx}"
|
||||
if layer_type == "mamba":
|
||||
ops.append(PrefixRename(f"{prefix}.mixer.", f"{prefix}.mamba."))
|
||||
elif layer_type == "attention":
|
||||
ops.append(PrefixRename(f"{prefix}.mixer.", f"{prefix}.self_attn."))
|
||||
elif layer_type == "moe":
|
||||
ops.extend(
|
||||
[
|
||||
Rename(f"{prefix}.mixer.gate.weight", f"{prefix}.mlp.router.gate.weight"),
|
||||
Rename(
|
||||
f"{prefix}.mixer.gate.e_score_correction_bias",
|
||||
f"{prefix}.mlp.router.selection_bias",
|
||||
),
|
||||
Stack(
|
||||
stacked=f"{prefix}.mlp.experts.up_proj",
|
||||
item=f"{prefix}.mixer.experts.{{e}}.up_proj.weight",
|
||||
),
|
||||
Stack(
|
||||
stacked=f"{prefix}.mlp.experts.down_proj",
|
||||
item=f"{prefix}.mixer.experts.{{e}}.down_proj.weight",
|
||||
),
|
||||
PrefixRename(f"{prefix}.mixer.shared_experts.", f"{prefix}.mlp.shared_expert."),
|
||||
PrefixRename(f"{prefix}.mixer.fc1_latent_proj.", f"{prefix}.mlp.fc1_latent_proj."),
|
||||
PrefixRename(f"{prefix}.mixer.fc2_latent_proj.", f"{prefix}.mlp.fc2_latent_proj."),
|
||||
]
|
||||
)
|
||||
return ops
|
||||
|
||||
|
||||
__all__ = ["conversion_chain", "is_hf_state_dict", "is_prime_state_dict"]
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
"""Nemotron-H Mamba-2 and context-parallel execution.
|
||||
|
||||
Packed training needs the convolution and state-space scan to reset at every
|
||||
document boundary. Under Ulysses context parallelism, each rank also needs the
|
||||
full sequence for its local Mamba heads because recurrent state cannot be split
|
||||
along the sequence.
|
||||
"""
|
||||
|
||||
import math
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.trainer.distributed.collectives import all_to_all_single_equal
|
||||
from prime_rl.trainer.models.nemotron_h.configuration_nemotron_h import NemotronHConfig
|
||||
from prime_rl.utils.cp import CPContext
|
||||
|
||||
|
||||
def sequence_to_head_parallel(
|
||||
tensor: torch.Tensor,
|
||||
process_group: dist.ProcessGroup,
|
||||
world_size: int,
|
||||
) -> torch.Tensor:
|
||||
"""Redistribute ``[B, S/world, D]`` into ``[B, S, D/world]``."""
|
||||
batch_size, local_sequence_length, feature_size = tensor.shape
|
||||
local_feature_size = feature_size // world_size
|
||||
tensor = tensor.reshape(batch_size, local_sequence_length, world_size, local_feature_size)
|
||||
tensor = tensor.permute(2, 0, 1, 3).contiguous()
|
||||
tensor = all_to_all_single_equal(tensor, process_group)
|
||||
return tensor.permute(1, 0, 2, 3).reshape(
|
||||
batch_size,
|
||||
world_size * local_sequence_length,
|
||||
local_feature_size,
|
||||
)
|
||||
|
||||
|
||||
def head_to_sequence_parallel(
|
||||
tensor: torch.Tensor,
|
||||
process_group: dist.ProcessGroup,
|
||||
world_size: int,
|
||||
) -> torch.Tensor:
|
||||
"""Redistribute ``[B, S, D/world]`` into ``[B, S/world, D]``."""
|
||||
batch_size, sequence_length, local_feature_size = tensor.shape
|
||||
local_sequence_length = sequence_length // world_size
|
||||
tensor = tensor.reshape(batch_size, world_size, local_sequence_length, local_feature_size)
|
||||
tensor = tensor.permute(1, 0, 2, 3).contiguous()
|
||||
tensor = all_to_all_single_equal(tensor, process_group)
|
||||
return tensor.permute(1, 2, 0, 3).reshape(
|
||||
batch_size,
|
||||
local_sequence_length,
|
||||
world_size * local_feature_size,
|
||||
)
|
||||
|
||||
|
||||
class GatedRMSNorm(nn.Module):
|
||||
def __init__(self, hidden_size: int, group_size: int, eps: float) -> None:
|
||||
super().__init__()
|
||||
self.weight = nn.Parameter(torch.ones(hidden_size))
|
||||
self.group_size = group_size
|
||||
self.variance_epsilon = eps
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
gate: torch.Tensor,
|
||||
weight: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
input_dtype = hidden_states.dtype
|
||||
hidden_states = hidden_states.float() * torch.nn.functional.silu(gate.float())
|
||||
group_count = hidden_states.shape[-1] // self.group_size
|
||||
grouped_states = hidden_states.reshape(*hidden_states.shape[:-1], group_count, self.group_size)
|
||||
variance = grouped_states.square().mean(dim=-1, keepdim=True)
|
||||
hidden_states = (grouped_states * torch.rsqrt(variance + self.variance_epsilon)).flatten(-2)
|
||||
return (self.weight if weight is None else weight) * hidden_states.to(input_dtype)
|
||||
|
||||
|
||||
class NemotronHMamba2(nn.Module):
|
||||
def __init__(self, config: NemotronHConfig) -> None:
|
||||
super().__init__()
|
||||
from fla.modules.conv import causal_conv1d
|
||||
from fla.ops.utils import prepare_sequence_ids
|
||||
from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined
|
||||
|
||||
self.hidden_size = config.hidden_size
|
||||
self.state_size = config.ssm_state_size
|
||||
self.num_heads = config.mamba_num_heads
|
||||
self.head_dim = config.mamba_head_dim
|
||||
self.num_groups = config.n_groups
|
||||
self.intermediate_size = self.num_heads * self.head_dim
|
||||
self.group_state_size = self.num_groups * self.state_size
|
||||
self.conv_size = self.intermediate_size + 2 * self.group_state_size
|
||||
self.chunk_size = config.chunk_size
|
||||
self.time_step_limit = config.time_step_limit
|
||||
self.activation = config.mamba_hidden_act
|
||||
|
||||
projection_size = self.intermediate_size + self.conv_size + self.num_heads
|
||||
self.in_proj = nn.Linear(config.hidden_size, projection_size, bias=config.use_bias)
|
||||
self.conv1d = nn.Conv1d(
|
||||
self.conv_size,
|
||||
self.conv_size,
|
||||
kernel_size=config.conv_kernel,
|
||||
groups=self.conv_size,
|
||||
padding=config.conv_kernel - 1,
|
||||
bias=config.use_conv_bias,
|
||||
)
|
||||
self.dt_bias = nn.Parameter(torch.empty(self.num_heads))
|
||||
self.A_log = nn.Parameter(torch.log(torch.arange(1, self.num_heads + 1, dtype=torch.float32)))
|
||||
self.D = nn.Parameter(torch.ones(self.num_heads, dtype=torch.float32))
|
||||
self.norm = GatedRMSNorm(
|
||||
self.intermediate_size,
|
||||
group_size=self.intermediate_size // self.num_groups,
|
||||
eps=config.layer_norm_epsilon,
|
||||
)
|
||||
self.out_proj = nn.Linear(self.intermediate_size, config.hidden_size, bias=config.use_bias)
|
||||
self.causal_conv1d = causal_conv1d
|
||||
self.prepare_sequence_ids = prepare_sequence_ids
|
||||
self.scan = mamba_chunk_scan_combined
|
||||
|
||||
time_steps = torch.exp(
|
||||
torch.rand(self.num_heads, dtype=torch.float32)
|
||||
* (math.log(config.time_step_max) - math.log(config.time_step_min))
|
||||
+ math.log(config.time_step_min)
|
||||
).clamp(min=config.time_step_floor)
|
||||
with torch.no_grad():
|
||||
self.dt_bias.copy_((time_steps + torch.log(-torch.expm1(-time_steps))).to(self.dt_bias.dtype))
|
||||
|
||||
self.cp_context = CPContext()
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor) -> torch.Tensor:
|
||||
batch_size, sequence_length, _ = hidden_states.shape
|
||||
projected_states = self.in_proj(hidden_states)
|
||||
gate, convolution_input, time_step = torch.split(
|
||||
projected_states,
|
||||
[self.intermediate_size, self.conv_size, self.num_heads],
|
||||
dim=-1,
|
||||
)
|
||||
|
||||
num_heads = self.num_heads
|
||||
num_groups = self.num_groups
|
||||
intermediate_size = self.intermediate_size
|
||||
conv_weight = self.conv1d.weight
|
||||
conv_bias = self.conv1d.bias
|
||||
state_decay = -torch.exp(self.A_log.float())
|
||||
skip = self.D
|
||||
dt_bias = self.dt_bias
|
||||
norm_weight = self.norm.weight
|
||||
|
||||
if self.cp_context.cp_enabled:
|
||||
cp_group = self.cp_context.cp_group
|
||||
world_size = self.cp_context.cp_world_size
|
||||
rank = self.cp_context.cp_rank
|
||||
gate = sequence_to_head_parallel(gate, cp_group, world_size)
|
||||
time_step = sequence_to_head_parallel(time_step, cp_group, world_size)
|
||||
|
||||
recurrent_input, state_input, state_output = torch.split(
|
||||
convolution_input,
|
||||
[self.intermediate_size, self.group_state_size, self.group_state_size],
|
||||
dim=-1,
|
||||
)
|
||||
convolution_input = torch.cat(
|
||||
[
|
||||
sequence_to_head_parallel(recurrent_input, cp_group, world_size),
|
||||
sequence_to_head_parallel(state_input, cp_group, world_size),
|
||||
sequence_to_head_parallel(state_output, cp_group, world_size),
|
||||
],
|
||||
dim=-1,
|
||||
)
|
||||
|
||||
num_heads //= world_size
|
||||
num_groups //= world_size
|
||||
intermediate_size //= world_size
|
||||
head_start = rank * num_heads
|
||||
group_start = rank * num_groups * self.state_size
|
||||
intermediate_start = rank * intermediate_size
|
||||
|
||||
state_decay = state_decay[head_start : head_start + num_heads]
|
||||
skip = skip[head_start : head_start + num_heads]
|
||||
dt_bias = dt_bias[head_start : head_start + num_heads]
|
||||
norm_weight = norm_weight[intermediate_start : intermediate_start + intermediate_size]
|
||||
|
||||
state_input_start = self.intermediate_size + group_start
|
||||
state_output_start = self.intermediate_size + self.group_state_size + group_start
|
||||
conv_weight = torch.cat(
|
||||
[
|
||||
conv_weight[intermediate_start : intermediate_start + intermediate_size],
|
||||
conv_weight[state_input_start : state_input_start + num_groups * self.state_size],
|
||||
conv_weight[state_output_start : state_output_start + num_groups * self.state_size],
|
||||
]
|
||||
)
|
||||
if conv_bias is not None:
|
||||
conv_bias = torch.cat(
|
||||
[
|
||||
conv_bias[intermediate_start : intermediate_start + intermediate_size],
|
||||
conv_bias[state_input_start : state_input_start + num_groups * self.state_size],
|
||||
conv_bias[state_output_start : state_output_start + num_groups * self.state_size],
|
||||
]
|
||||
)
|
||||
sequence_length = convolution_input.shape[1]
|
||||
|
||||
convolution_output, _ = self.causal_conv1d(
|
||||
x=convolution_input,
|
||||
weight=conv_weight.squeeze(1),
|
||||
bias=conv_bias,
|
||||
activation=self.activation,
|
||||
cu_seqlens=cu_seqlens,
|
||||
)
|
||||
local_group_state_size = num_groups * self.state_size
|
||||
hidden_states, state_input, state_output = torch.split(
|
||||
convolution_output,
|
||||
[intermediate_size, local_group_state_size, local_group_state_size],
|
||||
dim=-1,
|
||||
)
|
||||
|
||||
scan_kwargs = {}
|
||||
if self.time_step_limit is not None:
|
||||
scan_kwargs["dt_limit"] = self.time_step_limit
|
||||
hidden_states = self.scan(
|
||||
hidden_states.reshape(batch_size, sequence_length, num_heads, self.head_dim),
|
||||
time_step,
|
||||
state_decay,
|
||||
state_input.reshape(batch_size, sequence_length, num_groups, self.state_size),
|
||||
state_output.reshape(batch_size, sequence_length, num_groups, self.state_size),
|
||||
chunk_size=self.chunk_size,
|
||||
D=skip,
|
||||
z=None,
|
||||
seq_idx=self.prepare_sequence_ids(cu_seqlens).to(torch.int32).unsqueeze(0),
|
||||
return_final_states=False,
|
||||
dt_bias=dt_bias,
|
||||
dt_softplus=True,
|
||||
**scan_kwargs,
|
||||
).reshape(batch_size, sequence_length, intermediate_size)
|
||||
hidden_states = self.norm(hidden_states, gate, weight=norm_weight)
|
||||
|
||||
if self.cp_context.cp_enabled:
|
||||
hidden_states = head_to_sequence_parallel(
|
||||
hidden_states,
|
||||
self.cp_context.cp_group,
|
||||
self.cp_context.cp_world_size,
|
||||
)
|
||||
return self.out_proj(hidden_states)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"GatedRMSNorm",
|
||||
"NemotronHMamba2",
|
||||
"head_to_sequence_parallel",
|
||||
"sequence_to_head_parallel",
|
||||
]
|
||||
@@ -1,576 +1,249 @@
|
||||
"""PrimeRL implementation of NemotronH (Nemotron-3-Super-120B-A12B).
|
||||
|
||||
Hybrid Mamba-Transformer-MoE architecture with three distinct layer types:
|
||||
- Mamba-2 layers (using NemotronHMamba2Mixer from HF transformers)
|
||||
- MoE layers with non-gated experts and latent projections
|
||||
- Attention layers (using shared FlashAttention/SDPA from prime-rl)
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from fla.modules.conv import causal_conv1d as fla_causal_conv1d
|
||||
from fla.ops.utils import prepare_sequence_ids
|
||||
from torch import Tensor, nn
|
||||
from transformers.generation import GenerationMixin
|
||||
from transformers.modeling_layers import GradientCheckpointingLayer
|
||||
from transformers.modeling_outputs import BaseModelOutputWithPast
|
||||
from transformers.models.nemotron_h.modular_nemotron_h import NemotronHMamba2Mixer
|
||||
from transformers.utils import auto_docstring, logging
|
||||
from transformers.modeling_outputs import BaseModelOutput
|
||||
|
||||
from prime_rl.trainer.models.base import CPSupport, PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
|
||||
from prime_rl.trainer.models.layers.cp_mamba import mamba_cp_forward
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput, VanillaOutputLinear
|
||||
from prime_rl.trainer.models.layers.mlp import FeedForward
|
||||
from prime_rl.trainer.models.layers.moe import (
|
||||
GroupedExperts,
|
||||
MoE,
|
||||
TokenChoiceTopKRouter,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.rms_norm import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.ulysses_attn import ULYSSES_PARAMS
|
||||
from prime_rl.trainer.models.layers.moe import GroupedExperts, MoE, TokenChoiceTopKRouter
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.nemotron_h.configuration_nemotron_h import NemotronHConfig
|
||||
from prime_rl.trainer.models.nemotron_h.converting_nemotron_h import conversion_chain
|
||||
from prime_rl.trainer.models.nemotron_h.converting_nemotron_h import (
|
||||
conversion_chain,
|
||||
is_hf_state_dict,
|
||||
is_prime_state_dict,
|
||||
)
|
||||
from prime_rl.trainer.models.nemotron_h.mamba import NemotronHMamba2
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
_patch_applied = False
|
||||
|
||||
|
||||
def _patch_mamba2_use_triton_ssd():
|
||||
"""Patch NemotronHMamba2Mixer to use mamba_ssm Triton SSD kernels.
|
||||
|
||||
The HF torch_forward computes softplus in model dtype (bf16), while vLLM's
|
||||
Triton kernels and mamba_ssm use fp32. This causes ~0.4 KL divergence.
|
||||
|
||||
This patch makes the mixer use mamba_chunk_scan_combined (Triton, fp32
|
||||
softplus) for the SSD computation, with fla's Triton causal_conv1d for
|
||||
convolution. Requires mamba_ssm installed.
|
||||
"""
|
||||
global _patch_applied
|
||||
if _patch_applied:
|
||||
return
|
||||
|
||||
if not torch.cuda.is_available():
|
||||
logger.warning_once("CUDA not available; NemotronH Mamba layers will use torch_forward (bf16 softplus)")
|
||||
return
|
||||
|
||||
try:
|
||||
from mamba_ssm.ops.triton.ssd_combined import (
|
||||
mamba_chunk_scan_combined as _mamba_chunk_scan_combined,
|
||||
)
|
||||
except ImportError:
|
||||
logger.warning_once("mamba_ssm not installed; NemotronH Mamba layers will use torch_forward (bf16 softplus)")
|
||||
return
|
||||
|
||||
if _mamba_chunk_scan_combined is None:
|
||||
logger.warning_once("mamba_ssm not available; NemotronH Mamba layers will use torch_forward (bf16 softplus)")
|
||||
return
|
||||
|
||||
def _varlen_mamba_forward(self, hidden_states, cu_seqlens):
|
||||
"""Varlen-aware mamba forward. `cu_seqlens` is required: shape [num_seq+1],
|
||||
e.g. [0, s1, s1+s2, ...]. Handles packed batches by:
|
||||
- passing cu_seqlens to causal_conv1d (conv state resets at boundaries)
|
||||
- passing seq_idx to mamba_chunk_scan_combined (SSM state resets at boundaries)
|
||||
"""
|
||||
batch_size, seq_len, _ = hidden_states.shape
|
||||
assert batch_size == 1, "varlen mamba expects batch_size=1 (packed)"
|
||||
groups_time_state_size = self.n_groups * self.ssm_state_size
|
||||
|
||||
# 1. Input projection (pointwise, no cross-seq mixing)
|
||||
projected_states = self.in_proj(hidden_states)
|
||||
A = -torch.exp(self.A_log.float())
|
||||
dt_limit_kwargs = {} if self.time_step_limit is None else {"dt_limit": self.time_step_limit}
|
||||
|
||||
gate, hidden_states_B_C, time_step = torch.split(
|
||||
projected_states,
|
||||
[self.intermediate_size, self.conv_dim, self.num_heads],
|
||||
dim=-1,
|
||||
)
|
||||
|
||||
# 2. Causal conv1d — must reset at sequence boundaries for packed batches,
|
||||
# otherwise the kernel-1 left pad leaks state across sequences.
|
||||
hidden_states_B_C, _ = fla_causal_conv1d(
|
||||
x=hidden_states_B_C,
|
||||
weight=self.conv1d.weight.squeeze(1),
|
||||
bias=self.conv1d.bias,
|
||||
activation=self.activation,
|
||||
cu_seqlens=cu_seqlens,
|
||||
)
|
||||
|
||||
hidden_states, B, C = torch.split(
|
||||
hidden_states_B_C,
|
||||
[self.intermediate_size, groups_time_state_size, groups_time_state_size],
|
||||
dim=-1,
|
||||
)
|
||||
|
||||
# 3. SSM with seq_idx so state resets at sequence boundaries
|
||||
seq_idx = prepare_sequence_ids(cu_seqlens).to(torch.int32).unsqueeze(0)
|
||||
|
||||
scan_output = _mamba_chunk_scan_combined(
|
||||
hidden_states.view(batch_size, seq_len, -1, self.head_dim),
|
||||
time_step,
|
||||
A,
|
||||
B.view(batch_size, seq_len, self.n_groups, -1),
|
||||
C.view(batch_size, seq_len, self.n_groups, -1),
|
||||
chunk_size=self.chunk_size,
|
||||
D=self.D,
|
||||
z=None,
|
||||
seq_idx=seq_idx,
|
||||
return_final_states=False,
|
||||
dt_bias=self.dt_bias,
|
||||
dt_softplus=True,
|
||||
**dt_limit_kwargs,
|
||||
)
|
||||
scan_output = scan_output.view(batch_size, seq_len, -1)
|
||||
scan_output = self.norm(scan_output, gate)
|
||||
return self.out_proj(scan_output)
|
||||
|
||||
def _patched_forward(self, hidden_states, cache_params=None, attention_mask=None, cu_seqlens=None):
|
||||
if cu_seqlens is not None and cache_params is None and "cuda" in self.in_proj.weight.device.type:
|
||||
return _varlen_mamba_forward(self, hidden_states, cu_seqlens)
|
||||
if "cuda" in self.in_proj.weight.device.type:
|
||||
# Disable fused training path (needs causal_conv1d CUDA extension)
|
||||
orig = self.use_mem_eff_path
|
||||
self.use_mem_eff_path = False
|
||||
result = self.cuda_kernels_forward(hidden_states, cache_params, attention_mask)
|
||||
self.use_mem_eff_path = orig
|
||||
return result
|
||||
return self.torch_forward(hidden_states, cache_params, attention_mask)
|
||||
|
||||
NemotronHMamba2Mixer.forward = _patched_forward
|
||||
_patch_applied = True
|
||||
logger.info("Patched NemotronHMamba2Mixer: Triton SSD kernels + varlen (cu_seqlens) support")
|
||||
|
||||
|
||||
def _ensure_zamba2_compat(config: NemotronHConfig):
|
||||
"""Add Zamba2-compatible attribute aliases to NemotronHConfig.
|
||||
|
||||
The HF modular NemotronHMamba2Mixer inherits from Zamba2MambaMixer, whose
|
||||
__init__ reads Zamba2-style attribute names before the NemotronH child
|
||||
overrides them. We set the missing aliases so the parent __init__ doesn't
|
||||
crash.
|
||||
|
||||
Critically, ``mamba_expand`` must give ``mamba_num_heads * mamba_head_dim``
|
||||
when multiplied by ``hidden_size``; the config's ``expand`` field does not
|
||||
satisfy this for all model sizes (e.g. Nemotron-3-Nano-30B).
|
||||
"""
|
||||
correct_intermediate = config.mamba_num_heads * config.mamba_head_dim
|
||||
correct_expand = correct_intermediate / config.hidden_size
|
||||
|
||||
aliases = {
|
||||
"mamba_d_state": config.ssm_state_size,
|
||||
"mamba_d_conv": config.conv_kernel,
|
||||
"mamba_ngroups": config.n_groups,
|
||||
"mamba_headdim": config.mamba_head_dim,
|
||||
"n_mamba_heads": config.mamba_num_heads,
|
||||
"add_bias_linear": getattr(config, "use_bias", False),
|
||||
"use_mem_eff_path": True,
|
||||
}
|
||||
for attr, value in aliases.items():
|
||||
if not hasattr(config, attr):
|
||||
setattr(config, attr, value)
|
||||
|
||||
config.mamba_expand = correct_expand
|
||||
|
||||
|
||||
class NemotronHMambaLayer(GradientCheckpointingLayer):
|
||||
"""Mamba-2 SSM layer: norm -> NemotronHMamba2Mixer -> residual.
|
||||
|
||||
With context parallelism, uses all-to-all head partitioning: transposes
|
||||
from sequence-parallel to head-parallel before the SSM, so each CP rank
|
||||
processes the full sequence on a subset of heads, then transposes back.
|
||||
"""
|
||||
|
||||
def __init__(self, config: NemotronHConfig, layer_idx: int):
|
||||
super().__init__()
|
||||
_patch_mamba2_use_triton_ssd()
|
||||
_ensure_zamba2_compat(config)
|
||||
self.norm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.layer_norm_epsilon))
|
||||
self.mamba = NemotronHMamba2Mixer(config, layer_idx=layer_idx)
|
||||
self.mlp = None # No MoE in this layer type
|
||||
|
||||
def set_context_parallel_attributes(self, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
|
||||
assert self.mamba.num_heads % cp_world_size == 0, (
|
||||
f"num_heads ({self.mamba.num_heads}) must be divisible by cp_world_size ({cp_world_size})"
|
||||
)
|
||||
assert self.mamba.n_groups % cp_world_size == 0, (
|
||||
f"n_groups ({self.mamba.n_groups}) must be divisible by cp_world_size ({cp_world_size})"
|
||||
)
|
||||
self._cp_group = cp_group
|
||||
self._cp_rank = cp_rank
|
||||
self._cp_world_size = cp_world_size
|
||||
|
||||
@property
|
||||
def cp_enabled(self) -> bool:
|
||||
return hasattr(self, "_cp_group")
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
routed_experts: torch.Tensor | None = None,
|
||||
cu_seqlens_are_pre_shard: bool = False,
|
||||
) -> torch.Tensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.norm(hidden_states)
|
||||
|
||||
if self.cp_enabled:
|
||||
global_cu_seqlens = (
|
||||
cu_seqlens if cu_seqlens is not None and cu_seqlens_are_pre_shard else ULYSSES_PARAMS["cu_seqlens"]
|
||||
)
|
||||
hidden_states = mamba_cp_forward(
|
||||
self.mamba,
|
||||
hidden_states,
|
||||
self._cp_group,
|
||||
self._cp_rank,
|
||||
self._cp_world_size,
|
||||
global_cu_seqlens,
|
||||
)
|
||||
else:
|
||||
hidden_states = self.mamba(hidden_states, cu_seqlens=cu_seqlens)
|
||||
|
||||
return residual + hidden_states
|
||||
|
||||
|
||||
class NemotronHMoE(MoE):
|
||||
def __init__(self, *, hidden_size: int, latent_size: int, **kwargs):
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
hidden_size: int,
|
||||
latent_size: int,
|
||||
projection_bias: bool,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
super().__init__(**kwargs)
|
||||
self.fc1_latent_proj = nn.Linear(hidden_size, latent_size, bias=False)
|
||||
self.fc2_latent_proj = nn.Linear(latent_size, hidden_size, bias=False)
|
||||
self.fc1_latent_proj = nn.Linear(hidden_size, latent_size, bias=projection_bias)
|
||||
self.fc2_latent_proj = nn.Linear(latent_size, hidden_size, bias=projection_bias)
|
||||
|
||||
def prepare_expert_input(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self.fc1_latent_proj(x)
|
||||
def prepare_expert_input(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
return self.fc1_latent_proj(hidden_states)
|
||||
|
||||
def prepare_expert_output(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self.fc2_latent_proj(x)
|
||||
def prepare_expert_output(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
return self.fc2_latent_proj(hidden_states)
|
||||
|
||||
|
||||
class NemotronHMoELayer(GradientCheckpointingLayer):
|
||||
"""MoE layer with latent routed experts."""
|
||||
|
||||
def __init__(self, config: NemotronHConfig):
|
||||
class NemotronHDecoderLayer(nn.Module):
|
||||
def __init__(self, config: NemotronHConfig, layer_idx: int) -> None:
|
||||
super().__init__()
|
||||
self.layer_type = config.layer_types[layer_idx]
|
||||
self.norm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.layer_norm_epsilon))
|
||||
effective_latent_dim = config.moe_latent_size if config.moe_latent_size is not None else config.hidden_size
|
||||
router = TokenChoiceTopKRouter(
|
||||
dim=config.hidden_size,
|
||||
num_experts=config.n_routed_experts,
|
||||
top_k=config.num_experts_per_tok,
|
||||
score_func="sigmoid",
|
||||
route_norm=config.norm_topk_prob,
|
||||
route_scale=config.routed_scaling_factor,
|
||||
selection_bias=True,
|
||||
topk_sorted=False,
|
||||
)
|
||||
router.fp32_gate = True
|
||||
experts = GroupedExperts(
|
||||
dim=effective_latent_dim,
|
||||
hidden_dim=config.moe_intermediate_size,
|
||||
num_experts=config.n_routed_experts,
|
||||
expert_type="non_gated",
|
||||
activation=config.mlp_hidden_act,
|
||||
)
|
||||
shared_expert = FeedForward(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.moe_shared_expert_intermediate_size,
|
||||
expert_type="non_gated",
|
||||
activation=config.mlp_hidden_act,
|
||||
)
|
||||
moe_kwargs = dict(
|
||||
router=router,
|
||||
experts=experts,
|
||||
shared_expert=shared_expert,
|
||||
score_before_experts=False,
|
||||
load_balance_coeff=config.load_balance_coeff,
|
||||
)
|
||||
if config.moe_latent_size is None:
|
||||
self.mlp = MoE(**moe_kwargs)
|
||||
else:
|
||||
self.mlp = NemotronHMoE(
|
||||
hidden_size=config.hidden_size,
|
||||
latent_size=config.moe_latent_size,
|
||||
**moe_kwargs,
|
||||
|
||||
if self.layer_type == "mamba":
|
||||
self.mamba = NemotronHMamba2(config)
|
||||
elif self.layer_type == "attention":
|
||||
self.self_attn = ATTN_IMPL2CLASS[config._attn_implementation](
|
||||
AttentionConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
head_dim=config.head_dim,
|
||||
num_attention_heads=config.num_attention_heads,
|
||||
num_key_value_heads=config.num_key_value_heads,
|
||||
is_causal=True,
|
||||
attention_bias=config.attention_bias,
|
||||
output_bias=config.attention_bias,
|
||||
use_qk_norm=False,
|
||||
rms_norm_eps=config.layer_norm_epsilon,
|
||||
)
|
||||
)
|
||||
elif self.layer_type == "moe":
|
||||
router = TokenChoiceTopKRouter(
|
||||
dim=config.hidden_size,
|
||||
num_experts=config.n_routed_experts,
|
||||
top_k=config.num_experts_per_tok,
|
||||
score_func="sigmoid",
|
||||
route_norm=config.norm_topk_prob,
|
||||
route_scale=config.routed_scaling_factor,
|
||||
selection_bias=True,
|
||||
topk_sorted=False,
|
||||
)
|
||||
expert_size = config.moe_latent_size or config.hidden_size
|
||||
experts = GroupedExperts(
|
||||
dim=expert_size,
|
||||
hidden_dim=config.moe_intermediate_size,
|
||||
num_experts=config.n_routed_experts,
|
||||
expert_type="non_gated",
|
||||
activation=config.mlp_hidden_act,
|
||||
bias=config.mlp_bias,
|
||||
)
|
||||
experts.init_weights(config.initializer_range)
|
||||
shared_expert = FeedForward(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.moe_shared_expert_intermediate_size,
|
||||
expert_type="non_gated",
|
||||
activation=config.mlp_hidden_act,
|
||||
bias=config.mlp_bias,
|
||||
)
|
||||
moe_kwargs = {
|
||||
"router": router,
|
||||
"experts": experts,
|
||||
"shared_expert": shared_expert,
|
||||
"score_before_experts": False,
|
||||
"load_balance_coeff": config.load_balance_coeff,
|
||||
}
|
||||
if config.moe_latent_size is None:
|
||||
self.mlp = MoE(**moe_kwargs)
|
||||
else:
|
||||
self.mlp = NemotronHMoE(
|
||||
hidden_size=config.hidden_size,
|
||||
latent_size=config.moe_latent_size,
|
||||
projection_bias=config.mlp_bias,
|
||||
**moe_kwargs,
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
cu_seqlens: torch.Tensor,
|
||||
max_seqlen: int,
|
||||
routed_experts: torch.Tensor | None = None,
|
||||
cu_seqlens_are_pre_shard: bool = False,
|
||||
) -> torch.Tensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.norm(hidden_states)
|
||||
hidden_states = self.mlp(hidden_states, routed_experts=routed_experts)
|
||||
|
||||
if self.layer_type == "mamba":
|
||||
hidden_states = self.mamba(hidden_states, cu_seqlens)
|
||||
elif self.layer_type == "attention":
|
||||
hidden_states, _ = self.self_attn(
|
||||
hidden_states=hidden_states,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
)
|
||||
else:
|
||||
hidden_states = self.mlp(hidden_states, routed_experts=routed_experts)
|
||||
return residual + hidden_states
|
||||
|
||||
|
||||
class NemotronHAttentionLayer(GradientCheckpointingLayer):
|
||||
"""Attention layer: norm -> FlashAttention/SDPA -> residual."""
|
||||
|
||||
def __init__(self, config: NemotronHConfig):
|
||||
super().__init__()
|
||||
self.norm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.layer_norm_epsilon))
|
||||
attn_config = AttentionConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
head_dim=config.head_dim,
|
||||
num_attention_heads=config.num_attention_heads,
|
||||
num_key_value_heads=config.num_key_value_heads,
|
||||
is_causal=True,
|
||||
attention_bias=config.attention_bias,
|
||||
use_qk_norm=False,
|
||||
rms_norm_eps=config.layer_norm_epsilon,
|
||||
)
|
||||
self.self_attn = ATTN_IMPL2CLASS[config._attn_implementation](attn_config)
|
||||
self.mlp = None # No MoE in this layer type
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
routed_experts: torch.Tensor | None = None,
|
||||
cu_seqlens_are_pre_shard: bool = False,
|
||||
) -> torch.Tensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.norm(hidden_states)
|
||||
hidden_states, _ = self.self_attn(
|
||||
hidden_states=hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
)
|
||||
return residual + hidden_states
|
||||
|
||||
|
||||
BLOCK_TYPE_MAP = {
|
||||
"mamba": NemotronHMambaLayer,
|
||||
"moe": NemotronHMoELayer,
|
||||
"attention": NemotronHAttentionLayer,
|
||||
}
|
||||
|
||||
|
||||
def _build_layer(config: NemotronHConfig, layer_idx: int):
|
||||
layer_type = config.layers_block_type[layer_idx]
|
||||
cls = BLOCK_TYPE_MAP[layer_type]
|
||||
if layer_type == "mamba":
|
||||
return cls(config, layer_idx=layer_idx)
|
||||
return cls(config)
|
||||
|
||||
|
||||
@auto_docstring
|
||||
class NemotronHPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
config: NemotronHConfig
|
||||
base_model_prefix = "model"
|
||||
supports_gradient_checkpointing = True
|
||||
_no_split_modules = ["NemotronHMambaLayer", "NemotronHMoELayer", "NemotronHAttentionLayer"]
|
||||
_supports_flash_attn = True
|
||||
_supports_sdpa = False
|
||||
_can_compile_fullgraph = False
|
||||
|
||||
@classmethod
|
||||
def cp_support(cls, config) -> CPSupport:
|
||||
return CPSupport(
|
||||
frozenset({"ulysses"}),
|
||||
"ring CP is a softmax-attention algorithm and cannot run this model's Mamba layers, "
|
||||
"whereas ulysses' all-to-all on Q/K/V leaves the SSM kernel unchanged",
|
||||
"Mamba layers require Ulysses to reconstruct full sequences while sharding Mamba heads",
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
|
||||
return name.endswith(("mamba.A_log", "mamba.D", "mlp.router.selection_bias"))
|
||||
|
||||
def _init_weights(self, module):
|
||||
std = self.config.initializer_range
|
||||
if isinstance(module, nn.Linear):
|
||||
module.weight.data.normal_(mean=0.0, std=std)
|
||||
if module.bias is not None:
|
||||
module.bias.data.zero_()
|
||||
elif isinstance(module, nn.Embedding):
|
||||
module.weight.data.normal_(mean=0.0, std=std)
|
||||
if module.padding_idx is not None:
|
||||
module.weight.data[module.padding_idx].zero_()
|
||||
elif isinstance(module, (GroupedExperts, TokenChoiceTopKRouter)):
|
||||
module.init_weights(std)
|
||||
|
||||
@classmethod
|
||||
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return any("mixer." in name for name in state_dict) or any("backbone." in name for name in state_dict)
|
||||
return is_hf_state_dict(state_dict)
|
||||
|
||||
@classmethod
|
||||
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return any(
|
||||
"mamba." in name
|
||||
or "mlp.experts.up_proj" in name
|
||||
or "self_attn." in name
|
||||
or "model.embed_tokens." in name
|
||||
or "model.norm." in name
|
||||
for name in state_dict
|
||||
)
|
||||
return is_prime_state_dict(state_dict)
|
||||
|
||||
@classmethod
|
||||
def conversion_chain(cls, config):
|
||||
def conversion_chain(cls, config: NemotronHConfig):
|
||||
return conversion_chain(config)
|
||||
|
||||
@classmethod
|
||||
def convert_adapter_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
# HF NemotronH unifies attention/mlp under a single `mixer` attribute per layer.
|
||||
import re
|
||||
|
||||
rename = [
|
||||
(re.compile(r"(\.layers\.\d+)\.mlp\."), r"\1.mixer."),
|
||||
(re.compile(r"(\.layers\.\d+)\.self_attn\."), r"\1.mixer."),
|
||||
]
|
||||
for old_key in list(state_dict.keys()):
|
||||
new_key = old_key
|
||||
for pattern, repl in rename:
|
||||
new_key = pattern.sub(repl, new_key)
|
||||
if new_key != old_key:
|
||||
state_dict[new_key] = state_dict.pop(old_key)
|
||||
for name in list(state_dict):
|
||||
hf_name = re.sub(r"(\.layers\.\d+)\.(?:self_attn|mlp|mamba)\.", r"\1.mixer.", name)
|
||||
if hf_name != name:
|
||||
state_dict[hf_name] = state_dict.pop(name)
|
||||
return state_dict
|
||||
|
||||
|
||||
class NemotronHModel(NemotronHPreTrainedModel):
|
||||
def __init__(self, config: NemotronHConfig):
|
||||
def __init__(self, config: NemotronHConfig) -> None:
|
||||
super().__init__(config)
|
||||
self.padding_idx = config.pad_token_id
|
||||
self.vocab_size = config.vocab_size
|
||||
|
||||
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
||||
self.layers = nn.ModuleList([_build_layer(config, i) for i in range(config.num_hidden_layers)])
|
||||
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, config.pad_token_id)
|
||||
self.layers = nn.ModuleList(
|
||||
NemotronHDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)
|
||||
)
|
||||
self.norm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.layer_norm_epsilon))
|
||||
|
||||
# NemotronH does not use RoPE - position information comes from Mamba layers
|
||||
self.rotary_emb = None
|
||||
|
||||
self.gradient_checkpointing = False
|
||||
self.post_init()
|
||||
|
||||
def set_context_parallel_attributes(self, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
|
||||
for layer in self.layers.modules():
|
||||
if isinstance(layer, NemotronHMambaLayer):
|
||||
layer.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
|
||||
|
||||
@auto_docstring
|
||||
def forward(
|
||||
self,
|
||||
input_ids: Optional[torch.LongTensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
inputs_embeds: Optional[torch.FloatTensor] = None,
|
||||
routed_experts: Optional[torch.LongTensor] = None,
|
||||
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,
|
||||
) -> BaseModelOutputWithPast:
|
||||
"""
|
||||
routed_experts (`torch.LongTensor` of shape `(batch_size, sequence_length, num_hidden_layers, num_experts_per_tok)`, *optional*):
|
||||
Routed experts for each token, indexed by global layer index. Only used for router replay; slots
|
||||
for non-MoE (Mamba/attention) layers are ignored.
|
||||
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
|
||||
Per-document lengths of the packed row (PrimeRL packed-batch contract).
|
||||
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
|
||||
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
|
||||
"""
|
||||
if (input_ids is None) ^ (inputs_embeds is not None):
|
||||
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
||||
|
||||
if inputs_embeds is None:
|
||||
inputs_embeds = self.embed_tokens(input_ids)
|
||||
) -> BaseModelOutput:
|
||||
hidden_states = self.embed_tokens(input_ids)
|
||||
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(
|
||||
seq_lens.to(device=inputs_embeds.device),
|
||||
total_tokens=None if seq_lens_are_pre_shard else inputs_embeds.shape[1],
|
||||
seq_lens.to(device=hidden_states.device),
|
||||
total_tokens=None if seq_lens_are_pre_shard else hidden_states.shape[1],
|
||||
)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
|
||||
hidden_states = inputs_embeds
|
||||
position_embeddings = self.rotary_emb(hidden_states, position_ids) if self.rotary_emb is not None else None
|
||||
|
||||
for layer_idx, decoder_layer in enumerate(self.layers):
|
||||
# routed_experts is indexed by global layer index; non-MoE layers ignore it.
|
||||
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
|
||||
layer_routed_experts = routed_experts[:, :, layer_idx] if routed_experts is not None else None
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
routed_experts=routed_experts_layer,
|
||||
cu_seqlens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
cu_seqlens,
|
||||
max_seqlen,
|
||||
routed_experts=layer_routed_experts,
|
||||
)
|
||||
|
||||
hidden_states = self.norm(hidden_states)
|
||||
return BaseModelOutputWithPast(last_hidden_state=hidden_states)
|
||||
return BaseModelOutput(last_hidden_state=self.norm(hidden_states))
|
||||
|
||||
|
||||
@auto_docstring
|
||||
class NemotronHForCausalLM(NemotronHPreTrainedModel, GenerationMixin):
|
||||
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
||||
|
||||
def __init__(self, config: NemotronHConfig):
|
||||
class NemotronHForCausalLM(NemotronHPreTrainedModel):
|
||||
def __init__(self, config: NemotronHConfig) -> None:
|
||||
super().__init__(config)
|
||||
self.model = NemotronHModel(config)
|
||||
self.vocab_size = config.vocab_size
|
||||
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
||||
self.post_init()
|
||||
|
||||
def get_decoder(self):
|
||||
return self.model
|
||||
|
||||
def set_context_parallel_attributes(self, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
|
||||
self.model.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
|
||||
self.lm_head = VanillaOutputLinear(config.hidden_size, config.vocab_size)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: Optional[torch.LongTensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
inputs_embeds: Optional[torch.FloatTensor] = None,
|
||||
labels: Optional[torch.LongTensor] = None,
|
||||
logits_to_keep: int = 0,
|
||||
temperature: Optional[torch.Tensor] = None,
|
||||
routed_experts: Optional[torch.LongTensor] = None,
|
||||
input_ids: torch.LongTensor,
|
||||
position_ids: torch.LongTensor | None = None,
|
||||
labels: torch.LongTensor | None = None,
|
||||
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:
|
||||
if position_ids is None:
|
||||
if inputs_embeds is not None:
|
||||
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
||||
else:
|
||||
position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).unsqueeze(0)
|
||||
|
||||
outputs = self.model(
|
||||
input_ids=input_ids,
|
||||
position_ids=position_ids,
|
||||
inputs_embeds=inputs_embeds,
|
||||
routed_experts=routed_experts,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
)
|
||||
|
||||
hidden_states = outputs.last_hidden_state
|
||||
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
||||
return self.lm_head(
|
||||
hidden_states[:, slice_indices, :],
|
||||
labels[:, slice_indices] if labels is not None else None,
|
||||
outputs.last_hidden_state,
|
||||
labels,
|
||||
temperature=temperature,
|
||||
sampling_mask=sampling_mask,
|
||||
)
|
||||
|
||||
def init_buffers_post_meta(self):
|
||||
pass
|
||||
def init_buffers_post_meta(self) -> None:
|
||||
for module in self.modules():
|
||||
if isinstance(module, MoE):
|
||||
module.tokens_per_expert.zero_()
|
||||
module.routing_confidence_sum.zero_()
|
||||
|
||||
|
||||
__all__ = [
|
||||
"NemotronHDecoderLayer",
|
||||
"NemotronHForCausalLM",
|
||||
"NemotronHMoE",
|
||||
"NemotronHModel",
|
||||
"NemotronHPreTrainedModel",
|
||||
]
|
||||
|
||||
@@ -1,3 +1,19 @@
|
||||
from .configuration_qwen3_5 import (
|
||||
Qwen3_5Config,
|
||||
Qwen3_5MoeConfig,
|
||||
Qwen3_5MoeTextConfig,
|
||||
Qwen3_5TextConfig,
|
||||
Qwen3_5VisionConfig,
|
||||
)
|
||||
from .modeling_qwen3_5 import Qwen3_5ForCausalLM, Qwen3_5Model, Qwen3_5PreTrainedModel
|
||||
|
||||
__all__ = ["Qwen3_5ForCausalLM", "Qwen3_5Model", "Qwen3_5PreTrainedModel"]
|
||||
__all__ = [
|
||||
"Qwen3_5Config",
|
||||
"Qwen3_5ForCausalLM",
|
||||
"Qwen3_5Model",
|
||||
"Qwen3_5MoeConfig",
|
||||
"Qwen3_5MoeTextConfig",
|
||||
"Qwen3_5PreTrainedModel",
|
||||
"Qwen3_5TextConfig",
|
||||
"Qwen3_5VisionConfig",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.trainer.models.layers.attn import AttentionConfig, FlashAttention
|
||||
from prime_rl.trainer.models.layers.rotary_emb import apply_rotary_pos_emb
|
||||
from prime_rl.trainer.models.qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfig
|
||||
from prime_rl.trainer.models.qwen3_5.norm import Qwen3_5RMSNorm
|
||||
|
||||
|
||||
class Qwen3_5Attention(FlashAttention):
|
||||
def __init__(self, config: Qwen3_5TextConfig, attention_implementation: str) -> None:
|
||||
flash_attn_version = {
|
||||
"flash_attention_2": 2,
|
||||
"flash_attention_3": 3,
|
||||
"flash_attention_4": 4,
|
||||
}[attention_implementation]
|
||||
super().__init__(
|
||||
AttentionConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
head_dim=config.head_dim,
|
||||
num_attention_heads=config.num_attention_heads,
|
||||
num_key_value_heads=config.num_key_value_heads,
|
||||
is_causal=True,
|
||||
attention_bias=config.attention_bias,
|
||||
output_bias=config.attention_bias,
|
||||
use_qk_norm=False,
|
||||
rms_norm_eps=config.rms_norm_eps,
|
||||
),
|
||||
flash_attn_version=flash_attn_version,
|
||||
)
|
||||
self.num_heads = config.num_attention_heads
|
||||
self.num_key_value_heads = config.num_key_value_heads
|
||||
self.attn_output_gate = config.attn_output_gate
|
||||
q_output_size = self.num_heads * self.head_dim * (2 if self.attn_output_gate else 1)
|
||||
self.qkv_sizes = (q_output_size, self.qkv_sizes[1], self.qkv_sizes[2])
|
||||
self.q_proj = nn.Linear(config.hidden_size, q_output_size, bias=config.attention_bias)
|
||||
self.q_norm = Qwen3_5RMSNorm(self.head_dim, config.rms_norm_eps)
|
||||
self.k_norm = Qwen3_5RMSNorm(self.head_dim, config.rms_norm_eps)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
cu_seqlens: torch.LongTensor,
|
||||
max_seqlen: int,
|
||||
) -> tuple[torch.Tensor, None]:
|
||||
batch_size, sequence_length, _ = hidden_states.shape
|
||||
|
||||
query_states, key_states, value_states = self.project_qkv(hidden_states)
|
||||
if self.attn_output_gate:
|
||||
query_states, output_gate = query_states.view(
|
||||
batch_size, sequence_length, self.num_heads, self.head_dim * 2
|
||||
).chunk(2, dim=-1)
|
||||
output_gate = output_gate.reshape(batch_size, sequence_length, -1)
|
||||
else:
|
||||
query_states = query_states.view(batch_size, sequence_length, self.num_heads, self.head_dim)
|
||||
output_gate = None
|
||||
|
||||
key_states = key_states.view(batch_size, sequence_length, self.num_key_value_heads, self.head_dim)
|
||||
value_states = value_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)
|
||||
|
||||
cos, sin = position_embeddings
|
||||
query_states, key_states = apply_rotary_pos_emb(
|
||||
query_states.transpose(1, 2),
|
||||
key_states.transpose(1, 2),
|
||||
cos,
|
||||
sin,
|
||||
)
|
||||
query_states = query_states.transpose(1, 2)
|
||||
key_states = key_states.transpose(1, 2)
|
||||
|
||||
attention_output = self._compute_attention(
|
||||
query_states[0],
|
||||
key_states[0],
|
||||
value_states[0],
|
||||
cu_seqlens,
|
||||
max_seqlen,
|
||||
).reshape(batch_size, sequence_length, -1)
|
||||
if output_gate is not None:
|
||||
attention_output = attention_output * output_gate.sigmoid()
|
||||
return self.o_proj(attention_output), None
|
||||
|
||||
|
||||
__all__ = ["Qwen3_5Attention"]
|
||||
@@ -0,0 +1,207 @@
|
||||
from transformers.configuration_utils import PretrainedConfig
|
||||
|
||||
|
||||
class Qwen3_5TextConfig(PretrainedConfig):
|
||||
model_type = "qwen3_5_text"
|
||||
base_config_key = "text_config"
|
||||
ignore_keys_at_rope_validation = {"mrope_section", "mrope_interleaved"}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vocab_size: int = 248320,
|
||||
hidden_size: int = 4096,
|
||||
intermediate_size: int = 12288,
|
||||
num_hidden_layers: int = 32,
|
||||
num_attention_heads: int = 16,
|
||||
num_key_value_heads: int = 4,
|
||||
head_dim: int = 256,
|
||||
hidden_act: str = "silu",
|
||||
max_position_embeddings: int = 32768,
|
||||
initializer_range: float = 0.02,
|
||||
rms_norm_eps: float = 1e-6,
|
||||
rope_theta: float = 10_000.0,
|
||||
rope_scaling: dict | None = None,
|
||||
rope_parameters: dict | None = None,
|
||||
attention_bias: bool = False,
|
||||
attention_dropout: float = 0.0,
|
||||
attn_output_gate: bool = True,
|
||||
output_gate_type: str = "silu",
|
||||
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 = 32,
|
||||
layer_types: list[str] | None = None,
|
||||
full_attention_interval: int = 4,
|
||||
mamba_ssm_dtype: str = "float32",
|
||||
use_cache: bool = True,
|
||||
pad_token_id: int | None = None,
|
||||
bos_token_id: int | None = None,
|
||||
eos_token_id: int | list[int] | None = None,
|
||||
tie_word_embeddings: bool = False,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
self.vocab_size = vocab_size
|
||||
self.hidden_size = hidden_size
|
||||
self.intermediate_size = intermediate_size
|
||||
self.num_hidden_layers = num_hidden_layers
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.num_key_value_heads = num_key_value_heads
|
||||
self.head_dim = head_dim
|
||||
self.hidden_act = hidden_act
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
self.initializer_range = initializer_range
|
||||
self.rms_norm_eps = rms_norm_eps
|
||||
self.attention_bias = attention_bias
|
||||
self.attention_dropout = attention_dropout
|
||||
self.attn_output_gate = attn_output_gate
|
||||
self.output_gate_type = output_gate_type
|
||||
|
||||
if rope_parameters is None:
|
||||
rope_parameters = rope_scaling
|
||||
if rope_parameters is None:
|
||||
rope_parameters = {
|
||||
"rope_type": "default",
|
||||
"rope_theta": rope_theta,
|
||||
"partial_rotary_factor": kwargs.pop("partial_rotary_factor", 0.25),
|
||||
"mrope_interleaved": True,
|
||||
}
|
||||
self.rope_parameters = dict(rope_parameters)
|
||||
self.rope_parameters.setdefault("rope_type", "default")
|
||||
self.rope_parameters.setdefault("rope_theta", rope_theta)
|
||||
self.rope_parameters.setdefault("partial_rotary_factor", kwargs.pop("partial_rotary_factor", 0.25))
|
||||
self.rope_parameters.setdefault("mrope_interleaved", True)
|
||||
|
||||
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.layer_types = layer_types or [
|
||||
"linear_attention" if (layer_idx + 1) % full_attention_interval else "full_attention"
|
||||
for layer_idx in range(num_hidden_layers)
|
||||
]
|
||||
self.mamba_ssm_dtype = mamba_ssm_dtype
|
||||
self.use_cache = use_cache
|
||||
|
||||
kwargs.pop("mtp_num_hidden_layers", None)
|
||||
kwargs.pop("mtp_use_dedicated_embeddings", 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_5MoeTextConfig(Qwen3_5TextConfig):
|
||||
model_type = "qwen3_5_moe_text"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
moe_intermediate_size: int = 512,
|
||||
shared_expert_intermediate_size: int = 512,
|
||||
num_experts_per_tok: int = 8,
|
||||
num_experts: int = 256,
|
||||
output_router_logits: bool = False,
|
||||
router_aux_loss_coef: float = 0.001,
|
||||
load_balance_coeff: float | None = None,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
self.moe_intermediate_size = moe_intermediate_size
|
||||
self.shared_expert_intermediate_size = shared_expert_intermediate_size
|
||||
self.num_experts_per_tok = num_experts_per_tok
|
||||
self.num_experts = num_experts
|
||||
self.output_router_logits = output_router_logits
|
||||
self.router_aux_loss_coef = router_aux_loss_coef
|
||||
self.load_balance_coeff = load_balance_coeff
|
||||
kwargs.pop("mlp_only_layers", None)
|
||||
super().__init__(**kwargs)
|
||||
|
||||
|
||||
class Qwen3_5VisionConfig(PretrainedConfig):
|
||||
model_type = "qwen3_5_vision"
|
||||
base_config_key = "vision_config"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
depth: int = 27,
|
||||
hidden_size: int = 1152,
|
||||
hidden_act: str = "gelu_pytorch_tanh",
|
||||
intermediate_size: int = 4304,
|
||||
num_heads: int = 16,
|
||||
in_channels: int = 3,
|
||||
patch_size: int = 16,
|
||||
spatial_merge_size: int = 2,
|
||||
temporal_patch_size: int = 2,
|
||||
out_hidden_size: int = 3584,
|
||||
num_position_embeddings: int = 2304,
|
||||
initializer_range: float = 0.02,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
self.depth = depth
|
||||
self.hidden_size = hidden_size
|
||||
self.hidden_act = hidden_act
|
||||
self.intermediate_size = intermediate_size
|
||||
self.num_heads = num_heads
|
||||
self.in_channels = in_channels
|
||||
self.patch_size = patch_size
|
||||
self.spatial_merge_size = spatial_merge_size
|
||||
self.temporal_patch_size = temporal_patch_size
|
||||
self.out_hidden_size = out_hidden_size
|
||||
self.num_position_embeddings = num_position_embeddings
|
||||
self.initializer_range = initializer_range
|
||||
kwargs.pop("deepstack_visual_indexes", None)
|
||||
super().__init__(**kwargs)
|
||||
|
||||
|
||||
class Qwen3_5Config(PretrainedConfig):
|
||||
model_type = "qwen3_5"
|
||||
sub_configs = {"vision_config": Qwen3_5VisionConfig, "text_config": Qwen3_5TextConfig}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
text_config: dict | PretrainedConfig | None = None,
|
||||
vision_config: dict | PretrainedConfig | None = None,
|
||||
image_token_id: int = 248056,
|
||||
video_token_id: int = 248057,
|
||||
vision_start_token_id: int = 248053,
|
||||
vision_end_token_id: int = 248054,
|
||||
tie_word_embeddings: bool = False,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
self.text_config = (
|
||||
self.sub_configs["text_config"](**text_config) if isinstance(text_config, dict) else text_config
|
||||
) or self.sub_configs["text_config"]()
|
||||
self.vision_config = (
|
||||
self.sub_configs["vision_config"](**vision_config) if isinstance(vision_config, dict) else vision_config
|
||||
) or self.sub_configs["vision_config"]()
|
||||
self.image_token_id = image_token_id
|
||||
self.video_token_id = video_token_id
|
||||
self.vision_start_token_id = vision_start_token_id
|
||||
self.vision_end_token_id = vision_end_token_id
|
||||
kwargs.pop("language_model_only", None)
|
||||
super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
|
||||
|
||||
|
||||
class Qwen3_5MoeConfig(Qwen3_5Config):
|
||||
model_type = "qwen3_5_moe"
|
||||
sub_configs = {"vision_config": Qwen3_5VisionConfig, "text_config": Qwen3_5MoeTextConfig}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
text_config: dict | PretrainedConfig | None = None,
|
||||
vision_config: dict | PretrainedConfig | None = None,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
super().__init__(text_config=text_config, vision_config=vision_config, **kwargs)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"Qwen3_5Config",
|
||||
"Qwen3_5MoeConfig",
|
||||
"Qwen3_5MoeTextConfig",
|
||||
"Qwen3_5TextConfig",
|
||||
"Qwen3_5VisionConfig",
|
||||
]
|
||||
@@ -0,0 +1,48 @@
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.trainer.models.conversion_ops import ConvOp, Drop, Rename, SplitConcat
|
||||
from prime_rl.trainer.models.qwen3_5.configuration_qwen3_5 import Qwen3_5MoeTextConfig
|
||||
|
||||
|
||||
def is_hf_state_dict(state_dict: dict[str, Tensor]) -> bool:
|
||||
return any(name == "mtp.fc.weight" or name.endswith("mlp.experts.gate_up_proj") for name in state_dict)
|
||||
|
||||
|
||||
def is_prime_state_dict(state_dict: dict[str, Tensor]) -> bool:
|
||||
if any(name.endswith("mlp.experts.gate_proj") for name in state_dict):
|
||||
return True
|
||||
has_qwen_layers = any(name.endswith("linear_attn.A_log") for name in state_dict)
|
||||
has_fused_experts = any(name.endswith("mlp.experts.gate_up_proj") for name in state_dict)
|
||||
return has_qwen_layers and not has_fused_experts
|
||||
|
||||
|
||||
def conversion_chain(config) -> list[ConvOp]:
|
||||
operations: list[ConvOp] = [Drop("mtp.", is_prefix=True)]
|
||||
text_config = getattr(config, "text_config", config)
|
||||
if not isinstance(text_config, Qwen3_5MoeTextConfig):
|
||||
return operations
|
||||
|
||||
model_prefix = "model.language_model" if hasattr(config, "vision_config") else "model"
|
||||
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,
|
||||
),
|
||||
]
|
||||
)
|
||||
return operations
|
||||
|
||||
|
||||
__all__ = ["conversion_chain", "is_hf_state_dict", "is_prime_state_dict"]
|
||||
@@ -0,0 +1,112 @@
|
||||
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.trainer.models.qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfig
|
||||
from prime_rl.utils.cp import CPContext
|
||||
|
||||
# Dynamo lowers all-gather to concatenation, then fails to copy the result into
|
||||
# FLA's stacked output buffer. Keep CP convolution eager until this is fixed:
|
||||
# https://github.com/pytorch/pytorch/issues/155632
|
||||
causal_conv1d_with_context_parallelism = torch.compiler.disable(causal_conv1d)
|
||||
|
||||
|
||||
class Qwen3_5GatedDeltaNet(nn.Module):
|
||||
def __init__(self, config: Qwen3_5TextConfig) -> None:
|
||||
super().__init__()
|
||||
self.num_value_heads = config.linear_num_value_heads
|
||||
self.num_key_heads = config.linear_num_key_heads
|
||||
self.key_head_dim = config.linear_key_head_dim
|
||||
self.value_head_dim = config.linear_value_head_dim
|
||||
self.key_dim = self.key_head_dim * self.num_key_heads
|
||||
self.value_dim = self.value_head_dim * self.num_value_heads
|
||||
self.conv_kernel_size = config.linear_conv_kernel_dim
|
||||
self.activation = config.hidden_act
|
||||
|
||||
conv_dim = self.key_dim * 2 + self.value_dim
|
||||
self.conv1d = nn.Conv1d(
|
||||
conv_dim,
|
||||
conv_dim,
|
||||
kernel_size=self.conv_kernel_size,
|
||||
groups=conv_dim,
|
||||
padding=self.conv_kernel_size - 1,
|
||||
bias=False,
|
||||
)
|
||||
self.dt_bias = nn.Parameter(torch.ones(self.num_value_heads))
|
||||
self.A_log = nn.Parameter(torch.empty(self.num_value_heads).uniform_(0, 16).log_())
|
||||
self.norm = FusedRMSNormGated(
|
||||
self.value_head_dim,
|
||||
eps=config.rms_norm_eps,
|
||||
activation=config.output_gate_type,
|
||||
)
|
||||
self.out_proj = nn.Linear(self.value_dim, config.hidden_size, bias=False)
|
||||
self.in_proj_qkv = nn.Linear(config.hidden_size, conv_dim, bias=False)
|
||||
self.in_proj_z = nn.Linear(config.hidden_size, self.value_dim, bias=False)
|
||||
self.in_proj_b = nn.Linear(config.hidden_size, self.num_value_heads, bias=False)
|
||||
self.in_proj_a = nn.Linear(config.hidden_size, self.num_value_heads, bias=False)
|
||||
self.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 = causal_conv1d_with_context_parallelism if context is not None else causal_conv1d
|
||||
mixed_qkv, _ = convolution(
|
||||
x=mixed_qkv,
|
||||
weight=self.conv1d.weight.squeeze(1),
|
||||
bias=self.conv1d.bias,
|
||||
activation=self.activation,
|
||||
cu_seqlens=cu_seqlens,
|
||||
cp_context=context,
|
||||
)
|
||||
|
||||
query, key, value = torch.split(mixed_qkv, [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)
|
||||
|
||||
core_output, _ = chunk_gated_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,
|
||||
cp_context=context,
|
||||
)
|
||||
|
||||
core_output = self.norm(
|
||||
core_output.reshape(-1, self.value_head_dim),
|
||||
output_gate.reshape(-1, self.value_head_dim),
|
||||
).reshape(batch_size, sequence_length, self.value_dim)
|
||||
return self.out_proj(core_output)
|
||||
|
||||
|
||||
__all__ = ["Qwen3_5GatedDeltaNet"]
|
||||
@@ -1,141 +1,123 @@
|
||||
import functools
|
||||
from typing import Optional, Union
|
||||
|
||||
import torch
|
||||
from torch import Tensor, nn
|
||||
from transformers.cache_utils import Cache
|
||||
from transformers.configuration_utils import PretrainedConfig
|
||||
from transformers.generation import GenerationMixin
|
||||
from transformers.modeling_layers import GradientCheckpointingLayer
|
||||
from transformers.modeling_outputs import BaseModelOutputWithPast
|
||||
from transformers.models.qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfig
|
||||
from transformers.models.qwen3_5.modeling_qwen3_5 import (
|
||||
Qwen3_5PreTrainedModel as HFQwen3_5PreTrainedModel,
|
||||
)
|
||||
from transformers.models.qwen3_5.modeling_qwen3_5 import Qwen3_5VisionModel
|
||||
from transformers.processing_utils import Unpack
|
||||
from transformers.utils import TransformersKwargs
|
||||
from transformers.modeling_outputs import BaseModelOutput
|
||||
|
||||
from prime_rl.trainer.models.base import ALL_CP_STYLES, CPSupport, PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput, VanillaOutputLinear
|
||||
from prime_rl.trainer.models.layers.mlp import FeedForward
|
||||
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import (
|
||||
Qwen3_5MoeGatedAttentionConfig,
|
||||
Qwen3_5MoeGatedDeltaNet,
|
||||
Qwen3_5MoeGatedFlashAttention,
|
||||
Qwen3_5MoeRMSNorm,
|
||||
Qwen3_5MoeRotaryEmbedding,
|
||||
normalize_qwen3_5_attn_implementation,
|
||||
from prime_rl.trainer.models.layers.moe import GroupedExperts, MoE, TokenChoiceTopKRouter
|
||||
from prime_rl.trainer.models.qwen3_5.attention import Qwen3_5Attention
|
||||
from prime_rl.trainer.models.qwen3_5.configuration_qwen3_5 import (
|
||||
Qwen3_5MoeTextConfig,
|
||||
Qwen3_5TextConfig,
|
||||
)
|
||||
from prime_rl.trainer.models.qwen3_5_moe.mrope import build_qwen3_5_mrope_position_ids
|
||||
from prime_rl.utils.cp import setup_cp_attention_params, shard_for_cp, shard_position_ids_for_cp
|
||||
from prime_rl.trainer.models.qwen3_5.converting_qwen3_5 import (
|
||||
conversion_chain,
|
||||
is_hf_state_dict,
|
||||
is_prime_state_dict,
|
||||
)
|
||||
from prime_rl.trainer.models.qwen3_5.gated_delta_net import Qwen3_5GatedDeltaNet
|
||||
from prime_rl.trainer.models.qwen3_5.norm import Qwen3_5RMSNorm
|
||||
from prime_rl.trainer.models.qwen3_5.rotary_embedding import (
|
||||
Qwen3_5RotaryEmbedding,
|
||||
build_qwen3_5_mrope_position_ids,
|
||||
)
|
||||
from prime_rl.trainer.models.qwen3_5.vision import Qwen3_5VisionModel
|
||||
from prime_rl.utils.cp import CPContext, setup_cp_attention_params, shard_for_cp, shard_position_ids_for_cp
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
|
||||
|
||||
|
||||
class Qwen3_5GatedFlashAttention(Qwen3_5MoeGatedFlashAttention):
|
||||
pass
|
||||
|
||||
|
||||
QWEN35_ATTN_IMPL2CLASS = {
|
||||
"flash_attention_2": functools.partial(Qwen3_5GatedFlashAttention, flash_attn_version=2),
|
||||
"flash_attention_3": functools.partial(Qwen3_5GatedFlashAttention, flash_attn_version=3),
|
||||
"flash_attention_4": functools.partial(Qwen3_5GatedFlashAttention, flash_attn_version=4),
|
||||
}
|
||||
|
||||
|
||||
def _get_gated_attention(config: Qwen3_5TextConfig) -> nn.Module:
|
||||
attn_config = Qwen3_5MoeGatedAttentionConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
head_dim=config.head_dim,
|
||||
num_attention_heads=config.num_attention_heads,
|
||||
num_key_value_heads=config.num_key_value_heads,
|
||||
rms_norm_eps=config.rms_norm_eps,
|
||||
attention_bias=config.attention_bias,
|
||||
attention_dropout=config.attention_dropout,
|
||||
)
|
||||
|
||||
attn_impl = normalize_qwen3_5_attn_implementation(config._attn_implementation)
|
||||
config._attn_implementation = attn_impl
|
||||
|
||||
if attn_impl not in QWEN35_ATTN_IMPL2CLASS:
|
||||
supported = list(QWEN35_ATTN_IMPL2CLASS.keys())
|
||||
raise ValueError(
|
||||
f"Qwen3.5 attention does not support '{config._attn_implementation}'. "
|
||||
f"Supported implementations: {supported}."
|
||||
)
|
||||
|
||||
return QWEN35_ATTN_IMPL2CLASS[attn_impl](attn_config)
|
||||
|
||||
|
||||
def _create_rotary_emb(config: Qwen3_5TextConfig) -> Qwen3_5MoeRotaryEmbedding:
|
||||
return Qwen3_5MoeRotaryEmbedding(config)
|
||||
|
||||
|
||||
class Qwen3_5DecoderLayer(GradientCheckpointingLayer):
|
||||
def __init__(self, config: Qwen3_5TextConfig, layer_idx: int):
|
||||
super().__init__()
|
||||
self.hidden_size = config.hidden_size
|
||||
self.layer_type = config.layer_types[layer_idx]
|
||||
|
||||
if self.layer_type == "linear_attention":
|
||||
self.linear_attn = Qwen3_5MoeGatedDeltaNet(config)
|
||||
elif self.layer_type == "full_attention":
|
||||
self.self_attn = _get_gated_attention(config)
|
||||
else:
|
||||
raise ValueError(f"Unsupported Qwen3.5 layer type: {self.layer_type}")
|
||||
|
||||
self.mlp = FeedForward(
|
||||
class Qwen3_5SharedExpert(FeedForward):
|
||||
def __init__(self, config: Qwen3_5MoeTextConfig) -> None:
|
||||
super().__init__(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.intermediate_size,
|
||||
hidden_dim=config.shared_expert_intermediate_size,
|
||||
expert_type="gated",
|
||||
activation=config.hidden_act,
|
||||
)
|
||||
self.input_layernorm = Qwen3_5MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.post_attention_layernorm = Qwen3_5MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.output_gate = nn.Linear(config.hidden_size, 1, bias=False)
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor, routed_experts: torch.Tensor | None = None) -> torch.Tensor:
|
||||
output = super().forward(hidden_states, routed_experts)
|
||||
return output * self.output_gate(hidden_states).sigmoid()
|
||||
|
||||
|
||||
class Qwen3_5DecoderLayer(nn.Module):
|
||||
def __init__(self, config: Qwen3_5TextConfig, layer_index: int) -> None:
|
||||
super().__init__()
|
||||
self.layer_type = config.layer_types[layer_index]
|
||||
if self.layer_type == "linear_attention":
|
||||
self.linear_attn = Qwen3_5GatedDeltaNet(config)
|
||||
elif self.layer_type == "full_attention":
|
||||
self.self_attn = Qwen3_5Attention(config, config._attn_implementation)
|
||||
|
||||
if isinstance(config, Qwen3_5MoeTextConfig):
|
||||
router = TokenChoiceTopKRouter(
|
||||
dim=config.hidden_size,
|
||||
num_experts=config.num_experts,
|
||||
top_k=config.num_experts_per_tok,
|
||||
score_func="softmax",
|
||||
route_norm=True,
|
||||
route_scale=1.0,
|
||||
selection_bias=config.load_balance_coeff is not None,
|
||||
)
|
||||
experts = GroupedExperts(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.moe_intermediate_size,
|
||||
num_experts=config.num_experts,
|
||||
expert_type="gated",
|
||||
activation=config.hidden_act,
|
||||
)
|
||||
experts.init_weights(config.initializer_range)
|
||||
self.mlp = MoE(
|
||||
router=router,
|
||||
experts=experts,
|
||||
shared_expert=Qwen3_5SharedExpert(config),
|
||||
score_before_experts=False,
|
||||
load_balance_coeff=config.load_balance_coeff,
|
||||
)
|
||||
else:
|
||||
self.mlp = FeedForward(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.intermediate_size,
|
||||
expert_type="gated",
|
||||
activation=config.hidden_act,
|
||||
)
|
||||
|
||||
self.input_layernorm = Qwen3_5RMSNorm(config.hidden_size, config.rms_norm_eps)
|
||||
self.post_attention_layernorm = Qwen3_5RMSNorm(config.hidden_size, config.rms_norm_eps)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
cu_seqlens_are_pre_shard: bool = False,
|
||||
) -> torch.FloatTensor:
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
cu_seqlens: torch.LongTensor,
|
||||
max_seqlen: int,
|
||||
routed_experts: torch.LongTensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.input_layernorm(hidden_states)
|
||||
|
||||
if self.layer_type == "linear_attention":
|
||||
hidden_states = self.linear_attn(
|
||||
hidden_states, cu_seqlens=cu_seqlens, cu_seqlens_are_pre_shard=cu_seqlens_are_pre_shard
|
||||
hidden_states,
|
||||
cu_seqlens,
|
||||
)
|
||||
else:
|
||||
hidden_states, _ = self.self_attn(
|
||||
hidden_states=hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
hidden_states,
|
||||
position_embeddings,
|
||||
cu_seqlens,
|
||||
max_seqlen,
|
||||
)
|
||||
hidden_states = residual + hidden_states
|
||||
|
||||
residual = hidden_states
|
||||
hidden_states = self.post_attention_layernorm(hidden_states)
|
||||
hidden_states = self.mlp(hidden_states)
|
||||
return residual + hidden_states
|
||||
return residual + self.mlp(hidden_states, routed_experts=routed_experts)
|
||||
|
||||
|
||||
class Qwen3_5PreTrainedModel(PreTrainedModelPrimeRL, HFQwen3_5PreTrainedModel):
|
||||
class Qwen3_5PreTrainedModel(PreTrainedModelPrimeRL):
|
||||
config_class = Qwen3_5TextConfig
|
||||
base_model_prefix = "model"
|
||||
supports_gradient_checkpointing = True
|
||||
_no_split_modules = ["Qwen3_5DecoderLayer"]
|
||||
_skip_keys_device_placement = ["past_key_values"]
|
||||
_supports_flash_attn = True
|
||||
_supports_sdpa = False
|
||||
_supports_flex_attn = False
|
||||
_supports_attention_backend = True
|
||||
_can_compile_fullgraph = False
|
||||
_can_record_outputs = {
|
||||
"hidden_states": Qwen3_5DecoderLayer,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def cp_support(cls, config) -> CPSupport:
|
||||
@@ -144,9 +126,7 @@ class Qwen3_5PreTrainedModel(PreTrainedModelPrimeRL, HFQwen3_5PreTrainedModel):
|
||||
if "linear_attention" in (getattr(text_config, "layer_types", None) or ()):
|
||||
return CPSupport(
|
||||
frozenset({"ulysses"}),
|
||||
"ring CP is a softmax-attention algorithm and cannot run this model's DeltaNet "
|
||||
"layers, whereas ulysses' all-to-all on Q/K/V leaves the linear-attention kernel "
|
||||
"unchanged",
|
||||
"DeltaNet layers require Ulysses sequence sharding with FLA boundary-state exchange",
|
||||
)
|
||||
return CPSupport(ALL_CP_STYLES)
|
||||
|
||||
@@ -154,177 +134,128 @@ class Qwen3_5PreTrainedModel(PreTrainedModelPrimeRL, HFQwen3_5PreTrainedModel):
|
||||
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
|
||||
return name.endswith(("linear_attn.A_log", "linear_attn.norm.weight"))
|
||||
|
||||
def _check_and_adjust_attn_implementation(
|
||||
self, attn_implementation: str | None, is_init_check: bool = False, allow_all_kernels: bool = False
|
||||
) -> str:
|
||||
attn_impl = normalize_qwen3_5_attn_implementation(attn_implementation or "flash_attention_3")
|
||||
if attn_impl not in QWEN35_ATTN_IMPL2CLASS:
|
||||
supported = list(QWEN35_ATTN_IMPL2CLASS.keys())
|
||||
raise ValueError(
|
||||
f"Qwen3.5 attention does not support '{attn_implementation}'. Supported implementations: {supported}."
|
||||
)
|
||||
return attn_impl
|
||||
|
||||
@classmethod
|
||||
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return True
|
||||
return is_hf_state_dict(state_dict)
|
||||
|
||||
@classmethod
|
||||
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
# Dense models use identical key names in HF and PrimeRL format, so we
|
||||
# never claim to be in a separate PrimeRL format. This disables the
|
||||
# auto-conversion path in load_dcp_from_hf and lets DCP load directly.
|
||||
return False
|
||||
return is_prime_state_dict(state_dict)
|
||||
|
||||
@classmethod
|
||||
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_to_prime(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_hf(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_prime(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
return state_dict
|
||||
def conversion_chain(cls, config):
|
||||
return conversion_chain(config)
|
||||
|
||||
|
||||
class Qwen3_5Model(Qwen3_5PreTrainedModel):
|
||||
def __init__(self, config: Qwen3_5TextConfig):
|
||||
config._attn_implementation = normalize_qwen3_5_attn_implementation(config._attn_implementation)
|
||||
def __init__(self, config: Qwen3_5TextConfig) -> None:
|
||||
super().__init__(config)
|
||||
self.padding_idx = config.pad_token_id
|
||||
self.vocab_size = config.vocab_size
|
||||
|
||||
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
||||
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, config.pad_token_id)
|
||||
self.layers = nn.ModuleList(
|
||||
[Qwen3_5DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
||||
Qwen3_5DecoderLayer(config, layer_index) for layer_index in range(config.num_hidden_layers)
|
||||
)
|
||||
self.norm = Qwen3_5MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.rotary_emb = _create_rotary_emb(config)
|
||||
self.gradient_checkpointing = False
|
||||
self.norm = Qwen3_5RMSNorm(config.hidden_size, config.rms_norm_eps)
|
||||
self.rotary_emb = Qwen3_5RotaryEmbedding(config)
|
||||
|
||||
self.post_init()
|
||||
|
||||
def get_input_embeddings(self):
|
||||
def get_input_embeddings(self) -> nn.Embedding:
|
||||
return self.embed_tokens
|
||||
|
||||
def set_input_embeddings(self, value):
|
||||
self.embed_tokens = value
|
||||
|
||||
def set_context_parallel_attributes(self, cp_group, cp_rank: int, cp_world_size: int) -> None:
|
||||
self._cp_group = cp_group
|
||||
self._cp_rank = cp_rank
|
||||
self._cp_world_size = cp_world_size
|
||||
for layer in self.layers.modules():
|
||||
if getattr(layer, "layer_type", None) == "linear_attention":
|
||||
layer.linear_attn.cp_group = cp_group
|
||||
layer.linear_attn.cp_rank = cp_rank
|
||||
layer.linear_attn.cp_world_size = cp_world_size
|
||||
def set_input_embeddings(self, embeddings: nn.Embedding) -> None:
|
||||
self.embed_tokens = embeddings
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: Optional[torch.LongTensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
inputs_embeds: Optional[torch.FloatTensor] = None,
|
||||
input_ids: torch.LongTensor | None = None,
|
||||
position_ids: torch.LongTensor | None = None,
|
||||
inputs_embeds: torch.Tensor | None = None,
|
||||
routed_experts: torch.LongTensor | None = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
) -> BaseModelOutputWithPast:
|
||||
if (input_ids is None) ^ (inputs_embeds is not None):
|
||||
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
||||
|
||||
) -> BaseModelOutput:
|
||||
if inputs_embeds is None:
|
||||
inputs_embeds = self.embed_tokens(input_ids)
|
||||
|
||||
if position_ids is None:
|
||||
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
||||
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(
|
||||
seq_lens.to(device=inputs_embeds.device),
|
||||
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
|
||||
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
||||
|
||||
cu_seqlens_are_pre_shard = seq_lens_are_pre_shard
|
||||
|
||||
for decoder_layer in self.layers:
|
||||
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,
|
||||
position_embeddings=position_embeddings,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
cu_seqlens_are_pre_shard=cu_seqlens_are_pre_shard,
|
||||
position_embeddings,
|
||||
cu_seqlens,
|
||||
max_seqlen,
|
||||
routed_experts=layer_routed_experts,
|
||||
)
|
||||
|
||||
hidden_states = self.norm(hidden_states)
|
||||
return BaseModelOutputWithPast(last_hidden_state=hidden_states)
|
||||
return BaseModelOutput(last_hidden_state=self.norm(hidden_states))
|
||||
|
||||
|
||||
class Qwen3_5VLMModel(nn.Module):
|
||||
"""Composite VLM body: HF vision encoder + custom PrimeRL dense text model."""
|
||||
|
||||
def __init__(self, config: PretrainedConfig):
|
||||
def __init__(self, config) -> None:
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.visual = Qwen3_5VisionModel._from_config(config.vision_config)
|
||||
self.visual = Qwen3_5VisionModel(config.vision_config)
|
||||
self.language_model = Qwen3_5Model(config.text_config)
|
||||
self.cp_context = CPContext()
|
||||
|
||||
def get_input_embeddings(self):
|
||||
def get_input_embeddings(self) -> nn.Embedding:
|
||||
return self.language_model.get_input_embeddings()
|
||||
|
||||
def set_input_embeddings(self, value):
|
||||
self.language_model.set_input_embeddings(value)
|
||||
def set_input_embeddings(self, embeddings: nn.Embedding) -> None:
|
||||
self.language_model.set_input_embeddings(embeddings)
|
||||
|
||||
def set_context_parallel_attributes(self, cp_group, cp_rank: int, cp_world_size: int) -> None:
|
||||
self.language_model.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
|
||||
|
||||
def _dummy_vision_inputs(self, device: torch.device) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
vcfg = self.config.vision_config
|
||||
m = vcfg.spatial_merge_size
|
||||
num_patches = m * m
|
||||
patch_dim = vcfg.in_channels * vcfg.temporal_patch_size * vcfg.patch_size * vcfg.patch_size
|
||||
pixel_values = torch.zeros(num_patches, patch_dim, device=device, dtype=self.visual.dtype)
|
||||
grid_thw = torch.tensor([[1, m, m]], dtype=torch.long, device=device)
|
||||
return pixel_values, grid_thw
|
||||
|
||||
def prepare_inputs_embeds_and_position_ids(
|
||||
def prepare_inputs(
|
||||
self,
|
||||
input_ids: torch.LongTensor,
|
||||
position_ids: torch.LongTensor | None = None,
|
||||
pixel_values: torch.Tensor | None = None,
|
||||
image_grid_thw: torch.LongTensor | None = None,
|
||||
mm_token_type_ids: torch.LongTensor | None = None,
|
||||
*,
|
||||
position_ids: torch.LongTensor | None,
|
||||
pixel_values: torch.Tensor | None,
|
||||
image_grid_thw: torch.LongTensor | None,
|
||||
mm_token_type_ids: torch.LongTensor | None,
|
||||
seq_lens: torch.LongTensor,
|
||||
) -> tuple[torch.FloatTensor, torch.LongTensor]:
|
||||
) -> tuple[torch.Tensor, torch.LongTensor]:
|
||||
inputs_embeds = self.language_model.embed_tokens(input_ids)
|
||||
|
||||
has_images = pixel_values is not None
|
||||
vision_grid_thw = image_grid_thw
|
||||
vision_grid = image_grid_thw
|
||||
if has_images:
|
||||
pixel_values = pixel_values.type(self.visual.dtype)
|
||||
pixel_values = pixel_values.to(self.visual.dtype)
|
||||
else:
|
||||
pixel_values, vision_grid_thw = self._dummy_vision_inputs(inputs_embeds.device)
|
||||
|
||||
vision_output = self.visual(pixel_values, grid_thw=vision_grid_thw, return_dict=True)
|
||||
image_embeds = vision_output.pooler_output.to(inputs_embeds.device, inputs_embeds.dtype)
|
||||
merge_size = self.config.vision_config.spatial_merge_size
|
||||
num_patches = merge_size**2
|
||||
patch_dim = (
|
||||
self.config.vision_config.in_channels
|
||||
* self.config.vision_config.temporal_patch_size
|
||||
* self.config.vision_config.patch_size**2
|
||||
)
|
||||
pixel_values = torch.zeros(
|
||||
num_patches,
|
||||
patch_dim,
|
||||
device=inputs_embeds.device,
|
||||
dtype=self.visual.dtype,
|
||||
)
|
||||
vision_grid = torch.tensor([[1, merge_size, merge_size]], device=inputs_embeds.device)
|
||||
|
||||
image_embeds = self.visual(pixel_values, vision_grid).pooler_output.to(inputs_embeds.dtype)
|
||||
if has_images:
|
||||
image_mask = input_ids == self.config.image_token_id
|
||||
image_mask = image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
|
||||
image_mask = (input_ids == self.config.image_token_id).unsqueeze(-1).expand_as(inputs_embeds)
|
||||
inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
|
||||
else:
|
||||
# Every rank must retain the vision graph so FSDP collectives stay symmetric.
|
||||
inputs_embeds = inputs_embeds + image_embeds.sum() * 0.0
|
||||
|
||||
if position_ids is None:
|
||||
if image_grid_thw is not None:
|
||||
if image_grid_thw is None:
|
||||
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
||||
else:
|
||||
if mm_token_type_ids is None:
|
||||
raise ValueError("mm_token_type_ids are required with Qwen3.5 image inputs")
|
||||
position_ids = build_qwen3_5_mrope_position_ids(
|
||||
input_ids=input_ids,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
@@ -332,9 +263,6 @@ class Qwen3_5VLMModel(nn.Module):
|
||||
spatial_merge_size=self.config.vision_config.spatial_merge_size,
|
||||
seq_lens=seq_lens,
|
||||
)
|
||||
else:
|
||||
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
||||
|
||||
return inputs_embeds, position_ids
|
||||
|
||||
def forward(
|
||||
@@ -344,105 +272,86 @@ class Qwen3_5VLMModel(nn.Module):
|
||||
pixel_values: torch.Tensor | None = None,
|
||||
image_grid_thw: torch.LongTensor | None = None,
|
||||
mm_token_type_ids: torch.LongTensor | None = None,
|
||||
routed_experts: torch.LongTensor | None = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
) -> BaseModelOutputWithPast:
|
||||
inputs_embeds, position_ids = self.prepare_inputs_embeds_and_position_ids(
|
||||
input_ids=input_ids,
|
||||
position_ids=position_ids,
|
||||
pixel_values=pixel_values,
|
||||
image_grid_thw=image_grid_thw,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
seq_lens=seq_lens,
|
||||
) -> BaseModelOutput:
|
||||
inputs_embeds, position_ids = self.prepare_inputs(
|
||||
input_ids,
|
||||
position_ids,
|
||||
pixel_values,
|
||||
image_grid_thw,
|
||||
mm_token_type_ids,
|
||||
seq_lens,
|
||||
)
|
||||
|
||||
cp_group = getattr(self.language_model, "_cp_group", None)
|
||||
if image_grid_thw is not None and cp_group is not None:
|
||||
cp_rank = self.language_model._cp_rank
|
||||
cp_world_size = self.language_model._cp_world_size
|
||||
setup_cp_attention_params(position_ids, cp_group=cp_group, cp_style="ulysses", seq_lens=seq_lens)
|
||||
inputs_embeds = shard_for_cp(inputs_embeds, cp_rank=cp_rank, cp_world_size=cp_world_size)
|
||||
position_ids = shard_position_ids_for_cp(position_ids, cp_rank=cp_rank, cp_world_size=cp_world_size)
|
||||
if image_grid_thw is not None and self.cp_context.cp_enabled:
|
||||
rank, world_size = self.cp_context.cp_rank, self.cp_context.cp_world_size
|
||||
setup_cp_attention_params(
|
||||
position_ids,
|
||||
cp_group=self.cp_context.cp_group,
|
||||
cp_style=self.cp_context.cp_style,
|
||||
seq_lens=seq_lens,
|
||||
)
|
||||
inputs_embeds = shard_for_cp(inputs_embeds, cp_rank=rank, cp_world_size=world_size)
|
||||
position_ids = shard_position_ids_for_cp(position_ids, cp_rank=rank, cp_world_size=world_size)
|
||||
if routed_experts is not None:
|
||||
routed_experts = shard_for_cp(routed_experts, cp_rank=rank, cp_world_size=world_size)
|
||||
seq_lens_are_pre_shard = True
|
||||
|
||||
return self.language_model(
|
||||
inputs_embeds=inputs_embeds,
|
||||
position_ids=position_ids,
|
||||
routed_experts=routed_experts,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
)
|
||||
|
||||
|
||||
class Qwen3_5ForCausalLM(Qwen3_5PreTrainedModel, GenerationMixin):
|
||||
"""Unified dense Qwen3.5 model for both text-only and VLM configs."""
|
||||
class Qwen3_5ForCausalLM(Qwen3_5PreTrainedModel):
|
||||
def __init__(self, config) -> None:
|
||||
super().__init__(config)
|
||||
self.is_vlm = hasattr(config, "vision_config")
|
||||
text_config = config.text_config if self.is_vlm else config
|
||||
|
||||
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
||||
_checkpoint_conversion_mapping = {}
|
||||
_tp_plan = {"lm_head": "colwise_gather_output"}
|
||||
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
||||
|
||||
def __init__(self, config, **kwargs):
|
||||
super().__init__(config, **kwargs)
|
||||
self._is_vlm = hasattr(config, "vision_config")
|
||||
self.supports_packed_multimodal_training = self._is_vlm
|
||||
|
||||
if self._is_vlm:
|
||||
if self.is_vlm:
|
||||
self.model = Qwen3_5VLMModel(config)
|
||||
text_config = config.text_config
|
||||
self._tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"}
|
||||
else:
|
||||
self.model = Qwen3_5Model(config)
|
||||
text_config = config
|
||||
|
||||
self.vocab_size = text_config.vocab_size
|
||||
self.lm_head = nn.Linear(text_config.hidden_size, text_config.vocab_size, bias=False)
|
||||
self.post_init()
|
||||
self.supports_packed_multimodal_training = self.is_vlm
|
||||
self.lm_head = VanillaOutputLinear(text_config.hidden_size, text_config.vocab_size)
|
||||
|
||||
def get_input_embeddings(self):
|
||||
def get_input_embeddings(self) -> nn.Embedding:
|
||||
return self.model.get_input_embeddings()
|
||||
|
||||
def set_input_embeddings(self, value):
|
||||
self.model.set_input_embeddings(value)
|
||||
|
||||
def set_decoder(self, decoder):
|
||||
self.model = decoder
|
||||
|
||||
def get_decoder(self):
|
||||
return self.model
|
||||
|
||||
def set_context_parallel_attributes(self, cp_group, cp_rank: int, cp_world_size: int) -> None:
|
||||
self.model.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
|
||||
def set_input_embeddings(self, embeddings: nn.Embedding) -> None:
|
||||
self.model.set_input_embeddings(embeddings)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: Optional[torch.LongTensor] = None,
|
||||
attention_mask: Optional[torch.Tensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
past_key_values: Optional[Cache] = None,
|
||||
inputs_embeds: Optional[torch.FloatTensor] = None,
|
||||
labels: Optional[torch.LongTensor] = None,
|
||||
use_cache: Optional[bool] = None,
|
||||
logits_to_keep: Union[int, torch.Tensor] = 0,
|
||||
temperature: Union[torch.Tensor, None] = None,
|
||||
pixel_values: Optional[torch.Tensor] = None,
|
||||
image_grid_thw: Optional[torch.LongTensor] = None,
|
||||
mm_token_type_ids: Optional[torch.LongTensor] = None,
|
||||
input_ids: torch.LongTensor | None = None,
|
||||
position_ids: torch.LongTensor | None = None,
|
||||
inputs_embeds: torch.Tensor | None = None,
|
||||
labels: torch.LongTensor | None = None,
|
||||
temperature: torch.Tensor | None = None,
|
||||
sampling_mask: torch.Tensor | None = None,
|
||||
routed_experts: torch.LongTensor | None = None,
|
||||
pixel_values: torch.Tensor | None = None,
|
||||
image_grid_thw: torch.LongTensor | None = None,
|
||||
mm_token_type_ids: torch.LongTensor | None = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> PrimeLmOutput:
|
||||
assert use_cache is None, "use_cache is not supported for custom qwen3_5 for now"
|
||||
assert past_key_values is None, "past_key_values is not supported for custom qwen3_5 for now"
|
||||
|
||||
if self._is_vlm:
|
||||
if self.is_vlm:
|
||||
outputs = self.model(
|
||||
input_ids=input_ids,
|
||||
position_ids=position_ids,
|
||||
pixel_values=pixel_values,
|
||||
image_grid_thw=image_grid_thw,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
routed_experts=routed_experts,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
)
|
||||
@@ -451,42 +360,35 @@ class Qwen3_5ForCausalLM(Qwen3_5PreTrainedModel, GenerationMixin):
|
||||
input_ids=input_ids,
|
||||
position_ids=position_ids,
|
||||
inputs_embeds=inputs_embeds,
|
||||
routed_experts=routed_experts,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
)
|
||||
|
||||
hidden_states = outputs.last_hidden_state
|
||||
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
||||
return self.lm_head(
|
||||
hidden_states[:, slice_indices, :],
|
||||
labels[:, slice_indices] if labels is not None else None,
|
||||
outputs.last_hidden_state,
|
||||
labels,
|
||||
temperature=temperature,
|
||||
sampling_mask=sampling_mask,
|
||||
)
|
||||
|
||||
def init_buffers_post_meta(self):
|
||||
if self._is_vlm:
|
||||
lm_rope = self.model.language_model.rotary_emb
|
||||
else:
|
||||
lm_rope = self.model.rotary_emb
|
||||
|
||||
if hasattr(lm_rope, "rope_init_fn"):
|
||||
inv_freq, lm_rope.attention_scaling = lm_rope.rope_init_fn(lm_rope.config, lm_rope.inv_freq.device)
|
||||
lm_rope.inv_freq.copy_(inv_freq)
|
||||
|
||||
if self._is_vlm:
|
||||
vis_rope = self.model.visual.rotary_pos_emb
|
||||
if hasattr(vis_rope, "inv_freq"):
|
||||
dim = vis_rope.inv_freq.shape[0]
|
||||
inv_freq = 1.0 / (
|
||||
10000.0
|
||||
** (torch.arange(0, dim * 2, 2, dtype=torch.float32, device=vis_rope.inv_freq.device) / (dim * 2))
|
||||
)
|
||||
vis_rope.inv_freq.copy_(inv_freq)
|
||||
def init_buffers_post_meta(self) -> None:
|
||||
language_model = self.model.language_model if self.is_vlm else self.model
|
||||
language_model.rotary_emb.reset_parameters()
|
||||
if self.is_vlm:
|
||||
self.model.visual.rotary_pos_emb.reset_parameters()
|
||||
for module in self.modules():
|
||||
if 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_5Attention",
|
||||
"Qwen3_5DecoderLayer",
|
||||
"Qwen3_5ForCausalLM",
|
||||
"Qwen3_5GatedFlashAttention",
|
||||
"Qwen3_5Model",
|
||||
"Qwen3_5PreTrainedModel",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
|
||||
class Qwen3_5RMSNorm(nn.Module):
|
||||
"""Qwen's 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.variance_epsilon = 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
|
||||
hidden_states = hidden_states.float()
|
||||
variance = hidden_states.square().mean(dim=-1, keepdim=True)
|
||||
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
||||
return ((1.0 + self.weight.float()) * hidden_states).to(input_dtype)
|
||||
|
||||
|
||||
__all__ = ["Qwen3_5RMSNorm"]
|
||||
@@ -0,0 +1,171 @@
|
||||
import itertools
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
||||
|
||||
from prime_rl.trainer.models.qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfig
|
||||
|
||||
|
||||
class Qwen3_5RotaryEmbedding(nn.Module):
|
||||
inv_freq: torch.Tensor
|
||||
|
||||
def __init__(self, config: Qwen3_5TextConfig, device=None) -> None:
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.max_seq_len_cached = config.max_position_embeddings
|
||||
self.original_max_seq_len = config.max_position_embeddings
|
||||
self.rope_type = config.rope_parameters["rope_type"]
|
||||
self.rope_init_fn = self.compute_default_rope_parameters
|
||||
if self.rope_type != "default":
|
||||
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
||||
|
||||
inv_freq, self.attention_scaling = self.rope_init_fn(config, device)
|
||||
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
||||
self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
|
||||
|
||||
self.mrope_section = config.rope_parameters.get("mrope_section")
|
||||
if self.mrope_section is None:
|
||||
self.mrope_section = self.scaled_mrope_section(inv_freq.numel())
|
||||
|
||||
@staticmethod
|
||||
def scaled_mrope_section(num_rotary_pairs: int) -> list[int]:
|
||||
default_section = [11, 11, 10]
|
||||
total = sum(default_section)
|
||||
section = [num_rotary_pairs * size // total for size in default_section]
|
||||
remainder_order = sorted(
|
||||
range(len(section)),
|
||||
key=lambda index: num_rotary_pairs * default_section[index] % total,
|
||||
reverse=True,
|
||||
)
|
||||
for index in remainder_order[: num_rotary_pairs - sum(section)]:
|
||||
section[index] += 1
|
||||
return section
|
||||
|
||||
@staticmethod
|
||||
def compute_default_rope_parameters(
|
||||
config: Qwen3_5TextConfig,
|
||||
device: torch.device | None = None,
|
||||
seq_len: int | None = None,
|
||||
) -> tuple[torch.Tensor, float]:
|
||||
rope_parameters = config.rope_parameters
|
||||
rotary_dim = int(config.head_dim * rope_parameters.get("partial_rotary_factor", 1.0))
|
||||
positions = torch.arange(0, rotary_dim, 2, dtype=torch.int64, device=device).float()
|
||||
return 1.0 / (rope_parameters["rope_theta"] ** (positions / rotary_dim)), 1.0
|
||||
|
||||
def reset_parameters(self) -> None:
|
||||
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, self.inv_freq.device)
|
||||
self.inv_freq.copy_(inv_freq)
|
||||
self.original_inv_freq.copy_(inv_freq)
|
||||
|
||||
@torch.no_grad()
|
||||
@dynamic_rope_update
|
||||
def forward(self, hidden_states: torch.Tensor, position_ids: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
if position_ids.ndim == 2:
|
||||
position_ids = position_ids.unsqueeze(0).expand(3, -1, -1)
|
||||
|
||||
position_ids = position_ids.to(hidden_states.device)
|
||||
inv_freq = self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1)
|
||||
positions = position_ids[:, :, None, :].float()
|
||||
device_type = hidden_states.device.type if hidden_states.device.type != "mps" else "cpu"
|
||||
with torch.autocast(device_type=device_type, enabled=False):
|
||||
frequencies = (inv_freq @ positions).transpose(2, 3)
|
||||
interleaved = frequencies[0].clone()
|
||||
for dimension, offset in enumerate((1, 2), start=1):
|
||||
index = slice(offset, self.mrope_section[dimension] * 3, 3)
|
||||
interleaved[..., index] = frequencies[dimension, ..., index]
|
||||
embeddings = torch.cat((interleaved, interleaved), dim=-1)
|
||||
cos = embeddings.cos() * self.attention_scaling
|
||||
sin = embeddings.sin() * self.attention_scaling
|
||||
return cos.to(hidden_states.dtype), sin.to(hidden_states.dtype)
|
||||
|
||||
|
||||
def get_qwen3_5_vision_position_ids(
|
||||
*,
|
||||
start_position: int,
|
||||
grid_thw: torch.Tensor,
|
||||
spatial_merge_size: int,
|
||||
temporal_merge_size: int = 1,
|
||||
time_interval: int = 1,
|
||||
device: torch.device | None = None,
|
||||
) -> torch.LongTensor:
|
||||
grid_t = int(grid_thw[0].item()) // temporal_merge_size
|
||||
grid_h = int(grid_thw[1].item()) // spatial_merge_size
|
||||
grid_w = int(grid_thw[2].item()) // spatial_merge_size
|
||||
|
||||
temporal = torch.arange(grid_t, device=device) * time_interval + start_position
|
||||
height = torch.arange(grid_h, device=device) + start_position
|
||||
width = torch.arange(grid_w, device=device) + start_position
|
||||
return torch.stack(
|
||||
[
|
||||
temporal.repeat_interleave(grid_h * grid_w),
|
||||
height.repeat_interleave(grid_w).repeat(grid_t),
|
||||
width.repeat(grid_h * grid_t),
|
||||
],
|
||||
dim=0,
|
||||
)
|
||||
|
||||
|
||||
def build_qwen3_5_mrope_position_ids(
|
||||
*,
|
||||
input_ids: torch.LongTensor,
|
||||
mm_token_type_ids: torch.LongTensor,
|
||||
image_grid_thw: torch.LongTensor | None,
|
||||
spatial_merge_size: int,
|
||||
seq_lens: torch.Tensor,
|
||||
) -> torch.LongTensor:
|
||||
seq_lens = seq_lens.to(device=input_ids.device, dtype=torch.long)
|
||||
|
||||
image_grids = iter(image_grid_thw) if image_grid_thw is not None else None
|
||||
position_ids = torch.empty(3, 1, input_ids.shape[1], dtype=input_ids.dtype, device=input_ids.device)
|
||||
offset = 0
|
||||
for sequence_length_tensor in seq_lens:
|
||||
sequence_length = int(sequence_length_tensor)
|
||||
token_types = mm_token_type_ids[0, offset : offset + sequence_length]
|
||||
current_position = 0
|
||||
sequence_positions = []
|
||||
|
||||
for modality, indexed_group in itertools.groupby(enumerate(token_types.tolist()), lambda item: item[1]):
|
||||
group = list(indexed_group)
|
||||
group_length = group[-1][0] - group[0][0] + 1
|
||||
if modality == 0:
|
||||
text_positions = torch.arange(group_length, device=input_ids.device) + current_position
|
||||
sequence_positions.append(text_positions.unsqueeze(0).expand(3, -1))
|
||||
current_position += group_length
|
||||
continue
|
||||
if modality == 2:
|
||||
raise ValueError("Qwen3.5 video MRoPE is not supported")
|
||||
if modality != 1:
|
||||
raise ValueError(f"Unsupported Qwen3.5 multimodal token type: {modality}")
|
||||
if image_grids is None:
|
||||
raise ValueError("image_grid_thw is required for image tokens")
|
||||
|
||||
remaining = group_length
|
||||
while remaining:
|
||||
grid = next(image_grids, None)
|
||||
if grid is None:
|
||||
raise ValueError("Not enough image_grid_thw rows for the image tokens")
|
||||
image_positions = get_qwen3_5_vision_position_ids(
|
||||
start_position=current_position,
|
||||
grid_thw=grid,
|
||||
spatial_merge_size=spatial_merge_size,
|
||||
device=input_ids.device,
|
||||
)
|
||||
if image_positions.shape[1] > remaining:
|
||||
raise ValueError("Image token group length does not match image_grid_thw")
|
||||
sequence_positions.append(image_positions)
|
||||
current_position += max(int(grid[1]), int(grid[2])) // spatial_merge_size
|
||||
remaining -= image_positions.shape[1]
|
||||
|
||||
positions = torch.cat(sequence_positions, dim=1)
|
||||
if positions.shape[1] != sequence_length:
|
||||
raise ValueError("Built MRoPE positions do not match the packed sequence length")
|
||||
position_ids[:, 0, offset : offset + sequence_length] = positions
|
||||
offset += sequence_length
|
||||
|
||||
if image_grids is not None and next(image_grids, None) is not None:
|
||||
raise ValueError("image_grid_thw contains unused rows")
|
||||
return position_ids
|
||||
|
||||
|
||||
__all__ = ["Qwen3_5RotaryEmbedding", "build_qwen3_5_mrope_position_ids", "get_qwen3_5_vision_position_ids"]
|
||||
@@ -0,0 +1,263 @@
|
||||
import math
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import nn
|
||||
from transformers.modeling_outputs import BaseModelOutputWithPooling
|
||||
|
||||
from prime_rl.trainer.models.layers.attn import (
|
||||
flash_attn_3_varlen_func,
|
||||
flash_attn_4_varlen_func,
|
||||
flash_attn_varlen_func,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.rotary_emb import rotate_half
|
||||
from prime_rl.trainer.models.qwen3_5.configuration_qwen3_5 import Qwen3_5VisionConfig
|
||||
|
||||
|
||||
class Qwen3_5VisionRotaryEmbedding(nn.Module):
|
||||
def __init__(self, dim: int, theta: float = 10_000.0) -> None:
|
||||
super().__init__()
|
||||
self.dim = dim
|
||||
self.theta = theta
|
||||
self.register_buffer("inv_freq", torch.empty(dim // 2), persistent=False)
|
||||
self.reset_parameters()
|
||||
|
||||
def reset_parameters(self) -> None:
|
||||
positions = torch.arange(0, self.dim, 2, dtype=torch.float32, device=self.inv_freq.device)
|
||||
self.inv_freq.copy_(1.0 / (self.theta ** (positions / self.dim)))
|
||||
|
||||
def forward(self, sequence_length: int) -> torch.Tensor:
|
||||
positions = torch.arange(sequence_length, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
|
||||
return torch.outer(positions, self.inv_freq)
|
||||
|
||||
|
||||
class Qwen3_5VisionPatchEmbed(nn.Module):
|
||||
def __init__(self, config: Qwen3_5VisionConfig) -> None:
|
||||
super().__init__()
|
||||
self.in_channels = config.in_channels
|
||||
self.temporal_patch_size = config.temporal_patch_size
|
||||
self.patch_size = config.patch_size
|
||||
kernel_size = (self.temporal_patch_size, self.patch_size, self.patch_size)
|
||||
self.proj = nn.Conv3d(
|
||||
self.in_channels,
|
||||
config.hidden_size,
|
||||
kernel_size=kernel_size,
|
||||
stride=kernel_size,
|
||||
bias=True,
|
||||
)
|
||||
|
||||
def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
|
||||
pixel_values = pixel_values.view(
|
||||
-1,
|
||||
self.in_channels,
|
||||
self.temporal_patch_size,
|
||||
self.patch_size,
|
||||
self.patch_size,
|
||||
)
|
||||
return self.proj(pixel_values.to(self.proj.weight.dtype)).view(pixel_values.shape[0], -1)
|
||||
|
||||
|
||||
class Qwen3_5VisionMLP(nn.Module):
|
||||
def __init__(self, config: Qwen3_5VisionConfig) -> None:
|
||||
super().__init__()
|
||||
self.linear_fc1 = nn.Linear(config.hidden_size, config.intermediate_size, bias=True)
|
||||
self.linear_fc2 = nn.Linear(config.intermediate_size, config.hidden_size, bias=True)
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
return self.linear_fc2(F.gelu(self.linear_fc1(hidden_states), approximate="tanh"))
|
||||
|
||||
|
||||
class Qwen3_5VisionAttention(nn.Module):
|
||||
FLASH_ATTENTION_FUNCTIONS = {
|
||||
"flash_attention_2": flash_attn_varlen_func,
|
||||
"flash_attention_3": flash_attn_3_varlen_func,
|
||||
"flash_attention_4": flash_attn_4_varlen_func,
|
||||
}
|
||||
|
||||
def __init__(self, config: Qwen3_5VisionConfig) -> None:
|
||||
super().__init__()
|
||||
self.num_heads = config.num_heads
|
||||
self.head_dim = config.hidden_size // config.num_heads
|
||||
self.qkv = nn.Linear(config.hidden_size, config.hidden_size * 3, bias=True)
|
||||
self.proj = nn.Linear(config.hidden_size, config.hidden_size, bias=True)
|
||||
self.attention_implementation = config._attn_implementation
|
||||
self.flash_attention = self.FLASH_ATTENTION_FUNCTIONS[self.attention_implementation]
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
cu_seqlens: torch.IntTensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
) -> torch.Tensor:
|
||||
sequence_length = hidden_states.shape[0]
|
||||
query, key, value = (
|
||||
self.qkv(hidden_states).view(sequence_length, 3, self.num_heads, self.head_dim).unbind(dim=1)
|
||||
)
|
||||
cos, sin = position_embeddings
|
||||
cos = cos.unsqueeze(1).float()
|
||||
sin = sin.unsqueeze(1).float()
|
||||
query_dtype = query.dtype
|
||||
query = ((query.float() * cos) + (rotate_half(query.float()) * sin)).to(query_dtype)
|
||||
key = ((key.float() * cos) + (rotate_half(key.float()) * sin)).to(query_dtype)
|
||||
|
||||
if self.attention_implementation == "flash_attention_4":
|
||||
attention_output, _ = self.flash_attention(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
cu_seqlens_q=cu_seqlens,
|
||||
cu_seqlens_k=cu_seqlens,
|
||||
causal=False,
|
||||
)
|
||||
else:
|
||||
max_sequence_length = int((cu_seqlens[1:] - cu_seqlens[:-1]).max())
|
||||
attention_output = self.flash_attention(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
cu_seqlens,
|
||||
cu_seqlens,
|
||||
max_sequence_length,
|
||||
max_sequence_length,
|
||||
causal=False,
|
||||
)
|
||||
return self.proj(attention_output.reshape(sequence_length, -1))
|
||||
|
||||
|
||||
class Qwen3_5VisionBlock(nn.Module):
|
||||
def __init__(self, config: Qwen3_5VisionConfig) -> None:
|
||||
super().__init__()
|
||||
self.norm1 = nn.LayerNorm(config.hidden_size, eps=1e-6)
|
||||
self.norm2 = nn.LayerNorm(config.hidden_size, eps=1e-6)
|
||||
self.attn = Qwen3_5VisionAttention(config)
|
||||
self.mlp = Qwen3_5VisionMLP(config)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
cu_seqlens: torch.IntTensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
) -> torch.Tensor:
|
||||
hidden_states = hidden_states + self.attn(self.norm1(hidden_states), cu_seqlens, position_embeddings)
|
||||
return hidden_states + self.mlp(self.norm2(hidden_states))
|
||||
|
||||
|
||||
class Qwen3_5VisionPatchMerger(nn.Module):
|
||||
def __init__(self, config: Qwen3_5VisionConfig) -> None:
|
||||
super().__init__()
|
||||
merged_hidden_size = config.hidden_size * config.spatial_merge_size**2
|
||||
self.merged_hidden_size = merged_hidden_size
|
||||
self.norm = nn.LayerNorm(config.hidden_size, eps=1e-6)
|
||||
self.linear_fc1 = nn.Linear(merged_hidden_size, merged_hidden_size)
|
||||
self.linear_fc2 = nn.Linear(merged_hidden_size, config.out_hidden_size)
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
hidden_states = self.norm(hidden_states).view(-1, self.merged_hidden_size)
|
||||
return self.linear_fc2(F.gelu(self.linear_fc1(hidden_states)))
|
||||
|
||||
|
||||
class Qwen3_5VisionModel(nn.Module):
|
||||
def __init__(self, config: Qwen3_5VisionConfig) -> None:
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.spatial_merge_size = config.spatial_merge_size
|
||||
self.patch_embed = Qwen3_5VisionPatchEmbed(config)
|
||||
self.pos_embed = nn.Embedding(config.num_position_embeddings, config.hidden_size)
|
||||
self.num_grid_per_side = math.isqrt(config.num_position_embeddings)
|
||||
self.rotary_pos_emb = Qwen3_5VisionRotaryEmbedding(config.hidden_size // config.num_heads // 2)
|
||||
self.blocks = nn.ModuleList(Qwen3_5VisionBlock(config) for _ in range(config.depth))
|
||||
self.merger = Qwen3_5VisionPatchMerger(config)
|
||||
|
||||
@property
|
||||
def dtype(self) -> torch.dtype:
|
||||
return self.patch_embed.proj.weight.dtype
|
||||
|
||||
def rotary_embeddings(self, grid_thw: torch.Tensor) -> torch.Tensor:
|
||||
grids = grid_thw.tolist()
|
||||
frequency_table = self.rotary_pos_emb(max(max(height, width) for _, height, width in grids))
|
||||
coordinates = []
|
||||
merge_size = self.spatial_merge_size
|
||||
for frames, height, width in grids:
|
||||
block_rows = torch.arange(height // merge_size, device=frequency_table.device)
|
||||
block_columns = torch.arange(width // merge_size, device=frequency_table.device)
|
||||
intra_rows = torch.arange(merge_size, device=frequency_table.device)
|
||||
intra_columns = torch.arange(merge_size, device=frequency_table.device)
|
||||
rows = block_rows[:, None, None, None] * merge_size + intra_rows[None, None, :, None]
|
||||
columns = block_columns[None, :, None, None] * merge_size + intra_columns[None, None, None, :]
|
||||
rows = rows.expand(height // merge_size, width // merge_size, merge_size, merge_size).reshape(-1)
|
||||
columns = columns.expand(height // merge_size, width // merge_size, merge_size, merge_size).reshape(-1)
|
||||
coordinates.append(torch.stack((rows, columns), dim=-1).repeat(frames, 1))
|
||||
return frequency_table[torch.cat(coordinates)].flatten(1)
|
||||
|
||||
def interpolated_position_embeddings(self, grid_thw: torch.Tensor) -> torch.Tensor:
|
||||
embeddings = []
|
||||
merge_size = self.spatial_merge_size
|
||||
for frames, height, width in grid_thw.tolist():
|
||||
row_positions = torch.linspace(
|
||||
0,
|
||||
self.num_grid_per_side - 1,
|
||||
height,
|
||||
device=self.pos_embed.weight.device,
|
||||
)
|
||||
column_positions = torch.linspace(
|
||||
0,
|
||||
self.num_grid_per_side - 1,
|
||||
width,
|
||||
device=self.pos_embed.weight.device,
|
||||
)
|
||||
row_floor = row_positions.floor().long()
|
||||
column_floor = column_positions.floor().long()
|
||||
row_ceil = (row_floor + 1).clamp_max(self.num_grid_per_side - 1)
|
||||
column_ceil = (column_floor + 1).clamp_max(self.num_grid_per_side - 1)
|
||||
row_fraction = row_positions - row_floor
|
||||
column_fraction = column_positions - column_floor
|
||||
|
||||
indices = torch.stack(
|
||||
[
|
||||
(row_floor[:, None] * self.num_grid_per_side + column_floor[None, :]).flatten(),
|
||||
(row_floor[:, None] * self.num_grid_per_side + column_ceil[None, :]).flatten(),
|
||||
(row_ceil[:, None] * self.num_grid_per_side + column_floor[None, :]).flatten(),
|
||||
(row_ceil[:, None] * self.num_grid_per_side + column_ceil[None, :]).flatten(),
|
||||
]
|
||||
)
|
||||
weights = torch.stack(
|
||||
[
|
||||
((1 - row_fraction)[:, None] * (1 - column_fraction)[None, :]).flatten(),
|
||||
((1 - row_fraction)[:, None] * column_fraction[None, :]).flatten(),
|
||||
(row_fraction[:, None] * (1 - column_fraction)[None, :]).flatten(),
|
||||
(row_fraction[:, None] * column_fraction[None, :]).flatten(),
|
||||
]
|
||||
).to(self.pos_embed.weight.dtype)
|
||||
position_embedding = (self.pos_embed(indices) * weights[..., None]).sum(dim=0).repeat(frames, 1)
|
||||
position_embedding = (
|
||||
position_embedding.view(
|
||||
frames,
|
||||
height // merge_size,
|
||||
merge_size,
|
||||
width // merge_size,
|
||||
merge_size,
|
||||
-1,
|
||||
)
|
||||
.permute(0, 1, 3, 2, 4, 5)
|
||||
.flatten(0, 4)
|
||||
)
|
||||
embeddings.append(position_embedding)
|
||||
return torch.cat(embeddings)
|
||||
|
||||
def forward(self, pixel_values: torch.Tensor, grid_thw: torch.Tensor) -> BaseModelOutputWithPooling:
|
||||
hidden_states = self.patch_embed(pixel_values)
|
||||
hidden_states = hidden_states + self.interpolated_position_embeddings(grid_thw)
|
||||
rotary = self.rotary_embeddings(grid_thw)
|
||||
rotary = torch.cat((rotary, rotary), dim=-1)
|
||||
position_embeddings = (rotary.cos(), rotary.sin())
|
||||
sequence_lengths = torch.repeat_interleave(grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0])
|
||||
cu_seqlens = F.pad(sequence_lengths.cumsum(dim=0, dtype=torch.int32), (1, 0))
|
||||
for block in self.blocks:
|
||||
hidden_states = block(hidden_states, cu_seqlens, position_embeddings)
|
||||
return BaseModelOutputWithPooling(
|
||||
last_hidden_state=hidden_states,
|
||||
pooler_output=self.merger(hidden_states),
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["Qwen3_5VisionModel"]
|
||||
@@ -1,13 +0,0 @@
|
||||
from prime_rl.trainer.models.qwen3_5_moe.configuration_qwen3_5_moe import Qwen3_5MoeConfig
|
||||
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import (
|
||||
Qwen3_5MoeForCausalLM,
|
||||
Qwen3_5MoeModel,
|
||||
Qwen3_5MoePreTrainedModel,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"Qwen3_5MoeConfig",
|
||||
"Qwen3_5MoeForCausalLM",
|
||||
"Qwen3_5MoeModel",
|
||||
"Qwen3_5MoePreTrainedModel",
|
||||
]
|
||||
@@ -1,106 +0,0 @@
|
||||
from transformers.configuration_utils import PretrainedConfig
|
||||
|
||||
|
||||
class Qwen3_5MoeConfig(PretrainedConfig):
|
||||
r"""
|
||||
Configuration class for the custom PrimeRL Qwen3.5-MoE model.
|
||||
|
||||
This matches the HuggingFace `Qwen3_5MoeTextConfig` architecture:
|
||||
hybrid attention (GatedDeltaNet linear + gated softmax), MoE with gated shared expert,
|
||||
and (1+weight) RMSNorm parameterization.
|
||||
|
||||
Defaults match Qwen3.5-35B-A3B.
|
||||
"""
|
||||
|
||||
model_type = "qwen3_5_moe_text"
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vocab_size=248320,
|
||||
hidden_size=2048,
|
||||
num_hidden_layers=40,
|
||||
num_attention_heads=16,
|
||||
num_key_value_heads=2,
|
||||
hidden_act="silu",
|
||||
max_position_embeddings=32768,
|
||||
initializer_range=0.02,
|
||||
rms_norm_eps=1e-6,
|
||||
use_cache=True,
|
||||
tie_word_embeddings=False,
|
||||
rope_theta=10000.0,
|
||||
rope_scaling=None,
|
||||
attention_bias=False,
|
||||
attention_dropout=0.0,
|
||||
head_dim=256,
|
||||
# Linear attention (GatedDeltaNet) params
|
||||
linear_conv_kernel_dim=4,
|
||||
linear_key_head_dim=128,
|
||||
linear_value_head_dim=128,
|
||||
linear_num_key_heads=16,
|
||||
linear_num_value_heads=32,
|
||||
# MoE params
|
||||
moe_intermediate_size=512,
|
||||
shared_expert_intermediate_size=512,
|
||||
num_experts_per_tok=8,
|
||||
num_experts=256,
|
||||
output_router_logits=False,
|
||||
router_aux_loss_coef=0.001,
|
||||
# Layer type configuration
|
||||
layer_types=None,
|
||||
# PrimeRL additions
|
||||
load_balance_coeff=None,
|
||||
pad_token_id=None,
|
||||
**kwargs,
|
||||
):
|
||||
self.vocab_size = vocab_size
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
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.hidden_act = hidden_act
|
||||
self.initializer_range = initializer_range
|
||||
self.rms_norm_eps = rms_norm_eps
|
||||
self.use_cache = use_cache
|
||||
self.rope_theta = rope_theta
|
||||
self.rope_scaling = rope_scaling
|
||||
self.attention_bias = attention_bias
|
||||
self.attention_dropout = attention_dropout
|
||||
self.head_dim = head_dim
|
||||
self.pad_token_id = pad_token_id
|
||||
|
||||
# Partial RoPE: only rotate 25% of head_dim
|
||||
kwargs.setdefault("partial_rotary_factor", 0.25)
|
||||
|
||||
# Layer types: default every 4th layer is full_attention, rest linear_attention
|
||||
self.layer_types = layer_types
|
||||
if self.layer_types is None:
|
||||
interval_pattern = kwargs.pop("full_attention_interval", 4)
|
||||
self.layer_types = [
|
||||
"linear_attention" if bool((i + 1) % interval_pattern) else "full_attention"
|
||||
for i in range(self.num_hidden_layers)
|
||||
]
|
||||
|
||||
# Linear attention (GatedDeltaNet) params
|
||||
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
|
||||
|
||||
# MoE params
|
||||
self.moe_intermediate_size = moe_intermediate_size
|
||||
self.shared_expert_intermediate_size = shared_expert_intermediate_size
|
||||
self.num_experts_per_tok = num_experts_per_tok
|
||||
self.num_experts = num_experts
|
||||
self.output_router_logits = output_router_logits
|
||||
self.router_aux_loss_coef = router_aux_loss_coef
|
||||
|
||||
# PrimeRL additions
|
||||
self.load_balance_coeff = load_balance_coeff
|
||||
|
||||
super().__init__(
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
**kwargs,
|
||||
)
|
||||
@@ -1,25 +0,0 @@
|
||||
"""HF<->prime weight conversion for Qwen3.5-MoE, as a declarative op chain.
|
||||
|
||||
Per layer: the router and shared-expert output gate are nested under their
|
||||
PrimeRL modules, and routed experts use stacked canonical projections.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from prime_rl.trainer.models.conversion_ops import ConvOp, Rename, routed_experts_op
|
||||
|
||||
|
||||
def _conversion_chain(config, model_prefix: str) -> list[ConvOp]:
|
||||
ops: list[ConvOp] = []
|
||||
for i in range(config.num_hidden_layers):
|
||||
p = f"{model_prefix}.layers.{i}"
|
||||
# Router: mlp.gate.weight -> mlp.router.gate.weight
|
||||
ops.append(Rename(f"{p}.mlp.gate.weight", f"{p}.mlp.router.gate.weight"))
|
||||
ops.append(Rename(f"{p}.mlp.shared_expert_gate.weight", f"{p}.mlp.shared_expert.output_gate.weight"))
|
||||
ops.append(routed_experts_op(p, hf_experts="mlp.experts", prime_experts="mlp.experts", fused=True))
|
||||
return ops
|
||||
|
||||
|
||||
def conversion_chain(config) -> list[ConvOp]:
|
||||
text_config = getattr(config, "text_config", config)
|
||||
return _conversion_chain(text_config, "model") + _conversion_chain(text_config, "model.language_model")
|
||||
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user