Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
550beb6f43 | ||
|
|
bad80b1a30 | ||
|
|
aa3a6522b4 | ||
|
|
3f0c2e3b5a | ||
|
|
6b0d9e504b | ||
|
|
751a235af8 | ||
|
|
daa72a91d8 | ||
|
|
dad79d1ce8 | ||
|
|
dd2dd5461b |
@@ -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 | ❌ | ✅ |
|
||||
|
||||
|
||||
|
||||
Vendored
+1
-1
Submodule deps/verifiers updated: 828488fffe...392d596de8
+24
-1
@@ -34,10 +34,13 @@ 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`, … | ✅ | ✅ |
|
||||
|
||||
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:
|
||||
@@ -65,6 +68,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
|
||||
|
||||
+1
-1
@@ -112,7 +112,7 @@ For DeepEP, set `type = "deepep"` and tune `num_sms` plus optional `token_chunk_
|
||||
|
||||
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.
|
||||
|
||||
`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]
|
||||
|
||||
+2
-2
@@ -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
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ End-to-end usage examples for prime-rl, referenced from the top-level [README](.
|
||||
- `wiki-search` — multi-turn tool calling, LoRA
|
||||
- `wordle` — multi-turn (~6-turn games)
|
||||
- `hendrycks-sanity` — single-turn math, long-running
|
||||
- `dynamo` — five-step Qwen3 math training with external Dynamo inference and NCCL weight updates
|
||||
- **[`advanced/`](advanced)** — larger, mostly multi-node runs on frontier models, one folder
|
||||
per model: `qwen3-30b-a3b` (math/swe/tool), `glm-4.5-air` (search/swe/terminal), `glm-5.2`
|
||||
(large-scale + PD-disaggregated inference), `minimax-m2.5` (swe), `nemotron-3-super` (swe),
|
||||
|
||||
@@ -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/basic/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
|
||||
@@ -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 (
|
||||
@@ -180,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"
|
||||
|
||||
+18
-4
@@ -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
|
||||
@@ -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" }
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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)
|
||||
@@ -183,6 +183,15 @@ class AdminPlane:
|
||||
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
|
||||
|
||||
@@ -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 AdminPlane, 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
|
||||
@@ -208,7 +208,7 @@ class Orchestrator:
|
||||
eval_client_type="openai_chat_completions",
|
||||
renderer_config=config.renderer,
|
||||
)
|
||||
self.admin_plane = AdminPlane(config.model.client)
|
||||
self.admin_plane = setup_admin_plane(config.model.client, config.model.name)
|
||||
|
||||
await monitors.setup(
|
||||
producer="orch",
|
||||
|
||||
@@ -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,7 @@ 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,
|
||||
@@ -150,7 +150,7 @@ def _patch_qwen3_5_linear_attn_varlen():
|
||||
|
||||
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.
|
||||
vLLM (target <0.01).
|
||||
"""
|
||||
import torch.nn.functional as F
|
||||
from transformers.models.qwen3_5.modeling_qwen3_5 import (
|
||||
@@ -461,20 +461,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
|
||||
@@ -567,20 +569,6 @@ def get_model(
|
||||
"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()
|
||||
@@ -645,15 +633,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)
|
||||
@@ -1290,9 +1269,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:
|
||||
|
||||
@@ -31,13 +31,13 @@ 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_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.
|
||||
|
||||
_CUSTOM_CAUSAL_LM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, OrderedDict())
|
||||
_CUSTOM_CAUSAL_LM_MODELS: tuple[
|
||||
|
||||
@@ -27,10 +27,9 @@ Design constraints:
|
||||
* **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
|
||||
|
||||
@@ -113,23 +113,22 @@ All three layer types reach their keys the same way. `SparseAttnInputs` lays out
|
||||
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
|
||||
`min(index_topk, entries)` 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.
|
||||
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
|
||||
from torch import Tensor, nn
|
||||
|
||||
from prime_rl.trainer.models.deepseek_v4.configuration_deepseek_v4 import DeepseekV4Config
|
||||
from prime_rl.trainer.models.deepseek_v4.eager_reference import dense_mask_from_indices, eager_attention_with_sinks
|
||||
from prime_rl.trainer.models.deepseek_v4.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.sequence import get_cu_seqlens_from_seq_lens
|
||||
|
||||
@@ -324,27 +323,6 @@ 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:
|
||||
|
||||
- `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.
|
||||
|
||||
One `seq_lens` describes one packed row, so the leading axis is 1 and broadcasts over the
|
||||
batch, as `threshold` does.
|
||||
|
||||
`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.
|
||||
"""
|
||||
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, :])
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SparseAttnInputs:
|
||||
@@ -501,41 +479,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 `IGNORE_SLOT` (-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):
|
||||
@@ -547,33 +496,31 @@ 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)
|
||||
|
||||
@torch.no_grad() # Returns non-differentiable integer indices.
|
||||
def forward(self, hidden_states: torch.Tensor, q_residual: torch.Tensor, packed: PackedContext) -> torch.Tensor:
|
||||
batch, seq_len, _ = hidden_states.shape
|
||||
assert batch == 1, f"the indexer needs a packed batch of size 1, got {batch}"
|
||||
compressed_kv = self.compressor.compress(hidden_states, packed)
|
||||
compressed_len = compressed_kv.shape[1]
|
||||
top_k = min(self.index_topk, compressed_len)
|
||||
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 `IGNORE_SLOT` (-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, IGNORE_SLOT)
|
||||
)
|
||||
# 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)
|
||||
@@ -689,57 +636,15 @@ 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))
|
||||
self.attn_impl = config._attn_impl
|
||||
# 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 self.attn_impl == "kernel" else None
|
||||
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
|
||||
|
||||
def _eager(self, q: Tensor, kv: Tensor, attention_mask: Tensor) -> Tensor:
|
||||
return eager_attention_with_sinks(
|
||||
q,
|
||||
kv,
|
||||
kv,
|
||||
self.sinks,
|
||||
attention_mask,
|
||||
scaling=self.scaling,
|
||||
dropout=self.attention_dropout,
|
||||
training=self.training,
|
||||
)
|
||||
|
||||
def _attend(self, q: Tensor, kv: Tensor, compressed: tuple[Tensor, Tensor] | None, packed: PackedContext) -> Tensor:
|
||||
"""Attend `q` (b, h, t, d) over the local KV `kv` (b, 1, t, d), plus any compressed entries.
|
||||
|
||||
Returns (b, t, h, d). A sliding layer sees only its window and passes `compressed` as
|
||||
`None`; a compressed layer reaches further through its compressor's output, the entries
|
||||
paired with the per-query indices selecting among them.
|
||||
|
||||
Every layer lays its slots out once, in `SparseAttnInputs`, and then differs only in the
|
||||
attention core it hands them to, so the eager consumer is an oracle for the kernel rather
|
||||
than a second answer to which keys a query reads.
|
||||
"""
|
||||
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,
|
||||
)
|
||||
if self.attn_impl == "eager":
|
||||
n_positions = inputs.kv_buf.shape[1]
|
||||
attention_mask = dense_mask_from_indices(inputs.indices, n_positions, q.dtype)
|
||||
return self._eager(q, inputs.kv_buf.transpose(1, 2), attention_mask)
|
||||
|
||||
# `eager_attention_with_sinks` drops attention weights and the kernel does not, so the
|
||||
# two only agree at zero. The default is 0.0 but a config may set it.
|
||||
assert self.attention_dropout == 0.0, "the fused sparse attention kernel implements no dropout"
|
||||
q = q.transpose(1, 2).contiguous() # the kernel asserts contiguity
|
||||
out, _ = dsv4_sparse_attn(q, inputs.kv_buf, inputs.indices, self.sinks, self.scaling)
|
||||
return out
|
||||
|
||||
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:
|
||||
@@ -767,7 +672,20 @@ class DeepseekV4Attention(nn.Module):
|
||||
kv = apply_rotary_pos_emb_interleaved(kv, cos, sin)
|
||||
|
||||
compressed = self.compressor(hidden_states, q_residual, packed) if self.compressor is not None else None
|
||||
attn_output = self._attend(q, kv, compressed, packed) # (b, t, h, d)
|
||||
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,
|
||||
self.scaling,
|
||||
) # (b, t, h, d)
|
||||
|
||||
# The value stream is the key stream, so it arrived rotated. Rotating the output
|
||||
# by the conjugate angle at the query position cancels that out.
|
||||
@@ -792,9 +710,6 @@ __all__ = [
|
||||
"DeepseekV4GroupedLinear",
|
||||
"DeepseekV4HCACompressor",
|
||||
"DeepseekV4Indexer",
|
||||
"DeepseekV4IndexerScorer",
|
||||
"PackedContext",
|
||||
"SparseAttnInputs",
|
||||
"dense_mask_from_indices",
|
||||
"eager_attention_with_sinks",
|
||||
]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from typing import Any, Literal
|
||||
from typing import Any
|
||||
|
||||
from huggingface_hub.dataclasses import strict
|
||||
from transformers.configuration_utils import PretrainedConfig
|
||||
@@ -125,7 +125,6 @@ class DeepseekV4Config(PretrainedConfig):
|
||||
index_n_heads: int = 64,
|
||||
index_head_dim: int = 128,
|
||||
index_topk: int = 512,
|
||||
_attn_impl: Literal["kernel", "eager"] = "kernel",
|
||||
num_experts_per_tok: int = 6,
|
||||
n_routed_experts: int = 256,
|
||||
n_shared_experts: int = 1,
|
||||
@@ -182,9 +181,6 @@ class DeepseekV4Config(PretrainedConfig):
|
||||
self.index_n_heads = index_n_heads
|
||||
self.index_head_dim = index_head_dim
|
||||
self.index_topk = index_topk
|
||||
# Exists so tests can run toy shapes the kernel rejects; no shipped config may set it,
|
||||
# and `to_dict` drops it so it never reaches disk.
|
||||
self._attn_impl = _attn_impl
|
||||
|
||||
self.partial_rotary_factor = (
|
||||
partial_rotary_factor
|
||||
@@ -324,18 +320,15 @@ class DeepseekV4Config(PretrainedConfig):
|
||||
self.rope_parameters = rope_parameters_dict
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""Drop the in-memory-only fields 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`
|
||||
(which reads `config.mlp_layer_types[layer_idx]` directly) still works when this
|
||||
config is handed to it, e.g. in HF-parity tests. `_attn_impl` is a test knob: an
|
||||
underscore prefix alone would not keep it out, since the base method strips an
|
||||
explicit list of names.
|
||||
config is handed to it, e.g. in HF-parity tests.
|
||||
"""
|
||||
output = super().to_dict()
|
||||
output.pop("mlp_layer_types", None)
|
||||
output.pop("_attn_impl", None)
|
||||
return output
|
||||
|
||||
def validate_layer_type(self) -> None:
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
"""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. They take plain
|
||||
tensors, so this module imports nothing from `attention.py` and the dependency runs one way only.
|
||||
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
|
||||
from torch import Tensor, nn
|
||||
|
||||
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(
|
||||
@@ -91,3 +97,61 @@ def dense_mask_from_indices(indices: Tensor, n_positions: int, dtype: torch.dtyp
|
||||
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)).view(*hidden_shape).transpose(1, 2)
|
||||
kv = apply_rotary_pos_emb_interleaved(kv, cos, sin)
|
||||
|
||||
compressed = module.compressor(hidden_states, q_residual, packed) 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)
|
||||
|
||||
@@ -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 ALL_CP_STYLES, CPSupport, 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,42 @@ 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",
|
||||
)
|
||||
return CPSupport(ALL_CP_STYLES)
|
||||
|
||||
@classmethod
|
||||
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
@@ -129,169 +106,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",
|
||||
]
|
||||
|
||||
@@ -91,9 +91,6 @@ 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."""
|
||||
@@ -112,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(
|
||||
@@ -215,3 +210,7 @@ def substitute_ring_attn(
|
||||
from prime_rl.trainer.models.qwen3_5.modeling_qwen3_5 import Qwen3_5GatedFlashAttention
|
||||
|
||||
Qwen3_5GatedFlashAttention._compute_attention = _ring_compute_attention
|
||||
|
||||
from prime_rl.trainer.models.gpt_oss.attention import substitute_gpt_oss_ring_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)
|
||||
@@ -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
|
||||
|
||||
@@ -229,6 +231,10 @@ def substitute_ulysses_attn(
|
||||
|
||||
Qwen3_5GatedFlashAttention._compute_attention = _ulysses_compute_attention
|
||||
|
||||
from prime_rl.trainer.models.gpt_oss.attention import substitute_gpt_oss_ulysses_attention
|
||||
|
||||
substitute_gpt_oss_ulysses_attention(process_group)
|
||||
|
||||
|
||||
def substitute_hf_ulysses_attn(process_group: dist.ProcessGroup) -> None:
|
||||
"""Patch HF's `_flash_attention_forward` to use Ulysses all-to-all + local FA2.
|
||||
|
||||
@@ -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,255 @@
|
||||
"""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
|
||||
|
||||
|
||||
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))
|
||||
|
||||
def set_context_parallel_attributes(
|
||||
self,
|
||||
process_group: dist.ProcessGroup,
|
||||
rank: int,
|
||||
world_size: int,
|
||||
) -> None:
|
||||
self.process_group = process_group
|
||||
self.context_parallel_rank = rank
|
||||
self.context_parallel_world_size = world_size
|
||||
|
||||
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 hasattr(self, "process_group"):
|
||||
world_size = self.context_parallel_world_size
|
||||
rank = self.context_parallel_rank
|
||||
gate = sequence_to_head_parallel(gate, self.process_group, world_size)
|
||||
time_step = sequence_to_head_parallel(time_step, self.process_group, world_size)
|
||||
|
||||
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, self.process_group, world_size),
|
||||
sequence_to_head_parallel(state_input, self.process_group, world_size),
|
||||
sequence_to_head_parallel(state_output, self.process_group, world_size),
|
||||
],
|
||||
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 hasattr(self, "process_group"):
|
||||
hidden_states = head_to_sequence_parallel(
|
||||
hidden_states,
|
||||
self.process_group,
|
||||
self.context_parallel_world_size,
|
||||
)
|
||||
return self.out_proj(hidden_states)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"GatedRMSNorm",
|
||||
"NemotronHMamba2",
|
||||
"head_to_sequence_parallel",
|
||||
"sequence_to_head_parallel",
|
||||
]
|
||||
@@ -1,576 +1,268 @@
|
||||
"""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
|
||||
def set_context_parallel_attributes(
|
||||
self,
|
||||
process_group: dist.ProcessGroup,
|
||||
rank: int,
|
||||
world_size: int,
|
||||
) -> None:
|
||||
for module in self.layers.modules():
|
||||
if isinstance(module, NemotronHMamba2):
|
||||
module.set_context_parallel_attributes(process_group, rank, world_size)
|
||||
|
||||
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()
|
||||
self.lm_head = VanillaOutputLinear(config.hidden_size, config.vocab_size)
|
||||
|
||||
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)
|
||||
def set_context_parallel_attributes(
|
||||
self,
|
||||
process_group: dist.ProcessGroup,
|
||||
rank: int,
|
||||
world_size: int,
|
||||
) -> None:
|
||||
self.model.set_context_parallel_attributes(process_group, rank, world_size)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: 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",
|
||||
]
|
||||
|
||||
@@ -28,6 +28,7 @@ from prime_rl.trainer.models.layers.grouped_gemm import (
|
||||
from prime_rl.trainer.models.layers.moe import MoE
|
||||
from prime_rl.trainer.parallel_dims import ParallelDims
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.vlm import get_language_model
|
||||
|
||||
|
||||
def _resolve_grouped_gemm(config: ModelConfig) -> GroupedGemm:
|
||||
@@ -62,11 +63,27 @@ def configure_moe_runtime(model: nn.Module, config: ModelConfig, parallel_dims:
|
||||
raise ValueError("A non-default model.moe runtime was configured, but the model has no custom MoE layers.")
|
||||
return
|
||||
|
||||
grouped_gemm = _resolve_grouped_gemm(config)
|
||||
selected_moes = set(moe_layers)
|
||||
if config.moe.compute.apply_to != "all":
|
||||
language_model = get_language_model(
|
||||
model, override=config.vlm.language_model_attr if config.vlm is not None else None
|
||||
)
|
||||
selected_layers = config.moe.compute.resolve_layers(len(language_model.layers))
|
||||
selected_moes = {
|
||||
module
|
||||
for index, layer in enumerate(language_model.layers.children())
|
||||
if index in selected_layers
|
||||
for module in layer.modules()
|
||||
if isinstance(module, MoE)
|
||||
}
|
||||
get_logger().debug(f"Selected model layers for MoE compute: {sorted(selected_layers)}")
|
||||
bf16_grouped_gemm = BF16GroupedGemm()
|
||||
selected_grouped_gemm = _resolve_grouped_gemm(config) if selected_moes else bf16_grouped_gemm
|
||||
ep_mesh = parallel_dims.get_mesh("ep") if parallel_dims.ep_enabled else None
|
||||
dispatch = config.moe.dispatch
|
||||
|
||||
for moe in moe_layers:
|
||||
grouped_gemm = selected_grouped_gemm if moe in selected_moes else bf16_grouped_gemm
|
||||
if ep_mesh is not None and moe.experts.num_experts % parallel_dims.ep:
|
||||
raise ValueError(
|
||||
f"MoE expert count {moe.experts.num_experts} must be divisible by model.ep={parallel_dims.ep}."
|
||||
@@ -79,7 +96,7 @@ def configure_moe_runtime(model: nn.Module, config: ModelConfig, parallel_dims:
|
||||
token_group_alignment=grouped_gemm.token_group_alignment,
|
||||
)
|
||||
elif isinstance(dispatch, TorchMoEDispatchConfig):
|
||||
if dispatch.transport == "mxfp8":
|
||||
if dispatch.transport == "mxfp8" and isinstance(grouped_gemm, MXFP8GroupedGemm):
|
||||
token_dispatcher = MXFP8TorchTokenDispatcher(
|
||||
num_experts=moe.experts.num_experts,
|
||||
top_k=moe.router.top_k,
|
||||
@@ -111,6 +128,6 @@ def configure_moe_runtime(model: nn.Module, config: ModelConfig, parallel_dims:
|
||||
parallelize_module(moe.experts, device_mesh=ep_mesh, parallelize_plan=ExpertWeightParallel())
|
||||
|
||||
get_logger().info(
|
||||
f"Configured {len(moe_layers)} MoE layers with compute={config.moe.compute.type}, "
|
||||
f"dispatch={config.moe.dispatch.type}, ep={parallel_dims.ep}"
|
||||
f"Configured {len(selected_moes)}/{len(moe_layers)} MoE layers with compute={config.moe.compute.type}, "
|
||||
f"apply_to={config.moe.compute.apply_to}, fallback=bf16, dispatch={config.moe.dispatch.type}, ep={parallel_dims.ep}"
|
||||
)
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
import asyncio
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from prime_rl.configs.shared import ClientConfig
|
||||
from prime_rl.inference.dynamo import (
|
||||
DynamoAdminPlane,
|
||||
DynamoDiscoveryPending,
|
||||
parse_dynamo_worker,
|
||||
topology_fingerprint,
|
||||
)
|
||||
from prime_rl.orchestrator.clients import AdminPlane, setup_admin_plane
|
||||
|
||||
MODEL = "Qwen/Qwen3-0.6B"
|
||||
|
||||
|
||||
def dynamo_config() -> dict:
|
||||
return {"discovery_url": "http://worker:8001"}
|
||||
|
||||
|
||||
def worker(
|
||||
instance_id: int,
|
||||
*,
|
||||
admin_base_url: str | None = None,
|
||||
model: str = MODEL,
|
||||
) -> dict:
|
||||
return {
|
||||
"instance_id": instance_id,
|
||||
"admin_base_url": admin_base_url or f"http://worker:{8200 + instance_id}",
|
||||
"world_size": 1,
|
||||
"model": model,
|
||||
}
|
||||
|
||||
|
||||
def snapshot(*workers: dict) -> dict:
|
||||
return {"protocol_version": 1, "workers": list(workers)}
|
||||
|
||||
|
||||
def parsed(*workers: dict):
|
||||
return parse_dynamo_worker(snapshot(*workers), MODEL, expected_admin_host="worker")
|
||||
|
||||
|
||||
def admin_for(*workers: dict) -> DynamoAdminPlane:
|
||||
config = ClientConfig(
|
||||
base_url="http://worker:8000/v1",
|
||||
skip_model_check=True,
|
||||
wait_for_ready_timeout=2,
|
||||
dynamo=dynamo_config(),
|
||||
)
|
||||
admin = DynamoAdminPlane(config, MODEL, poll_interval=0)
|
||||
admin._fingerprint = topology_fingerprint(parsed(*workers))
|
||||
admin.clients = [AsyncMock() for _ in workers]
|
||||
return admin
|
||||
|
||||
|
||||
def test_parse_dynamo_worker_filters_model_and_checks_admin_host():
|
||||
discovered_worker = parse_dynamo_worker(
|
||||
snapshot(
|
||||
worker(3),
|
||||
worker(1, model="other"),
|
||||
),
|
||||
MODEL,
|
||||
expected_admin_host="worker",
|
||||
)
|
||||
|
||||
assert discovered_worker.admin_base_url == "http://worker:8203"
|
||||
|
||||
with pytest.raises(ValueError, match="does not match discovery host"):
|
||||
parse_dynamo_worker(
|
||||
snapshot(worker(1, admin_base_url="http://other-worker:8201")),
|
||||
MODEL,
|
||||
expected_admin_host="worker",
|
||||
)
|
||||
|
||||
|
||||
def test_parse_dynamo_worker_rejects_multiple_matching_workers():
|
||||
with pytest.raises(ValueError, match="exactly one inference worker"):
|
||||
parse_dynamo_worker(snapshot(worker(1), worker(2)), MODEL, expected_admin_host="worker")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("worker_update", "error", "match"),
|
||||
[
|
||||
({"admin_base_url": None}, DynamoDiscoveryPending, "admin_base_url"),
|
||||
({"world_size": 2}, ValueError, "exactly one inference rank"),
|
||||
],
|
||||
)
|
||||
def test_parse_dynamo_worker_validates_required_singleton_metadata(worker_update, error, match):
|
||||
payload = {**worker(1), **worker_update}
|
||||
with pytest.raises(error, match=match):
|
||||
parse_dynamo_worker(snapshot(payload), MODEL, expected_admin_host="worker")
|
||||
|
||||
|
||||
def test_dynamo_admin_plane_factory_pins_two_identical_snapshots():
|
||||
discovered_worker = parsed(worker(1))
|
||||
discover = AsyncMock(side_effect=[discovered_worker, discovered_worker])
|
||||
admin = setup_admin_plane(
|
||||
ClientConfig(
|
||||
base_url="http://worker:8000/v1",
|
||||
skip_model_check=True,
|
||||
wait_for_ready_timeout=2,
|
||||
dynamo=dynamo_config(),
|
||||
),
|
||||
MODEL,
|
||||
)
|
||||
assert isinstance(admin, DynamoAdminPlane)
|
||||
assert admin._discovery_url == "http://worker:8001"
|
||||
admin._poll_interval = 0
|
||||
|
||||
with (
|
||||
patch.object(admin, "_discover", discover),
|
||||
patch("prime_rl.inference.dynamo.check_health", new=AsyncMock()),
|
||||
patch("prime_rl.inference.dynamo.maybe_check_has_model", new=AsyncMock()),
|
||||
):
|
||||
asyncio.run(admin.wait_for_ready(MODEL))
|
||||
|
||||
assert discover.await_count == 2
|
||||
assert str(admin.clients[0].base_url) == "http://worker:8201"
|
||||
asyncio.run(admin.aclose())
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("api_key", "authorization"), [("secret", "Bearer secret"), ("EMPTY", None)])
|
||||
def test_dynamo_worker_client_propagates_admin_headers(monkeypatch, api_key, authorization):
|
||||
monkeypatch.setenv("DYNAMO_HEADER", "from-env")
|
||||
monkeypatch.setenv("DYNAMO_API_KEY", api_key)
|
||||
config = ClientConfig(
|
||||
base_url="http://worker:8000/v1",
|
||||
headers={"X-Static": "static"},
|
||||
headers_from_env={"X-Environment": "DYNAMO_HEADER"},
|
||||
api_key_var="DYNAMO_API_KEY",
|
||||
dynamo=dynamo_config(),
|
||||
)
|
||||
admin = DynamoAdminPlane(config, MODEL)
|
||||
client = admin._make_worker_client(parsed(worker(1)))
|
||||
|
||||
assert client.headers["X-Static"] == "static"
|
||||
assert client.headers["X-Environment"] == "from-env"
|
||||
assert client.headers.get("Authorization") == authorization
|
||||
|
||||
asyncio.run(client.aclose())
|
||||
asyncio.run(admin.aclose())
|
||||
|
||||
|
||||
def test_dynamo_admin_plane_derives_discovery_url_from_client_port():
|
||||
admin = setup_admin_plane(
|
||||
ClientConfig(
|
||||
base_url="http://worker:8000/v1",
|
||||
dynamo={"enabled": True},
|
||||
),
|
||||
MODEL,
|
||||
)
|
||||
|
||||
assert isinstance(admin, DynamoAdminPlane)
|
||||
assert admin._discovery_url == "http://worker:8001"
|
||||
asyncio.run(admin.aclose())
|
||||
|
||||
|
||||
def test_dynamo_admin_plane_can_be_disabled():
|
||||
admin = setup_admin_plane(
|
||||
ClientConfig(
|
||||
base_url="http://worker:8000/v1",
|
||||
dynamo={"enabled": False},
|
||||
),
|
||||
MODEL,
|
||||
)
|
||||
|
||||
assert type(admin) is AdminPlane
|
||||
asyncio.run(admin.aclose())
|
||||
|
||||
|
||||
def test_dynamo_discovery_url_derivation_requires_an_explicit_port():
|
||||
with pytest.raises(ValueError, match="Set dynamo.discovery_url"):
|
||||
setup_admin_plane(
|
||||
ClientConfig(
|
||||
base_url="http://worker/v1",
|
||||
dynamo={"enabled": True},
|
||||
),
|
||||
MODEL,
|
||||
)
|
||||
|
||||
|
||||
def test_dynamo_admin_plane_rejects_confirmed_topology_drift():
|
||||
admin_url = "http://worker:8200"
|
||||
changed = parsed(worker(2, admin_base_url=admin_url))
|
||||
admin = admin_for(worker(1, admin_base_url=admin_url))
|
||||
|
||||
with (
|
||||
patch.object(admin, "_discover", new=AsyncMock(side_effect=[changed, changed])),
|
||||
pytest.raises(RuntimeError, match="topology changed"),
|
||||
):
|
||||
asyncio.run(admin.ensure_topology_current())
|
||||
|
||||
asyncio.run(admin.aclose())
|
||||
|
||||
|
||||
def test_dynamo_nccl_lifecycle_initializes_and_updates_weights(tmp_path):
|
||||
admin = admin_for(worker(3))
|
||||
|
||||
with (
|
||||
patch.object(admin, "ensure_topology_current", new=AsyncMock()),
|
||||
patch.object(admin, "_collective_rpc", new=AsyncMock()) as collective_rpc,
|
||||
patch("prime_rl.inference.dynamo._admin_post", new=AsyncMock()) as post,
|
||||
):
|
||||
with pytest.raises(ValueError, match="exactly one inference rank"):
|
||||
asyncio.run(admin.initialize_nccl(host="trainer", port=29501, timeout=10, inference_world_size=2))
|
||||
collective_rpc.assert_not_awaited()
|
||||
assert admin._nccl_initialization_state == "uninitialized"
|
||||
|
||||
with pytest.raises(RuntimeError, match="ready NCCL initialization"):
|
||||
asyncio.run(admin.update_weights(tmp_path / "step_1", transport="nccl", step=1))
|
||||
|
||||
asyncio.run(admin.initialize_nccl(host="trainer", port=29501, timeout=10, inference_world_size=1))
|
||||
asyncio.run(admin.update_weights(tmp_path / "step_1", transport="nccl", step=1))
|
||||
|
||||
assert collective_rpc.await_args_list[0].kwargs["args"] == ["trainer", 29501, 0, 1, 10, False, "default"]
|
||||
assert collective_rpc.await_args_list[1].kwargs["args"] == [(tmp_path / "step_1").as_posix()]
|
||||
assert [call.args[1] for call in post.await_args_list] == ["/pause", "/resume"]
|
||||
assert admin._nccl_initialization_state == "ready"
|
||||
asyncio.run(admin.aclose())
|
||||
|
||||
|
||||
def test_dynamo_delegates_non_nccl_weight_updates(tmp_path):
|
||||
admin = admin_for(worker(1))
|
||||
|
||||
with (
|
||||
patch.object(admin, "ensure_topology_current", new=AsyncMock()) as ensure_topology,
|
||||
patch.object(AdminPlane, "update_weights", new=AsyncMock()) as update_weights,
|
||||
):
|
||||
asyncio.run(admin.update_weights(tmp_path, transport="filesystem", step=1))
|
||||
|
||||
ensure_topology.assert_awaited_once_with()
|
||||
update_weights.assert_awaited_once_with(tmp_path, transport="filesystem", step=1, on_paused=None)
|
||||
asyncio.run(admin.aclose())
|
||||
|
||||
|
||||
def test_dynamo_nccl_initialization_failure_is_terminal():
|
||||
admin = admin_for(worker(1))
|
||||
|
||||
with (
|
||||
patch.object(admin, "ensure_topology_current", new=AsyncMock()),
|
||||
patch.object(admin, "_collective_rpc", new=AsyncMock(side_effect=ValueError("unexpected"))),
|
||||
pytest.raises(RuntimeError, match="must restart"),
|
||||
):
|
||||
asyncio.run(admin.initialize_nccl(host="trainer", port=29501, timeout=10, inference_world_size=1))
|
||||
|
||||
assert admin._nccl_initialization_state == "terminal"
|
||||
asyncio.run(admin.aclose())
|
||||
|
||||
|
||||
def test_dynamo_nccl_update_failure_stays_paused_and_terminal(tmp_path):
|
||||
admin = admin_for(worker(1))
|
||||
admin._nccl_initialization_state = "ready"
|
||||
|
||||
with (
|
||||
patch.object(admin, "ensure_topology_current", new=AsyncMock()),
|
||||
patch("prime_rl.inference.dynamo._admin_post", new=AsyncMock()) as post,
|
||||
patch.object(admin, "_collective_rpc", new=AsyncMock(side_effect=RuntimeError("failed"))),
|
||||
pytest.raises(RuntimeError, match="engines remain paused"),
|
||||
):
|
||||
asyncio.run(admin.update_weights(tmp_path / "step_1", transport="nccl", step=1))
|
||||
|
||||
assert [call.args[1] for call in post.await_args_list] == ["/pause"]
|
||||
assert admin._nccl_initialization_state == "terminal"
|
||||
asyncio.run(admin.aclose())
|
||||
@@ -189,7 +189,46 @@ def test_moe_runtime_defaults_are_independent_from_dense_quantization():
|
||||
],
|
||||
)
|
||||
def test_supported_moe_runtime_configs(model):
|
||||
TrainerModelConfig.model_validate(model)
|
||||
config = TrainerModelConfig.model_validate(model)
|
||||
assert config.moe.compute.resolve_layers(43) == set(range(43))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("backend", ["bf16", "deepgemm_fp8", "mxfp8"])
|
||||
@pytest.mark.parametrize(
|
||||
("selection", "num_layers", "selected"),
|
||||
[
|
||||
("all", 10, set(range(10))),
|
||||
("85%", 48, set(range(40))),
|
||||
("100%", 3, {0, 1, 2}),
|
||||
("0%", 3, set()),
|
||||
("33.3%", 10, {0, 1, 2}),
|
||||
([], 10, set()),
|
||||
([2, 0], 10, {0, 2}),
|
||||
([0, 2, 2], 3, {0, 2}),
|
||||
],
|
||||
)
|
||||
def test_moe_compute_apply_to(backend, selection, num_layers, selected):
|
||||
config = TrainerModelConfig.model_validate({"moe": {"compute": {"type": backend, "apply_to": selection}}})
|
||||
config = TrainerModelConfig.model_validate_json(config.model_dump_json())
|
||||
assert config.moe.compute.resolve_layers(num_layers) == selected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("selection", ["*", "model.layers.*", "", "101%", "-1%", "nan%", [-1], [1.5], [True]])
|
||||
def test_moe_compute_rejects_invalid_apply_to(selection):
|
||||
with pytest.raises(ValidationError, match="apply_to"):
|
||||
TrainerModelConfig.model_validate({"moe": {"compute": {"type": "mxfp8", "apply_to": selection}}})
|
||||
|
||||
|
||||
def test_moe_compute_rejects_out_of_range_layer():
|
||||
config = TrainerModelConfig.model_validate({"moe": {"compute": {"type": "mxfp8", "apply_to": [3]}}})
|
||||
with pytest.raises(ValueError, match="out of range"):
|
||||
config.moe.compute.resolve_layers(3)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("selection", "selected"), [("all", {0, 1, 2}), ("50%", {0}), ("[0, 2]", {0, 2})])
|
||||
def test_moe_compute_apply_to_cli(selection, selected):
|
||||
config = cli(TrainerModelConfig, args=["--moe.compute.type", "mxfp8", "--moe.compute.apply-to", selection])
|
||||
assert config.moe.compute.resolve_layers(3) == selected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
|
||||
@@ -1,85 +1,50 @@
|
||||
import sys
|
||||
import types
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from prime_rl.trainer.models.layers import cp_mamba
|
||||
from prime_rl.trainer.models.nemotron_h import NemotronHConfig
|
||||
from prime_rl.trainer.models.nemotron_h.mamba import NemotronHMamba2
|
||||
|
||||
pytestmark = [pytest.mark.gpu]
|
||||
|
||||
|
||||
class _FakeMixer(torch.nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.intermediate_size = 1
|
||||
self.conv_dim = 3
|
||||
self.num_heads = 1
|
||||
self.n_groups = 1
|
||||
self.ssm_state_size = 1
|
||||
self.head_dim = 1
|
||||
self.chunk_size = 1
|
||||
self.time_step_limit = None
|
||||
self.variance_epsilon = 1e-5
|
||||
self.activation = "silu"
|
||||
|
||||
self.in_proj = torch.nn.Linear(1, 5, bias=False)
|
||||
self.in_proj.weight.data.copy_(torch.tensor([[1.0], [1.0], [1.0], [1.0], [1.0]]))
|
||||
self.A_log = torch.nn.Parameter(torch.zeros(1))
|
||||
self.D = torch.nn.Parameter(torch.ones(1))
|
||||
self.dt_bias = torch.nn.Parameter(torch.zeros(1))
|
||||
self.conv1d = torch.nn.Conv1d(3, 3, kernel_size=2, groups=3, bias=False)
|
||||
self.conv1d.weight.data.fill_(1.0)
|
||||
self.norm = types.SimpleNamespace(
|
||||
weight=torch.ones(1, device="cuda"), variance_epsilon=self.variance_epsilon, group_size=1
|
||||
)
|
||||
self.out_proj = torch.nn.Identity()
|
||||
@pytest.fixture
|
||||
def mamba():
|
||||
torch.manual_seed(0)
|
||||
config = NemotronHConfig(
|
||||
hidden_size=256,
|
||||
hybrid_override_pattern="M",
|
||||
mamba_num_heads=8,
|
||||
mamba_head_dim=64,
|
||||
n_groups=2,
|
||||
ssm_state_size=64,
|
||||
conv_kernel=4,
|
||||
chunk_size=64,
|
||||
)
|
||||
return NemotronHMamba2(config).cuda().to(torch.bfloat16)
|
||||
|
||||
|
||||
def _install_fake_scan(monkeypatch, seen_seq_idx: list[torch.Tensor]) -> None:
|
||||
def fake_scan(hidden_states, time_step, A, B, C, **kwargs):
|
||||
assert kwargs["return_final_states"] is False
|
||||
seen_seq_idx.append(kwargs["seq_idx"].clone())
|
||||
return hidden_states
|
||||
def test_mamba_resets_conv_and_scan_at_packed_boundaries(mamba):
|
||||
cu_seqlens = torch.tensor([0, 3, 8], dtype=torch.int32, device="cuda")
|
||||
first = torch.randn(1, 8, 256, device="cuda", dtype=torch.bfloat16, requires_grad=True)
|
||||
second = first.detach().clone()
|
||||
second[:, :3] *= 20
|
||||
|
||||
ssd_combined = types.ModuleType("mamba_ssm.ops.triton.ssd_combined")
|
||||
ssd_combined.mamba_chunk_scan_combined = fake_scan
|
||||
monkeypatch.setitem(sys.modules, "mamba_ssm", types.ModuleType("mamba_ssm"))
|
||||
monkeypatch.setitem(sys.modules, "mamba_ssm.ops", types.ModuleType("mamba_ssm.ops"))
|
||||
monkeypatch.setitem(sys.modules, "mamba_ssm.ops.triton", types.ModuleType("mamba_ssm.ops.triton"))
|
||||
monkeypatch.setitem(sys.modules, "mamba_ssm.ops.triton.ssd_combined", ssd_combined)
|
||||
first_output = mamba(first, cu_seqlens)
|
||||
second_output = mamba(second, cu_seqlens)
|
||||
torch.testing.assert_close(first_output[:, 3:], second_output[:, 3:])
|
||||
first_output[:, 3:].float().square().sum().backward()
|
||||
assert torch.count_nonzero(first.grad[:, :3]) == 0
|
||||
|
||||
|
||||
def test_mamba_cp_forward_resets_conv_and_scan_at_packed_boundaries(monkeypatch):
|
||||
"""Changing document A must not change document B under Ulysses CP."""
|
||||
seen_seq_idx: list[torch.Tensor] = []
|
||||
_install_fake_scan(monkeypatch, seen_seq_idx)
|
||||
monkeypatch.setattr(cp_mamba, "seq_to_head_parallel", lambda value, *_: value)
|
||||
monkeypatch.setattr(cp_mamba, "head_to_seq_parallel", lambda value, *_: value)
|
||||
|
||||
mixer = _FakeMixer().cuda()
|
||||
cu_seqlens = torch.tensor([0, 2, 4], dtype=torch.int32, device="cuda")
|
||||
first = torch.tensor([[[1.0], [2.0], [3.0], [4.0]]], device="cuda")
|
||||
second = first.clone()
|
||||
second[0, 1, 0] = 200.0
|
||||
|
||||
first_out = cp_mamba.mamba_cp_forward(mixer, first, None, 0, 1, cu_seqlens)
|
||||
second_out = cp_mamba.mamba_cp_forward(mixer, second, None, 0, 1, cu_seqlens)
|
||||
|
||||
assert torch.equal(seen_seq_idx[0], torch.tensor([[0, 0, 1, 1]], dtype=torch.int32, device="cuda"))
|
||||
assert torch.equal(seen_seq_idx[1], seen_seq_idx[0])
|
||||
torch.testing.assert_close(first_out[:, 2:], second_out[:, 2:])
|
||||
|
||||
|
||||
def test_mamba_cp_forward_builds_seq_idx_for_uneven_packs(monkeypatch):
|
||||
seen_seq_idx: list[torch.Tensor] = []
|
||||
_install_fake_scan(monkeypatch, seen_seq_idx)
|
||||
monkeypatch.setattr(cp_mamba, "seq_to_head_parallel", lambda value, *_: value)
|
||||
monkeypatch.setattr(cp_mamba, "head_to_seq_parallel", lambda value, *_: value)
|
||||
|
||||
def test_mamba_builds_sequence_ids_for_uneven_packs(mamba):
|
||||
cu_seqlens = torch.tensor([0, 1, 4, 6], dtype=torch.int32, device="cuda")
|
||||
hidden_states = torch.arange(6, dtype=torch.float32, device="cuda").reshape(1, 6, 1)
|
||||
|
||||
cp_mamba.mamba_cp_forward(_FakeMixer().cuda(), hidden_states, None, 0, 1, cu_seqlens)
|
||||
|
||||
assert torch.equal(seen_seq_idx[0], torch.tensor([[0, 1, 1, 1, 2, 2]], dtype=torch.int32, device="cuda"))
|
||||
hidden_states = torch.randn(1, 6, 256, device="cuda", dtype=torch.bfloat16)
|
||||
packed = mamba(hidden_states, cu_seqlens)
|
||||
separate = torch.cat(
|
||||
[
|
||||
mamba(hidden_states[:, start:end], torch.tensor([0, end - start], dtype=torch.int32, device="cuda"))
|
||||
for start, end in [(0, 1), (1, 4), (4, 6)]
|
||||
],
|
||||
dim=1,
|
||||
)
|
||||
torch.testing.assert_close(packed, separate, rtol=1e-2, atol=1e-2)
|
||||
|
||||
@@ -8,7 +8,7 @@ from torch import nn
|
||||
|
||||
from prime_rl.configs.trainer import ModelConfig
|
||||
from prime_rl.trainer.model import load_dcp_from_hf
|
||||
from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config, DeepseekV4ForCausalLM
|
||||
from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config, DeepseekV4ForCausalLM, eager_reference
|
||||
from prime_rl.trainer.models.deepseek_v4 import attention as dsv4_attention
|
||||
from prime_rl.trainer.models.deepseek_v4.attention import DeepseekV4Attention, PackedContext
|
||||
from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding
|
||||
@@ -16,7 +16,20 @@ from prime_rl.trainer.models.layers import norms
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
from prime_rl.utils.utils import default_dtype
|
||||
|
||||
pytestmark = [pytest.mark.gpu]
|
||||
# Every layer is built through `DeepseekV4Attention.__init__`, which refuses to construct without
|
||||
# the kernel it would dispatch to, so the whole file needs tilelang even though nothing here calls it.
|
||||
pytestmark = [
|
||||
pytest.mark.gpu,
|
||||
pytest.mark.skipif(
|
||||
dsv4_attention.dsv4_sparse_attn is None,
|
||||
reason="the fused sparse attention kernel did not import; tilelang ships in the `gpu` extra, on linux only",
|
||||
),
|
||||
]
|
||||
|
||||
requires_fp8_indexer = pytest.mark.skipif(
|
||||
not torch.cuda.is_available() or torch.cuda.get_device_capability()[0] < 9,
|
||||
reason="the indexer kernel quantizes to Triton fp8e4nv (e4m3), only supported on Hopper (SM90) and newer",
|
||||
)
|
||||
|
||||
# Deliberately heterogeneous: one layer of every attention type, hash-routed bootstrap
|
||||
# layers ahead of standard MoE ones, and a sliding window narrow enough that the compressed
|
||||
@@ -26,7 +39,9 @@ MODEL = dict(
|
||||
hidden_size=128,
|
||||
moe_intermediate_size=64,
|
||||
num_hidden_layers=5,
|
||||
num_attention_heads=4,
|
||||
# The smallest head count `DeepseekV4Attention.__init__` accepts: the kernel's tiler pads the
|
||||
# head axis to a power of two and its backward GEMM needs 32 rows.
|
||||
num_attention_heads=32,
|
||||
num_key_value_heads=1,
|
||||
head_dim=32,
|
||||
q_lora_rank=64,
|
||||
@@ -45,8 +60,10 @@ MODEL = dict(
|
||||
"sliding_attention",
|
||||
],
|
||||
compress_rates={"compressed_sparse_attention": 4, "heavily_compressed_attention": 8},
|
||||
index_n_heads=4,
|
||||
index_head_dim=24,
|
||||
# The real V4-Flash Lightning Indexer shapes. `fp8_indexer` is the only indexer path and it
|
||||
# does `tl.arange(0, index_head_dim)`, so the dimension has to be a power of two.
|
||||
index_n_heads=64,
|
||||
index_head_dim=128,
|
||||
# Smaller than the number of compressed entries the sequence yields, so the Lightning
|
||||
# Indexer's selection has to actually discard some of them.
|
||||
index_topk=2,
|
||||
@@ -63,8 +80,13 @@ MODEL = dict(
|
||||
rms_norm_eps=1e-6,
|
||||
)
|
||||
|
||||
MODEL_BATCH, MODEL_SEQ = 2, 32
|
||||
MODULE_BATCH = 2
|
||||
# Shared: model construction only writes transformers' private `_attn_implementation_internal`
|
||||
# and `_experts_implementation_internal`, idempotently, so deep-copy before any other mutation.
|
||||
MODEL_CONFIG = DeepseekV4Config(**MODEL)
|
||||
|
||||
# The Lightning Indexer scores one packed row, which makes every batch axis here 1.
|
||||
BATCH = 1
|
||||
MODEL_SEQ = 32
|
||||
|
||||
SLIDING_LAYER, CSA_LAYER, HCA_LAYER = 0, 1, 2
|
||||
COMPRESS_RATE = MODEL["compress_rates"]["compressed_sparse_attention"]
|
||||
@@ -125,29 +147,26 @@ def _randomize(module: nn.Module) -> None:
|
||||
buffer.copy_(_tid2eid(buffer.shape[0], router.num_experts, router.top_k))
|
||||
|
||||
|
||||
def _prime_config(attn_impl: str = "eager") -> DeepseekV4Config:
|
||||
"""The toy config. It defaults to eager because the kernel cannot tile 4 attention heads."""
|
||||
return DeepseekV4Config(**MODEL, _attn_impl=attn_impl)
|
||||
|
||||
|
||||
def get_prime_model(dtype: torch.dtype = torch.bfloat16, attn_impl: str = "eager") -> nn.Module:
|
||||
def get_prime_model(dtype: torch.dtype = torch.bfloat16) -> nn.Module:
|
||||
"""A prime-rl model with non-degenerate weights and the LM head training code wraps it in."""
|
||||
with torch.device("cuda"), default_dtype(dtype):
|
||||
model = DeepseekV4ForCausalLM._from_config(_prime_config(attn_impl))
|
||||
model = DeepseekV4ForCausalLM._from_config(MODEL_CONFIG)
|
||||
_randomize(model)
|
||||
eager_reference.use_eager_attention(model)
|
||||
inject_prime_lm_head(model, chunk_size=None)
|
||||
return model
|
||||
|
||||
|
||||
def prime_attention(layer_idx: int, dtype: torch.dtype = torch.bfloat16, attn_impl: str = "eager") -> nn.Module:
|
||||
def prime_attention(layer_idx: int, dtype: torch.dtype = torch.bfloat16) -> nn.Module:
|
||||
"""One attention layer of the same config the whole-model tests use.
|
||||
|
||||
`DeepseekV4Attention` reads no MoE or hyper-connection field, so the layer this builds is
|
||||
bit-identical to one from a config carrying only the attention keys.
|
||||
"""
|
||||
with torch.device("cuda"), default_dtype(dtype):
|
||||
module = DeepseekV4Attention(_prime_config(attn_impl), layer_idx=layer_idx)
|
||||
module = DeepseekV4Attention(MODEL_CONFIG, layer_idx=layer_idx)
|
||||
_randomize(module)
|
||||
eager_reference.use_eager_attention(module)
|
||||
return module
|
||||
|
||||
|
||||
@@ -174,7 +193,7 @@ def _packed_context(doc_lens: tuple[int, ...], dtype: torch.dtype) -> PackedCont
|
||||
be the one the caller runs at.
|
||||
"""
|
||||
with torch.device("cuda"), default_dtype(dtype):
|
||||
rotary = DeepseekV4RotaryEmbedding(_prime_config())
|
||||
rotary = DeepseekV4RotaryEmbedding(MODEL_CONFIG)
|
||||
return PackedContext.build(
|
||||
rotary_emb=rotary,
|
||||
seq_lens=torch.tensor(doc_lens, device="cuda"),
|
||||
@@ -183,6 +202,7 @@ def _packed_context(doc_lens: tuple[int, ...], dtype: torch.dtype) -> PackedCont
|
||||
)
|
||||
|
||||
|
||||
@requires_fp8_indexer
|
||||
def test_deepseek_v4_hash_layers_route_on_token_ids():
|
||||
"""The bootstrap layers read `input_ids`, so identical hidden states still route apart."""
|
||||
prime_model = get_prime_model()
|
||||
@@ -191,7 +211,7 @@ def test_deepseek_v4_hash_layers_route_on_token_ids():
|
||||
|
||||
counts = []
|
||||
for token_id in (0, 1):
|
||||
input_ids = torch.full((MODEL_BATCH, MODEL_SEQ), token_id, device="cuda", dtype=torch.long)
|
||||
input_ids = torch.full((BATCH, MODEL_SEQ), token_id, device="cuda", dtype=torch.long)
|
||||
for layer in hash_layers:
|
||||
layer.mlp.tokens_per_expert.zero_()
|
||||
position_ids, seq_lens = _single_doc(input_ids)
|
||||
@@ -202,19 +222,20 @@ def test_deepseek_v4_hash_layers_route_on_token_ids():
|
||||
assert set(table[0].tolist()) != set(table[1].tolist()), "the two table rows must differ for this to bite"
|
||||
assert not torch.equal(counts[0], counts[1]), "a hash layer must route the two token ids to different experts"
|
||||
expected = torch.zeros_like(counts[0][0])
|
||||
expected[table[0]] = MODEL_BATCH * MODEL_SEQ
|
||||
expected[table[0]] = BATCH * MODEL_SEQ
|
||||
torch.testing.assert_close(counts[0][0], expected)
|
||||
|
||||
|
||||
@requires_fp8_indexer
|
||||
def test_deepseek_v4_backward():
|
||||
"""Every parameter that can train does, and the Lightning Indexer's still cannot."""
|
||||
prime_config = _prime_config()
|
||||
with torch.device("cuda"), default_dtype(torch.bfloat16):
|
||||
model = DeepseekV4ForCausalLM(prime_config)
|
||||
model = DeepseekV4ForCausalLM(MODEL_CONFIG)
|
||||
_randomize(model)
|
||||
eager_reference.use_eager_attention(model)
|
||||
inject_prime_lm_head(model)
|
||||
|
||||
input_ids = torch.randint(0, MODEL["vocab_size"], (MODEL_BATCH, MODEL_SEQ), device="cuda")
|
||||
input_ids = torch.randint(0, MODEL["vocab_size"], (BATCH, MODEL_SEQ), device="cuda")
|
||||
position_ids, seq_lens = _single_doc(input_ids)
|
||||
output = model(input_ids, position_ids=position_ids, seq_lens=seq_lens)
|
||||
output["logits"].sum().backward()
|
||||
@@ -238,8 +259,7 @@ def test_deepseek_v4_backward():
|
||||
|
||||
|
||||
def test_deepseek_v4_weight_conversion_roundtrip():
|
||||
prime_config = _prime_config()
|
||||
model = DeepseekV4ForCausalLM(prime_config).to("cuda")
|
||||
model = DeepseekV4ForCausalLM(MODEL_CONFIG).to("cuda")
|
||||
original = {name: tensor.clone() for name, tensor in model.state_dict().items()}
|
||||
|
||||
state_dict = model.state_dict()
|
||||
@@ -284,8 +304,7 @@ def test_deepseek_v4_hash_table_survives_the_load_path(tmp_path, monkeypatch):
|
||||
so getting it to reset one buffer too many is an easy mistake with no symptom other than every
|
||||
bootstrap token routing to expert 0.
|
||||
"""
|
||||
prime_config = _prime_config()
|
||||
model = DeepseekV4ForCausalLM(prime_config).to("cuda")
|
||||
model = DeepseekV4ForCausalLM(MODEL_CONFIG).to("cuda")
|
||||
tables = _fill_hash_tables(model)
|
||||
|
||||
state_dict = model.convert_to_hf(dict(model.state_dict()))
|
||||
@@ -297,15 +316,13 @@ def test_deepseek_v4_hash_table_survives_the_load_path(tmp_path, monkeypatch):
|
||||
assert torch.equal(state_dict[f"layers.{layer_idx}.ffn.gate.tid2eid"], table)
|
||||
|
||||
model.convert_to_prime(state_dict)
|
||||
reloaded = DeepseekV4ForCausalLM(prime_config).to("cuda")
|
||||
reloaded = DeepseekV4ForCausalLM(MODEL_CONFIG).to("cuda")
|
||||
reloaded.load_state_dict(state_dict)
|
||||
for layer_idx, table in tables.items():
|
||||
assert torch.equal(reloaded.model.layers[layer_idx].mlp.router.tid2eid, table)
|
||||
|
||||
# And now the loading path itself, on a meta-device model, with the name `load_dcp_from_hf`
|
||||
# asks the checkpoint for raising a `KeyError` in the stub below if the buffer ever moves.
|
||||
with torch.device("meta"):
|
||||
meta_model = DeepseekV4ForCausalLM(prime_config)
|
||||
meta_model = DeepseekV4ForCausalLM(MODEL_CONFIG)
|
||||
expected = tables[0]
|
||||
|
||||
def fake_dcp_load(state_dict, storage_reader=None):
|
||||
@@ -391,7 +408,7 @@ def test_deepseek_v4_on_disk_keys_map_to_the_names_vllm_expects():
|
||||
from vllm.models.deepseek_v4.nvidia.model import _make_deepseek_v4_weights_mapper
|
||||
|
||||
with torch.device("meta"):
|
||||
model = DeepseekV4ForCausalLM._from_config(_prime_config())
|
||||
model = DeepseekV4ForCausalLM._from_config(MODEL_CONFIG)
|
||||
on_disk_state_dict = model.convert_to_hf(dict(model.state_dict()))
|
||||
assert on_disk_state_dict, "vacuous probe: the model produced no weights to map"
|
||||
|
||||
@@ -407,14 +424,13 @@ def test_deepseek_v4_on_disk_keys_map_to_the_names_vllm_expects():
|
||||
|
||||
def test_deepseek_v4_init_buffers_post_meta_restores_every_rotary():
|
||||
"""Rotary tables are non-persistent and computed eagerly, so meta loading loses them."""
|
||||
prime_config = _prime_config()
|
||||
with torch.device("meta"):
|
||||
model = DeepseekV4ForCausalLM(prime_config)
|
||||
model = DeepseekV4ForCausalLM(MODEL_CONFIG)
|
||||
model.to_empty(device="cuda")
|
||||
|
||||
model.init_buffers_post_meta()
|
||||
|
||||
reference = 1.0 / (prime_config.rope_theta ** (torch.arange(0, 16, 2, device="cuda", dtype=torch.float) / 16))
|
||||
reference = 1.0 / (MODEL_CONFIG.rope_theta ** (torch.arange(0, 16, 2, device="cuda", dtype=torch.float) / 16))
|
||||
torch.testing.assert_close(model.model.rotary_emb.main_inv_freq, reference)
|
||||
compressors = [layer.self_attn.compressor for layer in model.model.layers if layer.self_attn.compressor]
|
||||
assert compressors, "config must contain a compressed attention layer"
|
||||
@@ -636,7 +652,7 @@ def _entry_counts(doc_lens: tuple[int, ...], compress_rate: int) -> list[int]:
|
||||
def _fp32_hidden_states(seq_len: int) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Two leaves carrying identical values, one for the packed run and one for the lone runs."""
|
||||
with torch.device("cuda"):
|
||||
hidden = torch.randn(MODULE_BATCH, seq_len, MODEL["hidden_size"])
|
||||
hidden = torch.randn(BATCH, seq_len, MODEL["hidden_size"])
|
||||
return hidden.clone().requires_grad_(True), hidden.clone().requires_grad_(True)
|
||||
|
||||
|
||||
@@ -663,6 +679,7 @@ def _compare_accumulated_grads(
|
||||
_assert_relative(param.grad, expected[name], rtol, name)
|
||||
|
||||
|
||||
@requires_fp8_indexer
|
||||
def test_packed_sliding_window_mask_respects_documents(_torch_rms_norm, monkeypatch): # noqa: F811
|
||||
"""The local window stops at document boundaries, on every layer.
|
||||
|
||||
@@ -671,19 +688,19 @@ def test_packed_sliding_window_mask_respects_documents(_torch_rms_norm, monkeypa
|
||||
`sliding_window` packed positions whatever document they belong to, which at the production
|
||||
`sliding_window = 128` against 77-token rollouts spans roughly two neighbours on all 43 layers.
|
||||
|
||||
Captured from the mask the model actually applies rather than by calling the builder, so it
|
||||
keeps holding if the masking ever moves.
|
||||
Captured from the dense mask the reference consumer applies to production's own
|
||||
`window_indices`, rather than by calling the builder, so it keeps holding if the masking moves.
|
||||
"""
|
||||
recorded = []
|
||||
real_attention = dsv4_attention.eager_attention_with_sinks
|
||||
real_attention = eager_reference.eager_attention_with_sinks
|
||||
|
||||
def record(query, key, value, sinks, attention_mask, **kwargs):
|
||||
recorded.append(attention_mask)
|
||||
return real_attention(query, key, value, sinks, attention_mask, **kwargs)
|
||||
|
||||
monkeypatch.setattr(dsv4_attention, "eager_attention_with_sinks", record)
|
||||
monkeypatch.setattr(eager_reference, "eager_attention_with_sinks", record)
|
||||
|
||||
# The dense mask is an eager-path artifact; the count below is one call per layer.
|
||||
# The dense mask is a reference-path artifact; the count below is one call per layer.
|
||||
prime_model = get_prime_model(torch.float32)
|
||||
input_ids, position_ids, seq_lens = _packed_inputs(DOC_LENS)
|
||||
prime_model(input_ids, position_ids=position_ids, seq_lens=seq_lens)
|
||||
@@ -701,6 +718,7 @@ def test_packed_sliding_window_mask_respects_documents(_torch_rms_norm, monkeypa
|
||||
assert torch.equal(local, expected), f"layer {layer_idx}: the local window crosses a document boundary"
|
||||
|
||||
|
||||
@requires_fp8_indexer
|
||||
def test_model_packed_matches_unpacked(_torch_rms_norm): # noqa: F811
|
||||
"""The invariant that makes the trainer agree with vLLM, which serves each rollout alone.
|
||||
|
||||
@@ -804,7 +822,7 @@ def test_compressor_packed_matches_per_document(layer_idx, compress_rate, expect
|
||||
packed_input, alone_input = _fp32_hidden_states(sum(doc_lens))
|
||||
|
||||
packed_entries = compressor.compress(packed_input, packed)
|
||||
assert packed_entries.shape == (MODULE_BATCH, sum(counts), compressor.head_dim)
|
||||
assert packed_entries.shape == (BATCH, sum(counts), compressor.head_dim)
|
||||
|
||||
with torch.device("cuda"):
|
||||
weight = torch.randn_like(packed_entries)
|
||||
@@ -817,9 +835,7 @@ def test_compressor_packed_matches_per_document(layer_idx, compress_rate, expect
|
||||
alone = compressor.compress(
|
||||
alone_input[:, _doc_slice(doc_lens, index)], _packed_context((doc_lens[index],), torch.float32)
|
||||
)
|
||||
assert alone.shape == (MODULE_BATCH, count, compressor.head_dim), (
|
||||
f"document {index} compressed to the wrong count"
|
||||
)
|
||||
assert alone.shape == (BATCH, count, compressor.head_dim), f"document {index} compressed to the wrong count"
|
||||
torch.testing.assert_close(
|
||||
packed_entries[:, entries],
|
||||
alone,
|
||||
@@ -836,7 +852,7 @@ def test_compressor_packed_matches_per_document(layer_idx, compress_rate, expect
|
||||
@pytest.mark.parametrize(
|
||||
("layer_idx", "doc_lens"),
|
||||
[
|
||||
(CSA_LAYER, MID_WINDOW_DOCS),
|
||||
pytest.param(CSA_LAYER, MID_WINDOW_DOCS, marks=requires_fp8_indexer),
|
||||
(HCA_LAYER, EXACT_MULTIPLE_DOCS),
|
||||
(SLIDING_LAYER, MID_WINDOW_DOCS),
|
||||
],
|
||||
|
||||
@@ -31,6 +31,14 @@ requires_sparse_attn_kernel = pytest.mark.skipif(
|
||||
reason="the fused sparse attention kernel did not import; tilelang ships in the `gpu` extra, on linux only",
|
||||
)
|
||||
|
||||
# The kernels' shared tiles fit only the datacenter Hopper and Blackwell SMs. The opt-in limit does
|
||||
# not follow capability order, so this enumerates rather than compares: sm120 allows well under half
|
||||
# of what sm90 does.
|
||||
requires_datacenter_gpu = pytest.mark.skipif(
|
||||
not torch.cuda.is_available() or torch.cuda.get_device_capability()[0] not in (9, 10),
|
||||
reason="the fused sparse attention kernels need the shared memory of a datacenter Hopper or Blackwell GPU",
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _seed_rng():
|
||||
@@ -115,21 +123,9 @@ def _compare_accumulated_grads(
|
||||
_assert_relative(param.grad, expected[name], rtol, name)
|
||||
|
||||
|
||||
def _set_attn_impl(module: nn.Module, impl: str) -> None:
|
||||
"""Pin the CSA attention implementation on every attention layer `module` owns.
|
||||
|
||||
`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.attn_impl = impl
|
||||
|
||||
|
||||
# The real DeepSeek V4-Flash attention shapes, written out as a literal so nothing here depends on a local HF
|
||||
# cache. This file runs these shapes and no others: the kernel does not tile smaller ones, and the
|
||||
# sparse path it serves only exists at this size. The MoE fields are shrunk to nothing, since
|
||||
# `DeepseekV4Attention` reads none of them.
|
||||
# cache. This file runs these shapes and no others: the sparse path the kernel serves only exists at
|
||||
# this size. The MoE fields are shrunk to nothing, since `DeepseekV4Attention` reads none of them.
|
||||
V4FLASH_MODEL = dict(
|
||||
vocab_size=64,
|
||||
hidden_size=4096,
|
||||
@@ -172,52 +168,42 @@ V4FLASH_MODEL = dict(
|
||||
},
|
||||
)
|
||||
|
||||
# The hand-built tensors of the first section describe the same CSA layer `V4FLASH_MODEL` does, so
|
||||
# they are read off it rather than written out again: 64 heads over 512 channels, each query
|
||||
# gathering `sliding_window + index_topk = 128 + 512` slots from a single KV group, in bfloat16.
|
||||
# Shared by every test here: `DeepseekV4Attention` and `PackedContext.build` only read it.
|
||||
V4FLASH_CONFIG = DeepseekV4Config(**V4FLASH_MODEL)
|
||||
|
||||
# Read off `V4FLASH_MODEL` so the hand-built tensors below describe the same CSA layer it does.
|
||||
HEADS = V4FLASH_MODEL["num_attention_heads"]
|
||||
DIM = V4FLASH_MODEL["head_dim"]
|
||||
KV_GROUP = V4FLASH_MODEL["num_key_value_heads"]
|
||||
TOPK = V4FLASH_MODEL["sliding_window"] + V4FLASH_MODEL["index_topk"]
|
||||
SM_SCALE = DIM**-0.5
|
||||
|
||||
# Three shapes. The first is aligned to both of the backward's tile sizes and the second to
|
||||
# neither: `preprocess` tiles the query axis at 32 and `postprocess` tiles the KV axis at 64, so a
|
||||
# remainder tile in either is a distinct code path. `200 % 32 = 8` and `1000 % 64 = 40`. The third
|
||||
# carries a batch, which nothing else here does: `Q` and `Indices` are indexed by batch and the
|
||||
# `dKV[by, Indices[by, ...]]` atomics scatter per batch entry, so a batch stride dropped anywhere
|
||||
# in that chain is invisible at batch 1. Sequence lengths stay modest because the float32 oracle
|
||||
# materializes a `(batch, seq_len, topk, head_dim)` gather, roughly 640 KB per token even before
|
||||
# its backward.
|
||||
# The first is aligned to both of the backward's tile sizes (32 in `preprocess`, 64 in
|
||||
# `postprocess`), the second to neither, and the third carries a batch, which nothing else here
|
||||
# does. Sequence lengths stay modest because the float32 oracle materializes the whole gather.
|
||||
SHAPES = [(1, 256, 1024), (1, 200, 1000), (3, 128, 768)]
|
||||
SHAPE_IDS = ["aligned", "misaligned", "batched"]
|
||||
|
||||
# A quarter of the gather slots are masked, which is what a real query with a short window or a
|
||||
# saturated top-k looks like: the masked slots still cost a GEMM column.
|
||||
# What a real query with a short window or a saturated top-k looks like; a masked slot still
|
||||
# costs a GEMM column.
|
||||
MASKED_FRACTION = 0.25
|
||||
|
||||
# Bounds on the largest absolute deviation against each tensor's own scale, not element-wise:
|
||||
# every entry is a sum over hundreds of terms, so the near-zero entries are the ones whose
|
||||
# summands cancelled, and an element-wise relative bound would read out that cancellation noise.
|
||||
# The kernel returns bfloat16, so its output cannot agree with a float32 oracle any more closely
|
||||
# than bfloat16 rounding allows: one ulp at full scale is 2**-8 = 3.9e-3.
|
||||
# Bounds on the largest deviation against each tensor's own scale, not element-wise: every entry
|
||||
# sums hundreds of terms, so an element-wise bound would read out the near-zero entries'
|
||||
# cancellation noise. The kernel returns bfloat16, one ulp of which is 2**-8 at full scale.
|
||||
OUT_RTOL = 1e-2
|
||||
# The LSE is float32 throughout on both sides.
|
||||
LSE_RTOL = 5e-7
|
||||
DQ_RTOL = 1e-2
|
||||
# The vendored kernel this one forked from rounds `P` and `dP` to bfloat16 before the `dKV` GEMMs
|
||||
# while the float32 oracle keeps them in float32. The rest is the bfloat16 `kv` the two sides
|
||||
# share. Neither effect needs a looser bound than the other gradients get: what used to need one
|
||||
# was the oracle's own bfloat16 leaf, see `_float32_leaves`.
|
||||
# while the oracle keeps them in float32, on top of the bfloat16 `kv` both sides share.
|
||||
DKV_RTOL = 1e-2
|
||||
# The sink gradient is a full reduction over every query in the row, so it cancels harder than
|
||||
# anything else here.
|
||||
DSINK_RTOL = 1e-2
|
||||
|
||||
# Compiled against eager. The forward and the log-sum-exp are bit-identical, but `dKV` is not
|
||||
# comparable that way on either side: the backward scatters it with `atomic_addx4`, so its
|
||||
# summation order is whatever the scheduler picks and the same eager call against itself moves by
|
||||
# the same amount.
|
||||
# Compiled against eager, where the forward and the log-sum-exp are bit-identical. `dKV` is not,
|
||||
# because `atomic_addx4` leaves its summation order to the scheduler, on both sides.
|
||||
COMPILE_RTOL = 1e-2
|
||||
|
||||
|
||||
@@ -320,6 +306,7 @@ def _reference_lse(q: torch.Tensor, kv: torch.Tensor, indices: torch.Tensor, sin
|
||||
|
||||
@pytest.mark.parametrize(("batch", "seq_len", "seq_len_kv"), SHAPES, ids=SHAPE_IDS)
|
||||
@requires_sparse_attn_kernel
|
||||
@requires_datacenter_gpu
|
||||
def test_kernel_forward_matches_the_dense_reference(batch, seq_len, seq_len_kv):
|
||||
"""Output and log-sum-exp against the float32 gather oracle, which has identical semantics."""
|
||||
q, kv, indices, sinks = _inputs(batch, seq_len, seq_len_kv)
|
||||
@@ -339,6 +326,7 @@ def test_kernel_forward_matches_the_dense_reference(batch, seq_len, seq_len_kv):
|
||||
|
||||
|
||||
@requires_sparse_attn_kernel
|
||||
@requires_datacenter_gpu
|
||||
def test_kernel_pads_a_slot_count_its_tile_does_not_divide():
|
||||
"""A caller states the slots it means and the kernel covers the difference to its own tile.
|
||||
|
||||
@@ -363,6 +351,7 @@ def test_kernel_pads_a_slot_count_its_tile_does_not_divide():
|
||||
|
||||
|
||||
@requires_sparse_attn_kernel
|
||||
@requires_datacenter_gpu
|
||||
def test_fully_masked_query_reads_as_zero_keys():
|
||||
"""A query with no keys at all must emit exactly zero, on the sink term alone.
|
||||
|
||||
@@ -440,6 +429,7 @@ def test_tilelang_zero_fills_an_out_of_range_gather():
|
||||
|
||||
@pytest.mark.parametrize(("batch", "seq_len", "seq_len_kv"), SHAPES, ids=SHAPE_IDS)
|
||||
@requires_sparse_attn_kernel
|
||||
@requires_datacenter_gpu
|
||||
def test_kernel_backward_matches_autograd_through_the_reference(batch, seq_len, seq_len_kv):
|
||||
"""All three differentiable inputs, each against its own bound.
|
||||
|
||||
@@ -468,6 +458,7 @@ def test_kernel_backward_matches_autograd_through_the_reference(batch, seq_len,
|
||||
|
||||
|
||||
@requires_sparse_attn_kernel
|
||||
@requires_datacenter_gpu
|
||||
def test_kernel_traces_under_torch_compile():
|
||||
"""`torch.compile(fullgraph=True)` through the op, forward and backward.
|
||||
|
||||
@@ -523,15 +514,13 @@ V4FLASH_DOC_LENS = [(517, 1019), (3,), (300,), (3, 129, 1021), (2600,)]
|
||||
V4FLASH_DOC_IDS = ["two-docs", "no-entries", "one-short-doc", "three-docs", "saturated-topk"]
|
||||
|
||||
|
||||
def _v4flash_config(attn_impl: str = "kernel") -> DeepseekV4Config:
|
||||
return DeepseekV4Config(**V4FLASH_MODEL, _attn_impl=attn_impl)
|
||||
|
||||
|
||||
def v4flash_attention(layer_idx: int, dtype: torch.dtype = torch.float32, attn_impl: str = "kernel") -> nn.Module:
|
||||
def v4flash_attention(layer_idx: int, dtype: torch.dtype = torch.float32, eager: bool = False) -> nn.Module:
|
||||
"""One attention layer at the real DeepSeek V4 Flash shapes, 126M parameters of it."""
|
||||
with torch.device("cuda"), default_dtype(dtype):
|
||||
module = DeepseekV4Attention(_v4flash_config(attn_impl), layer_idx=layer_idx)
|
||||
module = DeepseekV4Attention(V4FLASH_CONFIG, layer_idx=layer_idx)
|
||||
_randomize(module)
|
||||
if eager:
|
||||
eager_reference.use_eager_attention(module)
|
||||
return module
|
||||
|
||||
|
||||
@@ -547,26 +536,19 @@ def _v4flash_hidden_states(seq_len: int) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
|
||||
|
||||
def _record_attention(monkeypatch) -> dict[str, torch.Tensor]:
|
||||
"""Capture what each attention path is handed and what it returns, from real forwards.
|
||||
"""Capture what the kernel is handed and what it returns, from real forwards.
|
||||
|
||||
Both implementations are module-level functions the layer looks up by name, so patching them
|
||||
`dsv4_sparse_attn` is a module-level function the layer looks up by name, so patching it
|
||||
records the call the layer actually made rather than a reconstruction of it.
|
||||
"""
|
||||
recorded: dict[str, torch.Tensor] = {}
|
||||
real_eager = dsv4_attention.eager_attention_with_sinks
|
||||
real_kernel = dsv4_attention.dsv4_sparse_attn
|
||||
|
||||
def eager(query, key, value, sinks, attention_mask, **kwargs):
|
||||
recorded["mask"] = attention_mask
|
||||
recorded["eager"] = real_eager(query, key, value, sinks, attention_mask, **kwargs)
|
||||
return recorded["eager"]
|
||||
|
||||
def kernel(q, kv_buf, indices, sinks, scale):
|
||||
recorded["kv_buf"], recorded["indices"] = kv_buf, indices
|
||||
recorded["kernel"] = real_kernel(q, kv_buf, indices, sinks, scale)
|
||||
return recorded["kernel"]
|
||||
|
||||
monkeypatch.setattr(dsv4_attention, "eager_attention_with_sinks", eager)
|
||||
monkeypatch.setattr(dsv4_attention, "dsv4_sparse_attn", kernel)
|
||||
return recorded
|
||||
|
||||
@@ -580,14 +562,17 @@ def _entry_counts(doc_lens: tuple[int, ...], compress_rate: int) -> list[int]:
|
||||
|
||||
|
||||
def _expected_picks(layer_type: str, doc_lens: tuple[int, ...]) -> int:
|
||||
"""How many pick slots every query of this layer type gets, on top of its local window."""
|
||||
"""How many pick slots every query of this layer type gets, on top of its local window.
|
||||
|
||||
CSA gets `index_topk` whatever the row holds, because `fp8_indexer` pads its output to the
|
||||
requested width and the surplus comes back as `IGNORE_SLOT`. HCA's tracks the longest document.
|
||||
"""
|
||||
rate = V4FLASH_MODEL["compress_rates"].get(layer_type)
|
||||
if rate is None:
|
||||
return 0
|
||||
counts = _entry_counts(doc_lens, rate)
|
||||
if layer_type == "heavily_compressed_attention":
|
||||
return max(counts)
|
||||
return min(V4FLASH_MODEL["index_topk"], sum(counts))
|
||||
return max(_entry_counts(doc_lens, rate))
|
||||
return V4FLASH_MODEL["index_topk"]
|
||||
|
||||
|
||||
def _hca_entries_admitted(doc_lens: tuple[int, ...]) -> torch.Tensor:
|
||||
@@ -633,6 +618,15 @@ def _selected_positions(indices: torch.Tensor, n_positions: int) -> torch.Tensor
|
||||
|
||||
|
||||
@requires_sparse_attn_kernel
|
||||
def test_deepseek_v4_refuses_a_shape_the_kernel_cannot_tile():
|
||||
"""The constructor refuses a head count the kernels cannot tile, rather than the first forward."""
|
||||
config = DeepseekV4Config(**{**V4FLASH_MODEL, "num_attention_heads": 16})
|
||||
with pytest.raises(ValueError, match="cannot run the fused sparse-attention kernel"):
|
||||
DeepseekV4Attention(config, layer_idx=V4FLASH_CSA_LAYER)
|
||||
|
||||
|
||||
@requires_sparse_attn_kernel
|
||||
@requires_datacenter_gpu
|
||||
@pytest.mark.parametrize("doc_lens", V4FLASH_DOC_LENS, ids=V4FLASH_DOC_IDS)
|
||||
@pytest.mark.parametrize("layer_idx", V4FLASH_LAYERS, ids=V4FLASH_LAYER_IDS)
|
||||
def test_sparse_indices_address_exactly_the_keys_the_dense_mask_admits(doc_lens, layer_idx, monkeypatch):
|
||||
@@ -656,7 +650,7 @@ def test_sparse_indices_address_exactly_the_keys_the_dense_mask_admits(doc_lens,
|
||||
"""
|
||||
module = v4flash_attention(layer_idx, dtype=torch.bfloat16)
|
||||
layer_type = V4FLASH_MODEL["layer_types"][layer_idx]
|
||||
packed = _packed_context(doc_lens, torch.bfloat16, _v4flash_config())
|
||||
packed = _packed_context(doc_lens, torch.bfloat16, V4FLASH_CONFIG)
|
||||
hidden_states = _v4flash_hidden_states(sum(doc_lens))[0].detach().to(torch.bfloat16)
|
||||
recorded = _record_attention(monkeypatch)
|
||||
|
||||
@@ -690,6 +684,7 @@ def test_sparse_indices_address_exactly_the_keys_the_dense_mask_admits(doc_lens,
|
||||
|
||||
|
||||
@requires_sparse_attn_kernel
|
||||
@requires_datacenter_gpu
|
||||
@pytest.mark.parametrize("doc_lens", V4FLASH_DOC_LENS, ids=V4FLASH_DOC_IDS)
|
||||
@pytest.mark.parametrize("layer_idx", V4FLASH_LAYERS, ids=V4FLASH_LAYER_IDS)
|
||||
def test_sparse_indices_are_in_range_and_never_repeat_a_key(doc_lens, layer_idx, monkeypatch):
|
||||
@@ -704,7 +699,7 @@ def test_sparse_indices_are_in_range_and_never_repeat_a_key(doc_lens, layer_idx,
|
||||
"""
|
||||
module = v4flash_attention(layer_idx, dtype=torch.bfloat16)
|
||||
layer_type = V4FLASH_MODEL["layer_types"][layer_idx]
|
||||
packed = _packed_context(doc_lens, torch.bfloat16, _v4flash_config())
|
||||
packed = _packed_context(doc_lens, torch.bfloat16, V4FLASH_CONFIG)
|
||||
hidden_states = _v4flash_hidden_states(sum(doc_lens))[0].detach().to(torch.bfloat16)
|
||||
recorded = _record_attention(monkeypatch)
|
||||
|
||||
@@ -730,6 +725,7 @@ def test_sparse_indices_are_in_range_and_never_repeat_a_key(doc_lens, layer_idx,
|
||||
|
||||
|
||||
@requires_sparse_attn_kernel
|
||||
@requires_datacenter_gpu
|
||||
@pytest.mark.parametrize("doc_lens", V4FLASH_DOC_LENS, ids=V4FLASH_DOC_IDS)
|
||||
def test_absent_slots_are_marked_negative_rather_than_pointed_at_a_pad_row(doc_lens, monkeypatch):
|
||||
"""An unused gather slot must hold `IGNORE_SLOT` (-1), never a position that `kv_buf` actually has.
|
||||
@@ -751,7 +747,7 @@ def test_absent_slots_are_marked_negative_rather_than_pointed_at_a_pad_row(doc_l
|
||||
this asserts the contract directly.
|
||||
"""
|
||||
module = v4flash_attention(V4FLASH_CSA_LAYER, dtype=torch.bfloat16)
|
||||
packed = _packed_context(doc_lens, torch.bfloat16, _v4flash_config())
|
||||
packed = _packed_context(doc_lens, torch.bfloat16, V4FLASH_CONFIG)
|
||||
hidden_states = _v4flash_hidden_states(sum(doc_lens))[0].detach().to(torch.bfloat16)
|
||||
recorded = _record_attention(monkeypatch)
|
||||
|
||||
@@ -806,6 +802,7 @@ EAGER_KERNEL_RTOL, EAGER_KERNEL_GRAD_RTOL = 1e-2, 5e-2
|
||||
|
||||
@pytest.mark.parametrize("doc_lens", EAGER_KERNEL_DOC_LENS, ids=EAGER_KERNEL_DOC_IDS)
|
||||
@requires_sparse_attn_kernel
|
||||
@requires_datacenter_gpu
|
||||
def test_sparse_attention_kernel_matches_eager(doc_lens, monkeypatch):
|
||||
"""The fused kernel against the naive dense softmax, single-document and packed.
|
||||
|
||||
@@ -829,7 +826,7 @@ def test_sparse_attention_kernel_matches_eager(doc_lens, monkeypatch):
|
||||
seq_len = sum(doc_lens)
|
||||
kernel_module = v4flash_attention(V4FLASH_CSA_LAYER, dtype=torch.bfloat16)
|
||||
eager_module = copy.deepcopy(kernel_module).float()
|
||||
_set_attn_impl(eager_module, "eager")
|
||||
eager_reference.use_eager_attention(eager_module)
|
||||
|
||||
with torch.device("cuda"):
|
||||
base = torch.randn(1, seq_len, V4FLASH_MODEL["hidden_size"], dtype=torch.bfloat16)
|
||||
@@ -845,8 +842,8 @@ def test_sparse_attention_kernel_matches_eager(doc_lens, monkeypatch):
|
||||
|
||||
monkeypatch.setattr(dsv4_attention, "dsv4_sparse_attn", counting_kernel)
|
||||
|
||||
kernel_output, _ = kernel_module(kernel_input, packed=_packed_context(doc_lens, torch.bfloat16, _v4flash_config()))
|
||||
eager_output, _ = eager_module(eager_input, packed=_packed_context(doc_lens, torch.float32, _v4flash_config()))
|
||||
kernel_output, _ = kernel_module(kernel_input, packed=_packed_context(doc_lens, torch.bfloat16, V4FLASH_CONFIG))
|
||||
eager_output, _ = eager_module(eager_input, packed=_packed_context(doc_lens, torch.float32, V4FLASH_CONFIG))
|
||||
assert calls == [seq_len], f"the forward never reached the kernel, calls={calls}"
|
||||
_assert_relative(kernel_output, eager_output, EAGER_KERNEL_RTOL, "attention output")
|
||||
|
||||
@@ -865,6 +862,7 @@ def test_sparse_attention_kernel_matches_eager(doc_lens, monkeypatch):
|
||||
|
||||
|
||||
@requires_sparse_attn_kernel
|
||||
@requires_datacenter_gpu
|
||||
def test_sparse_attention_kernel_packed_matches_unpacked(monkeypatch):
|
||||
"""The fused kernel path, end to end through one CSA layer, must respect documents.
|
||||
|
||||
@@ -880,7 +878,7 @@ def test_sparse_attention_kernel_packed_matches_unpacked(monkeypatch):
|
||||
a fallback would leave this test asserting a property of the gather reference instead.
|
||||
"""
|
||||
module = v4flash_attention(V4FLASH_CSA_LAYER, dtype=torch.bfloat16)
|
||||
packed = _packed_context(KERNEL_DOC_LENS, torch.bfloat16, _v4flash_config())
|
||||
packed = _packed_context(KERNEL_DOC_LENS, torch.bfloat16, V4FLASH_CONFIG)
|
||||
with torch.device("cuda"):
|
||||
hidden = torch.randn(1, sum(KERNEL_DOC_LENS), V4FLASH_MODEL["hidden_size"], dtype=torch.bfloat16)
|
||||
packed_input, alone_input = hidden.clone().requires_grad_(True), hidden.clone().requires_grad_(True)
|
||||
@@ -904,7 +902,7 @@ def test_sparse_attention_kernel_packed_matches_unpacked(monkeypatch):
|
||||
for index, length in enumerate(KERNEL_DOC_LENS):
|
||||
span = _doc_slice(KERNEL_DOC_LENS, index)
|
||||
alone_output, _ = module(
|
||||
alone_input[:, span], packed=_packed_context((length,), torch.bfloat16, _v4flash_config())
|
||||
alone_input[:, span], packed=_packed_context((length,), torch.bfloat16, V4FLASH_CONFIG)
|
||||
)
|
||||
_assert_relative(packed_output[:, span], alone_output, KERNEL_RTOL, f"document {index}")
|
||||
(alone_output * weight[:, span]).sum().backward()
|
||||
@@ -915,12 +913,13 @@ def test_sparse_attention_kernel_packed_matches_unpacked(monkeypatch):
|
||||
|
||||
|
||||
@requires_sparse_attn_kernel
|
||||
@requires_datacenter_gpu
|
||||
def test_sparse_attention_kernel_trains_every_parameter(monkeypatch):
|
||||
"""Every parameter of a CSA layer that can train does, with the kernel in the path.
|
||||
|
||||
`test_deepseek_v4_backward` makes this assertion through the assembled model, but only on the
|
||||
gather path: the kernel does not tile the toy shapes that file runs. This is the same assertion
|
||||
at module level and at the real Flash shapes, and it is not implied by its neighbour above, which
|
||||
dense reference, which is what that whole file binds. This is the same assertion at module
|
||||
level and at the real Flash shapes, and it is not implied by its neighbour above, which
|
||||
compares two runs of the same path and would pass unchanged if both left a parameter at zero.
|
||||
|
||||
The call count is load-bearing rather than decoration: `dsv4_sparse_attn` raises today
|
||||
@@ -928,7 +927,7 @@ def test_sparse_attention_kernel_trains_every_parameter(monkeypatch):
|
||||
asserting a property of the gather reference.
|
||||
"""
|
||||
module = v4flash_attention(V4FLASH_CSA_LAYER, dtype=torch.bfloat16)
|
||||
packed = _packed_context(KERNEL_DOC_LENS, torch.bfloat16, _v4flash_config())
|
||||
packed = _packed_context(KERNEL_DOC_LENS, torch.bfloat16, V4FLASH_CONFIG)
|
||||
with torch.device("cuda"):
|
||||
hidden_states = torch.randn(1, sum(KERNEL_DOC_LENS), V4FLASH_MODEL["hidden_size"], dtype=torch.bfloat16)
|
||||
hidden_states.requires_grad_(True)
|
||||
@@ -974,6 +973,7 @@ def test_sparse_attention_kernel_trains_every_parameter(monkeypatch):
|
||||
V4FLASH_HCA_DOCS = (256, 512)
|
||||
|
||||
|
||||
@requires_sparse_attn_kernel
|
||||
def test_v4flash_hca_attention_packed_matches_unpacked():
|
||||
"""An HCA layer at production shapes must answer each document as if it stood alone.
|
||||
|
||||
@@ -987,13 +987,13 @@ def test_v4flash_hca_attention_packed_matches_unpacked():
|
||||
`test_attention_packed_matches_unpacked[hca]` asserts the same invariant at toy shapes and
|
||||
rate 8.
|
||||
"""
|
||||
module = v4flash_attention(V4FLASH_HCA_LAYER, dtype=torch.float32, attn_impl="eager")
|
||||
module = v4flash_attention(V4FLASH_HCA_LAYER, dtype=torch.float32, eager=True)
|
||||
assert module.layer_type == "heavily_compressed_attention", (
|
||||
f"expected the Flash config's HCA layer, got {module.layer_type}"
|
||||
)
|
||||
seq_len = sum(V4FLASH_HCA_DOCS)
|
||||
packed_input, alone_input = _v4flash_hidden_states(seq_len)
|
||||
packed = _packed_context(V4FLASH_HCA_DOCS, torch.float32, _v4flash_config())
|
||||
packed = _packed_context(V4FLASH_HCA_DOCS, torch.float32, V4FLASH_CONFIG)
|
||||
|
||||
q_residual = module.q_a_norm(module.q_a_proj(packed_input.detach()))
|
||||
_, picks = module.compressor(packed_input.detach(), q_residual, packed)
|
||||
@@ -1010,9 +1010,7 @@ def test_v4flash_hca_attention_packed_matches_unpacked():
|
||||
|
||||
for index, length in enumerate(V4FLASH_HCA_DOCS):
|
||||
span = _doc_slice(V4FLASH_HCA_DOCS, index)
|
||||
alone_output, _ = module(
|
||||
alone_input[:, span], packed=_packed_context((length,), torch.float32, _v4flash_config())
|
||||
)
|
||||
alone_output, _ = module(alone_input[:, span], packed=_packed_context((length,), torch.float32, V4FLASH_CONFIG))
|
||||
_assert_relative(packed_output[:, span], alone_output, PACKED_RTOL, f"document {index}")
|
||||
(alone_output * weight[:, span]).sum().backward()
|
||||
|
||||
@@ -1068,14 +1066,15 @@ def _assert_within_the_bfloat16_floor(
|
||||
|
||||
|
||||
@requires_sparse_attn_kernel
|
||||
@requires_datacenter_gpu
|
||||
@pytest.mark.parametrize("doc_lens", PARITY_DOC_LENS, ids=PARITY_DOC_IDS)
|
||||
@pytest.mark.parametrize("layer_idx", V4FLASH_LAYERS, ids=V4FLASH_LAYER_IDS)
|
||||
def test_kernel_and_eager_consumers_agree_on_shared_weights(layer_idx, doc_lens):
|
||||
"""The two consumers of one `SparseAttnInputs` must compute the same attention, and its gradient.
|
||||
|
||||
They are handed the identical index tensor, so this is not about which keys a query reads,
|
||||
which its neighbours settle on integers. What is at stake is the attention core the layer picks
|
||||
between: the sink term in the softmax denominator, the scale, the value weighting and the
|
||||
which its neighbours settle on integers. What is at stake is the attention core itself: the
|
||||
sink term in the softmax denominator, the scale, the value weighting and the
|
||||
backward's scatter. A kernel that dropped the sink, weighted a head with another head's
|
||||
probabilities or lost a term in `dQ` would still hand back finite numbers of the right shape,
|
||||
and every packing test in this file would still pass, because both halves of those comparisons
|
||||
@@ -1088,9 +1087,9 @@ def test_kernel_and_eager_consumers_agree_on_shared_weights(layer_idx, doc_lens)
|
||||
"""
|
||||
module = v4flash_attention(layer_idx, dtype=torch.bfloat16)
|
||||
weights = module.state_dict()
|
||||
eager_bf16 = v4flash_attention(layer_idx, dtype=torch.bfloat16, attn_impl="eager")
|
||||
eager_bf16 = v4flash_attention(layer_idx, dtype=torch.bfloat16, eager=True)
|
||||
eager_bf16.load_state_dict(weights)
|
||||
eager_fp32 = v4flash_attention(layer_idx, dtype=torch.float32, attn_impl="eager")
|
||||
eager_fp32 = v4flash_attention(layer_idx, dtype=torch.float32, eager=True)
|
||||
eager_fp32.load_state_dict({name: tensor.float() for name, tensor in weights.items()})
|
||||
|
||||
with torch.device("cuda"):
|
||||
@@ -1104,7 +1103,7 @@ def test_kernel_and_eager_consumers_agree_on_shared_weights(layer_idx, doc_lens)
|
||||
("eager_fp32", eager_fp32, torch.float32),
|
||||
):
|
||||
hidden_states = hidden.to(dtype).clone().requires_grad_(True)
|
||||
packed = _packed_context(doc_lens, dtype, _v4flash_config())
|
||||
packed = _packed_context(doc_lens, dtype, V4FLASH_CONFIG)
|
||||
with _SparseAttnCallCounter() as counter:
|
||||
output, _ = layer(hidden_states, packed=packed)
|
||||
assert counter.count == (1 if name == "kernel" else 0), f"{name} made {counter.count} kernel calls"
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from prime_rl.trainer.models.kernels.fp8_indexer import fp8_indexer
|
||||
|
||||
pytestmark = [
|
||||
pytest.mark.gpu,
|
||||
pytest.mark.skipif(
|
||||
not torch.cuda.is_available() or torch.cuda.get_device_capability()[0] < 9,
|
||||
reason="the indexer kernel quantizes to Triton fp8e4nv (e4m3), only supported on Hopper (SM90) and newer",
|
||||
),
|
||||
]
|
||||
|
||||
HEADS, DIM, TOPK = 64, 128, 512
|
||||
|
||||
# How many queries and keys, the kernel's `S_q` and `S_k`. NUM_K >= 2 * TOPK, so the selection has
|
||||
# to discard some, and neither axis is a whole number of the kernel's widest tile, so its
|
||||
# ragged-tail masking runs.
|
||||
NUM_Q, NUM_K = 3000, 1060
|
||||
|
||||
# A segment is a run of queries over a run of keys. One segment, then three uneven ones, where
|
||||
# `ks` stops being zero. One segment holds more than TOPK keys, which is what it takes for a query
|
||||
# to have a full ranking to disagree about.
|
||||
SEGMENTS = [((NUM_Q, NUM_K),), ((700, 200), (500, 260), (1800, 600))]
|
||||
SEGMENT_IDS = ["one-segment", "three-segments"]
|
||||
|
||||
# FP8 quantization can only move a pick across the top-k boundary, so the two selections agree on
|
||||
# nearly every key. `p1` is the 1st percentile over queries: a whole tile of queries going wrong
|
||||
# is more than one percent of them, so it shows up there rather than hiding in the mean.
|
||||
AGREEMENT_MEAN, AGREEMENT_P1 = 0.98, 0.97
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def seed_rng():
|
||||
torch.manual_seed(0)
|
||||
|
||||
|
||||
def ranges(segments: tuple[tuple[int, int], ...]) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""The half-open key range `[ks, ke)` each query may read, one segment after another.
|
||||
|
||||
A segment's keys are contiguous, so its queries read a growing prefix of them: the first reads
|
||||
none of the segment at all, the last reads all of it.
|
||||
"""
|
||||
assert sum(n_q for n_q, _ in segments) == NUM_Q
|
||||
assert sum(n_k for _, n_k in segments) == NUM_K
|
||||
ks, ke, base = [], [], 0
|
||||
for n_q, n_k in segments:
|
||||
ks.append(torch.full((n_q,), base, device="cuda"))
|
||||
ke.append(base + torch.arange(n_q, device="cuda") * n_k // (n_q - 1))
|
||||
base += n_k
|
||||
return torch.cat(ks), torch.cat(ke)
|
||||
|
||||
|
||||
def eager_score_reference(q: torch.Tensor, k: torch.Tensor, w: torch.Tensor) -> torch.Tensor:
|
||||
"""`score[t,s] = sum_h w[t,h] relu(sum_d q[t,h,d] k[s,d])`, in float32.
|
||||
|
||||
The kernel's own formula, through the `(NUM_Q, HEADS, NUM_K)` intermediate the kernel exists to
|
||||
avoid, so the only difference between the two is the kernel's FP8 quantization. The ReLU is
|
||||
in place because a second buffer that size is most of a gigabyte.
|
||||
"""
|
||||
per_head = (q.float() @ k.float().T).relu_()
|
||||
return torch.einsum("th,ths->ts", w.float(), per_head)
|
||||
|
||||
|
||||
def readable_mask(ks: torch.Tensor, ke: torch.Tensor) -> torch.Tensor:
|
||||
"""`(NUM_Q, NUM_K)` bool: key `s` is in query `t`'s range `[ks[t], ke[t])`."""
|
||||
key_idx = torch.arange(NUM_K, device=ks.device)
|
||||
return (key_idx[None, :] >= ks[:, None]) & (key_idx[None, :] < ke[:, None])
|
||||
|
||||
|
||||
def selected_mask(picks: torch.Tensor) -> torch.Tensor:
|
||||
"""`(NUM_Q, NUM_K)` bool: which keys each query's picks name.
|
||||
|
||||
A query's unused slots come back holding `NUM_K`, the kernel's "no pick" sentinel, so they
|
||||
scatter into one throwaway column that is sliced back off.
|
||||
"""
|
||||
mask = torch.zeros(NUM_Q, NUM_K + 1, dtype=torch.bool, device=picks.device)
|
||||
return mask.scatter_(1, picks, True)[:, :NUM_K]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("segments", SEGMENTS, ids=SEGMENT_IDS)
|
||||
def test_selection_agreement(segments):
|
||||
"""The FP8 kernel's picks against the float32 reference's, as sets, per query.
|
||||
|
||||
Both sides read the same bfloat16 tensors, so the only difference measured is the kernel's own
|
||||
FP8 quantization. A query with no more than `TOPK` readable keys has nothing to rank away and
|
||||
must name that whole set exactly; the statistics cover the saturated queries, the only ones a
|
||||
pick can move across the top-k boundary of.
|
||||
"""
|
||||
ks, ke = ranges(segments)
|
||||
readable = readable_mask(ks, ke)
|
||||
|
||||
q = torch.randn(NUM_Q, HEADS, DIM, device="cuda").bfloat16()
|
||||
k = torch.randn(NUM_K, DIM, device="cuda").bfloat16()
|
||||
w = torch.randn(NUM_Q, HEADS, device="cuda").bfloat16()
|
||||
|
||||
scores = eager_score_reference(q, k, w).masked_fill(~readable, float("-inf"))
|
||||
# A query with fewer than TOPK readable keys fills its surplus picks from the -inf columns.
|
||||
ref_selected = selected_mask(scores.topk(TOPK, dim=-1).indices) & readable
|
||||
kernel_selected = selected_mask(fp8_indexer(q, k, w, ks.int(), ke.int(), TOPK).long())
|
||||
|
||||
saturated = readable.sum(-1) > TOPK
|
||||
assert torch.equal(kernel_selected[~saturated], ref_selected[~saturated]), (
|
||||
"a query that could hold every key it may read did not pick them all"
|
||||
)
|
||||
assert saturated.any(), "vacuous probe: no query has more readable keys than it can pick"
|
||||
|
||||
agreement = (ref_selected & kernel_selected).sum(-1)[saturated] / TOPK
|
||||
mean, p1 = agreement.mean().item(), agreement.quantile(0.01).item()
|
||||
assert mean > AGREEMENT_MEAN, f"mean set agreement {mean} below {AGREEMENT_MEAN}"
|
||||
assert p1 > AGREEMENT_P1, f"p1 set agreement {p1} below {AGREEMENT_P1}"
|
||||
@@ -1,9 +1,17 @@
|
||||
import os
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from transformers.models.gpt_oss.modeling_gpt_oss import GptOssForCausalLM as HFGptOssForCausalLM
|
||||
import torch.distributed as dist
|
||||
|
||||
from prime_rl.trainer.models.gpt_oss import GptOssConfig
|
||||
from prime_rl.trainer.models.gpt_oss import GptOssForCausalLM as PrimeRLGptOssForCausalLM
|
||||
from prime_rl.trainer.models.gpt_oss.attention import (
|
||||
GptOssAttention,
|
||||
substitute_gpt_oss_ring_attention,
|
||||
substitute_gpt_oss_ulysses_attention,
|
||||
)
|
||||
from prime_rl.utils.cp import setup_cp_attention_params
|
||||
|
||||
|
||||
def _config() -> GptOssConfig:
|
||||
@@ -18,44 +26,108 @@ def _config() -> GptOssConfig:
|
||||
num_key_value_heads=2,
|
||||
max_position_embeddings=128,
|
||||
num_experts_per_tok=2,
|
||||
sliding_window=4,
|
||||
rope_parameters={"rope_type": "default", "rope_theta": 150000.0},
|
||||
attn_implementation="flash_attention_4",
|
||||
use_cache=False,
|
||||
)
|
||||
|
||||
|
||||
def test_gpt_oss_checkpoint_conversion_roundtrip():
|
||||
config = _config()
|
||||
with torch.device("meta"):
|
||||
hf_model = HFGptOssForCausalLM(config)
|
||||
prime_model = PrimeRLGptOssForCausalLM(config)
|
||||
model = PrimeRLGptOssForCausalLM(_config())
|
||||
|
||||
hf_state_dict = {name: torch.randn(tensor.shape) for name, tensor in hf_model.state_dict().items()}
|
||||
expected_hf = {name: tensor.clone() for name, tensor in hf_state_dict.items()}
|
||||
prime_state_dict = prime_model.convert_to_prime(hf_state_dict)
|
||||
prime_state_dict = {name: torch.randn(tensor.shape) for name, tensor in model.state_dict().items()}
|
||||
expected_prime = {name: tensor.clone() for name, tensor in prime_state_dict.items()}
|
||||
hf_state_dict = model.convert_to_hf(prime_state_dict)
|
||||
|
||||
assert prime_model.is_prime_state_dict(prime_state_dict)
|
||||
assert not prime_model.is_hf_state_dict(prime_state_dict)
|
||||
assert set(prime_state_dict) == set(prime_model.state_dict())
|
||||
for name, tensor in prime_state_dict.items():
|
||||
assert tensor.shape == prime_model.state_dict()[name].shape, name
|
||||
assert model.is_hf_state_dict(hf_state_dict)
|
||||
assert not model.is_prime_state_dict(hf_state_dict)
|
||||
|
||||
roundtrip = prime_model.convert_to_hf(prime_state_dict)
|
||||
assert roundtrip.keys() == expected_hf.keys()
|
||||
roundtrip = model.convert_to_prime(hf_state_dict)
|
||||
assert roundtrip.keys() == expected_prime.keys()
|
||||
for name, tensor in roundtrip.items():
|
||||
torch.testing.assert_close(tensor, expected_hf[name])
|
||||
torch.testing.assert_close(tensor, expected_prime[name])
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def cp_process_group():
|
||||
if int(os.environ.get("WORLD_SIZE", 1)) != 2:
|
||||
pytest.skip("run with torchrun --nproc-per-node=2")
|
||||
if torch.cuda.get_device_capability()[0] not in (9, 10, 11):
|
||||
pytest.skip("GPT-OSS learned sinks require SM90 or SM100/SM110")
|
||||
|
||||
local_rank = int(os.environ["LOCAL_RANK"])
|
||||
torch.cuda.set_device(local_rank)
|
||||
dist.init_process_group("nccl")
|
||||
yield dist.group.WORLD
|
||||
dist.destroy_process_group()
|
||||
|
||||
|
||||
@pytest.mark.gpu
|
||||
def test_gpt_oss_moe_matches_hf():
|
||||
config = _config()
|
||||
with torch.device("cuda"):
|
||||
hf_model = HFGptOssForCausalLM(config).to(torch.bfloat16)
|
||||
prime_model = PrimeRLGptOssForCausalLM(config).to(torch.bfloat16)
|
||||
@pytest.mark.parametrize("cp_style", ["ring", "ulysses"])
|
||||
def test_gpt_oss_context_parallel_attention(cp_style: str, cp_process_group):
|
||||
local_rank = int(os.environ["LOCAL_RANK"])
|
||||
process_group = cp_process_group
|
||||
original_compute_attention = GptOssAttention.compute_attention
|
||||
|
||||
state_dict = hf_model.state_dict()
|
||||
prime_model.convert_to_prime(state_dict)
|
||||
prime_model.load_state_dict(state_dict)
|
||||
try:
|
||||
torch.manual_seed(0)
|
||||
config = _config()
|
||||
config.head_dim = 64
|
||||
attention = GptOssAttention(config, layer_idx=0).cuda().to(torch.bfloat16)
|
||||
query = torch.randn(8, 4, 64, device="cuda", dtype=torch.bfloat16)
|
||||
key = torch.randn(8, 2, 64, device="cuda", dtype=torch.bfloat16)
|
||||
value = torch.randn(8, 2, 64, device="cuda", dtype=torch.bfloat16)
|
||||
with torch.no_grad():
|
||||
for tensor in (attention.sinks, query, key, value):
|
||||
dist.broadcast(tensor, src=0)
|
||||
cu_seqlens = torch.tensor([0, 5, 8], device="cuda", dtype=torch.int32)
|
||||
|
||||
hidden_states = torch.randn(2, 8, config.hidden_size, device="cuda", dtype=torch.bfloat16)
|
||||
expected, _ = hf_model.model.layers[0].mlp(hidden_states)
|
||||
actual = prime_model.model.layers[0].mlp(hidden_states)
|
||||
torch.testing.assert_close(actual, expected, rtol=2e-2, atol=2e-2)
|
||||
reference_query = query.detach().clone().requires_grad_()
|
||||
reference_key = key.detach().clone().requires_grad_()
|
||||
reference_value = value.detach().clone().requires_grad_()
|
||||
reference = original_compute_attention(
|
||||
attention,
|
||||
reference_query,
|
||||
reference_key,
|
||||
reference_value,
|
||||
cu_seqlens,
|
||||
5,
|
||||
)
|
||||
reference_output = reference.detach().clone()
|
||||
reference.float().square().sum().backward()
|
||||
reference_sink_grad = attention.sinks.grad.detach().clone()
|
||||
attention.sinks.grad = None
|
||||
|
||||
position_ids = torch.tensor([[0, 1, 2, 3, 4, 0, 1, 2]], device="cuda")
|
||||
setup_cp_attention_params(
|
||||
position_ids,
|
||||
process_group,
|
||||
seq_lens=torch.tensor([5, 3], device="cuda"),
|
||||
cp_style=cp_style,
|
||||
)
|
||||
if cp_style == "ring":
|
||||
substitute_gpt_oss_ring_attention(process_group, heads_k_stride=1)
|
||||
else:
|
||||
substitute_gpt_oss_ulysses_attention(process_group)
|
||||
|
||||
local_slice = slice(local_rank * 4, (local_rank + 1) * 4)
|
||||
local_query = query[local_slice].detach().clone().requires_grad_()
|
||||
local_key = key[local_slice].detach().clone().requires_grad_()
|
||||
local_value = value[local_slice].detach().clone().requires_grad_()
|
||||
actual = attention.compute_attention(local_query, local_key, local_value, cu_seqlens, 5)
|
||||
actual.float().square().sum().backward()
|
||||
|
||||
gathered = [torch.empty_like(actual) for _ in range(2)]
|
||||
dist.all_gather(gathered, actual)
|
||||
torch.testing.assert_close(torch.cat(gathered), reference_output, rtol=3e-2, atol=3e-2)
|
||||
torch.testing.assert_close(local_query.grad, reference_query.grad[local_slice], rtol=5e-2, atol=5e-2)
|
||||
torch.testing.assert_close(local_key.grad, reference_key.grad[local_slice], rtol=5e-2, atol=5e-2)
|
||||
torch.testing.assert_close(local_value.grad, reference_value.grad[local_slice], rtol=5e-2, atol=5e-2)
|
||||
|
||||
sink_grad = attention.sinks.grad
|
||||
dist.all_reduce(sink_grad)
|
||||
torch.testing.assert_close(sink_grad, reference_sink_grad, rtol=5e-2, atol=5e-2)
|
||||
finally:
|
||||
GptOssAttention.compute_attention = original_compute_attention
|
||||
|
||||
@@ -2,14 +2,36 @@ import pytest
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
from prime_rl.configs.trainer import ModelConfig
|
||||
from prime_rl.trainer.distributed.token_dispatcher import LocalTokenDispatcher
|
||||
from prime_rl.trainer.models.layers.activations import ActivationDispatch
|
||||
from prime_rl.trainer.models.layers.grouped_gemm import BF16GroupedGemm
|
||||
from prime_rl.trainer.models.layers.mlp import FeedForward
|
||||
from prime_rl.trainer.models.layers.moe import (
|
||||
GroupedExperts,
|
||||
MoE,
|
||||
MoEArgs,
|
||||
)
|
||||
from prime_rl.trainer.moe_runtime import configure_moe_runtime
|
||||
from prime_rl.trainer.parallel_dims import ParallelDims
|
||||
|
||||
|
||||
@pytest.mark.parametrize("selection", [[], [0], "0%", "50%"])
|
||||
def test_unselected_moe_uses_bf16_without_loading_quantization_backend(selection):
|
||||
moe = MoE.from_args(MoEArgs(num_experts=2), dim=4, hidden_dim=8, shared_expert=None)
|
||||
parameters = dict(moe.named_parameters())
|
||||
model = torch.nn.Module()
|
||||
model.model = torch.nn.Module()
|
||||
model.model.layers = torch.nn.ModuleList([torch.nn.Identity(), moe])
|
||||
config = ModelConfig.model_validate({"moe": {"compute": {"type": "mxfp8", "apply_to": selection}}})
|
||||
dims = ParallelDims(dp_replicate=1, dp_shard=1, cp=1, pp=1, ep=1, world_size=1)
|
||||
|
||||
configure_moe_runtime(model, config, dims)
|
||||
|
||||
assert isinstance(moe.experts.grouped_gemm, BF16GroupedGemm)
|
||||
assert isinstance(moe.token_dispatcher, LocalTokenDispatcher)
|
||||
assert moe.token_dispatcher.token_group_alignment == moe.experts.grouped_gemm.token_group_alignment
|
||||
assert all(moe.get_parameter(name) is parameter for name, parameter in parameters.items())
|
||||
|
||||
|
||||
def _grouped_mm_reference(x: torch.Tensor, weights: torch.Tensor, *, offs: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
@@ -2,24 +2,17 @@ from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from transformers.models.nemotron_h.configuration_nemotron_h import NemotronHConfig as HFNemotronHConfig
|
||||
from transformers.models.nemotron_h.modeling_nemotron_h import (
|
||||
NemotronHAttention,
|
||||
)
|
||||
from transformers.models.nemotron_h.modeling_nemotron_h import (
|
||||
NemotronHForCausalLM as HFNemotronHForCausalLM,
|
||||
)
|
||||
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
from prime_rl.trainer.models.nemotron_h import NemotronHConfig, NemotronHForCausalLM
|
||||
from prime_rl.trainer.models.nemotron_h.modeling_nemotron_h import NemotronHAttentionLayer, NemotronHMambaLayer
|
||||
from prime_rl.trainer.models.nemotron_h.mamba import NemotronHMamba2
|
||||
from prime_rl.utils.cp import setup_model_cp
|
||||
from prime_rl.utils.utils import default_dtype
|
||||
|
||||
pytestmark = [pytest.mark.gpu]
|
||||
|
||||
# Shared small-model hyperparams (satisfy mamba_expand * hidden_size == mamba_num_heads * mamba_head_dim)
|
||||
_BASE = dict(
|
||||
attn_implementation="flash_attention_2",
|
||||
vocab_size=256,
|
||||
hidden_size=256,
|
||||
num_attention_heads=4,
|
||||
@@ -27,13 +20,13 @@ _BASE = dict(
|
||||
head_dim=64,
|
||||
max_position_embeddings=128,
|
||||
intermediate_size=512,
|
||||
mamba_expand=2,
|
||||
expand=2,
|
||||
mamba_num_heads=8,
|
||||
mamba_head_dim=64,
|
||||
ssm_state_size=64,
|
||||
mamba_n_groups=1,
|
||||
mamba_d_conv=4,
|
||||
mamba_chunk_size=64,
|
||||
n_groups=1,
|
||||
conv_kernel=4,
|
||||
chunk_size=64,
|
||||
n_routed_experts=4,
|
||||
n_shared_experts=1,
|
||||
moe_intermediate_size=256,
|
||||
@@ -49,66 +42,11 @@ def _seq_lens(input_ids: torch.Tensor) -> torch.Tensor:
|
||||
return torch.tensor([input_ids.shape[1]], device=input_ids.device)
|
||||
|
||||
|
||||
def get_model_pairs():
|
||||
"""Create an HF model and a PrimeRL model with shared weights."""
|
||||
hf_config = HFNemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
|
||||
hf_config._attn_implementation = "flash_attention_2"
|
||||
|
||||
prime_config = NemotronHConfig(
|
||||
**_BASE,
|
||||
layers_block_type=["mamba", "moe", "attention", "moe"],
|
||||
)
|
||||
prime_config._attn_implementation = "flash_attention_2"
|
||||
|
||||
with torch.device("cuda"), default_dtype(torch.bfloat16):
|
||||
hf_model = HFNemotronHForCausalLM._from_config(hf_config)
|
||||
prime_model = NemotronHForCausalLM._from_config(prime_config)
|
||||
|
||||
with torch.no_grad():
|
||||
state_dict = hf_model.state_dict()
|
||||
prime_state_keys = prime_model.state_dict().keys()
|
||||
prime_model.convert_to_prime(state_dict)
|
||||
prime_model.load_state_dict(state_dict)
|
||||
|
||||
inject_prime_lm_head(prime_model, chunk_size=None)
|
||||
assert set(prime_state_keys) - set(state_dict.keys()) == set()
|
||||
return hf_model, prime_model
|
||||
|
||||
|
||||
def test_nemotron_h_mamba_moe_only():
|
||||
"""Test Mamba and MoE layers produce identical outputs (attention bypassed)."""
|
||||
hf_model, prime_model = get_model_pairs()
|
||||
|
||||
# Bypass attention layers in both models so only Mamba+MoE are exercised
|
||||
for layer in hf_model.model.layers:
|
||||
if isinstance(layer.mixer, NemotronHAttention):
|
||||
layer.forward = lambda hidden_states, **kwargs: hidden_states
|
||||
|
||||
for layer in prime_model.model.layers:
|
||||
if isinstance(layer, NemotronHAttentionLayer):
|
||||
layer.forward = lambda hidden_states, **kwargs: hidden_states
|
||||
|
||||
torch.manual_seed(42)
|
||||
with torch.device("cuda"), default_dtype(torch.bfloat16):
|
||||
input_ids = torch.randint(0, 256, (1, 32))
|
||||
position_ids = torch.arange(0, 32).unsqueeze(0)
|
||||
|
||||
hf_output = hf_model(input_ids, position_ids=position_ids)
|
||||
prime_output = prime_model(input_ids, position_ids=position_ids, seq_lens=_seq_lens(input_ids))
|
||||
hf_output.logits.sum().backward()
|
||||
prime_output["logits"].sum().backward()
|
||||
|
||||
logits_diff = prime_output["logits"] - hf_output.logits
|
||||
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=1e-0), (
|
||||
f"Max logits diff: {logits_diff.abs().max()}"
|
||||
)
|
||||
grad_diff = hf_model.model.embeddings.weight.grad - prime_model.model.embed_tokens.weight.grad
|
||||
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=1000), f"Max grad diff: {grad_diff.abs().max()}"
|
||||
|
||||
|
||||
def test_nemotron_h_reverse():
|
||||
"""PrimeRL weights convert back to the source checkpoint layout."""
|
||||
_, prime_model = get_model_pairs()
|
||||
config = NemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
|
||||
with torch.device("meta"):
|
||||
prime_model = NemotronHForCausalLM(config)
|
||||
converted = prime_model.convert_to_hf(dict(prime_model.state_dict()))
|
||||
|
||||
assert prime_model.is_hf_state_dict(converted)
|
||||
@@ -116,34 +54,14 @@ def test_nemotron_h_reverse():
|
||||
assert not any("mlp.experts.up_proj" in name for name in converted)
|
||||
|
||||
|
||||
def test_nemotron_h():
|
||||
"""Test full model (Mamba + MoE + Attention) produces close outputs."""
|
||||
hf_model, prime_model = get_model_pairs()
|
||||
|
||||
with torch.device("cuda"), default_dtype(torch.bfloat16):
|
||||
input_ids = torch.randint(0, 256, (1, 32))
|
||||
position_ids = torch.arange(0, 32).unsqueeze(0)
|
||||
|
||||
hf_output = hf_model(input_ids, position_ids=position_ids)
|
||||
prime_output = prime_model(input_ids, position_ids=position_ids, seq_lens=_seq_lens(input_ids))
|
||||
# Slightly larger tolerance due to different SDPA attention implementations
|
||||
logits_diff = prime_output["logits"] - hf_output.logits
|
||||
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=1e-0), (
|
||||
f"Max logits diff: {logits_diff.abs().max()}"
|
||||
)
|
||||
|
||||
|
||||
def test_nemotron_h_backward():
|
||||
"""Verify all parameters receive non-zero gradients."""
|
||||
prime_config = NemotronHConfig(
|
||||
**_BASE,
|
||||
layers_block_type=["mamba", "moe", "attention", "moe"],
|
||||
)
|
||||
prime_config = NemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
|
||||
with torch.device("cuda"), default_dtype(torch.bfloat16):
|
||||
model = NemotronHForCausalLM(prime_config)
|
||||
inject_prime_lm_head(model)
|
||||
|
||||
input_ids = torch.randint(0, 256, (2, 16), device="cuda")
|
||||
input_ids = torch.randint(0, 256, (1, 16), device="cuda")
|
||||
output = model(input_ids, seq_lens=_seq_lens(input_ids))
|
||||
output["logits"].sum().backward()
|
||||
|
||||
@@ -158,10 +76,7 @@ def test_nemotron_h_backward():
|
||||
|
||||
def test_nemotron_h_weight_conversion_roundtrip():
|
||||
"""Verify PrimeRL -> HF -> PrimeRL conversion preserves all weights."""
|
||||
prime_config = NemotronHConfig(
|
||||
**_BASE,
|
||||
layers_block_type=["mamba", "moe", "attention", "moe"],
|
||||
)
|
||||
prime_config = NemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
|
||||
model = NemotronHForCausalLM(prime_config).to("cuda")
|
||||
original_sd = {k: v.clone() for k, v in model.state_dict().items()}
|
||||
|
||||
@@ -176,46 +91,49 @@ def test_nemotron_h_weight_conversion_roundtrip():
|
||||
assert torch.equal(original_sd[key], sd[key]), f"Value mismatch for {key}"
|
||||
|
||||
|
||||
def test_nemotron_h_hybrid_override_pattern():
|
||||
"""Verify hybrid_override_pattern correctly maps to layers_block_type."""
|
||||
config = NemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
|
||||
assert config.layers_block_type == ["mamba", "moe", "attention", "moe"]
|
||||
assert config.num_hidden_layers == 4
|
||||
def test_nemotron_h_layer_types():
|
||||
expected = ["mamba", "moe", "attention", "moe"]
|
||||
pattern_config = NemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
|
||||
list_config = NemotronHConfig(**_BASE, layers_block_type=expected)
|
||||
|
||||
assert pattern_config.layer_types == expected
|
||||
assert list_config.layer_types == expected
|
||||
assert pattern_config.num_hidden_layers == list_config.num_hidden_layers == 4
|
||||
|
||||
|
||||
def test_nemotron_h_context_parallel_setup_finds_wrapped_mamba_layer():
|
||||
config = NemotronHConfig(
|
||||
**(_BASE | {"mamba_n_groups": 2}),
|
||||
layers_block_type=["mamba", "moe", "attention", "moe"],
|
||||
**(_BASE | {"n_groups": 2}),
|
||||
hybrid_override_pattern="ME*E",
|
||||
)
|
||||
with torch.device("meta"):
|
||||
model = NemotronHForCausalLM(config)
|
||||
|
||||
mamba_layer = model.model.layers[0]
|
||||
assert isinstance(mamba_layer, NemotronHMambaLayer)
|
||||
assert isinstance(mamba_layer.mamba, NemotronHMamba2)
|
||||
model.model.layers[0] = torch.nn.Sequential(mamba_layer)
|
||||
|
||||
cp_group = MagicMock()
|
||||
setup_model_cp(model, cp_group, cp_rank=1, cp_world_size=2)
|
||||
|
||||
assert mamba_layer._cp_group is cp_group
|
||||
assert mamba_layer._cp_rank == 1
|
||||
assert mamba_layer._cp_world_size == 2
|
||||
assert mamba_layer.mamba.process_group is cp_group
|
||||
assert mamba_layer.mamba.context_parallel_rank == 1
|
||||
assert mamba_layer.mamba.context_parallel_world_size == 2
|
||||
|
||||
|
||||
def test_nemotron_h_no_latent_projection():
|
||||
"""Verify model works without latent projections (moe_latent_size=None)."""
|
||||
prime_config = NemotronHConfig(
|
||||
**{**_BASE, "moe_latent_size": None},
|
||||
layers_block_type=["mamba", "moe", "attention", "moe"],
|
||||
hybrid_override_pattern="ME*E",
|
||||
)
|
||||
with torch.device("cuda"), default_dtype(torch.bfloat16):
|
||||
model = NemotronHForCausalLM(prime_config)
|
||||
inject_prime_lm_head(model)
|
||||
|
||||
input_ids = torch.randint(0, 256, (2, 16), device="cuda")
|
||||
input_ids = torch.randint(0, 256, (1, 16), device="cuda")
|
||||
output = model(input_ids, seq_lens=_seq_lens(input_ids))
|
||||
assert output["logits"].shape == (2, 16, 256)
|
||||
assert output["logits"].shape == (1, 16, 256)
|
||||
|
||||
output["logits"].sum().backward()
|
||||
for name, p in model.named_parameters():
|
||||
|
||||
@@ -29,13 +29,13 @@ _BASE = dict(
|
||||
head_dim=64,
|
||||
max_position_embeddings=128,
|
||||
intermediate_size=512,
|
||||
mamba_expand=2,
|
||||
expand=2,
|
||||
mamba_num_heads=8,
|
||||
mamba_head_dim=64,
|
||||
ssm_state_size=64,
|
||||
mamba_n_groups=1,
|
||||
mamba_d_conv=4,
|
||||
mamba_chunk_size=64,
|
||||
n_groups=1,
|
||||
conv_kernel=4,
|
||||
chunk_size=64,
|
||||
n_routed_experts=4,
|
||||
n_shared_experts=1,
|
||||
moe_intermediate_size=256,
|
||||
@@ -48,13 +48,10 @@ _BASE = dict(
|
||||
|
||||
|
||||
def _make_model(device="cuda"):
|
||||
config = NemotronHConfig(
|
||||
**_BASE,
|
||||
layers_block_type=["mamba", "moe", "attention", "moe"],
|
||||
)
|
||||
config = NemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
|
||||
config._attn_implementation = "flash_attention_2"
|
||||
with torch.device(device), default_dtype(torch.bfloat16):
|
||||
model = NemotronHForCausalLM._from_config(config)
|
||||
model = NemotronHForCausalLM(config)
|
||||
inject_prime_lm_head(model, chunk_size=None)
|
||||
return model
|
||||
|
||||
@@ -88,7 +85,7 @@ def test_kl_zero_when_identical():
|
||||
"""Two identical models should have zero KL mismatch."""
|
||||
model = _make_model()
|
||||
|
||||
input_ids = torch.randint(0, 256, (2, 32), device="cuda")
|
||||
input_ids = torch.randint(0, 256, (1, 32), device="cuda")
|
||||
logprobs = _get_logprobs_vanilla(model, input_ids)
|
||||
|
||||
loss_mask = torch.ones(32, dtype=torch.bool, device="cuda")
|
||||
@@ -121,7 +118,7 @@ def test_kl_positive_after_perturbation():
|
||||
policy_model.load_state_dict(ref_model.state_dict())
|
||||
_perturb_model(policy_model, scale=0.05)
|
||||
|
||||
input_ids = torch.randint(0, 256, (2, 32), device="cuda")
|
||||
input_ids = torch.randint(0, 256, (1, 32), device="cuda")
|
||||
|
||||
ref_logprobs = _get_logprobs_vanilla(ref_model, input_ids)
|
||||
policy_logprobs = _get_logprobs_vanilla(policy_model, input_ids)
|
||||
@@ -182,14 +179,11 @@ def test_kl_increases_with_larger_perturbation():
|
||||
|
||||
def test_kl_with_fused_lm_head():
|
||||
"""FusedOutputLinear should produce same logprobs as VanillaOutputLinear."""
|
||||
config = NemotronHConfig(
|
||||
**_BASE,
|
||||
layers_block_type=["mamba", "moe", "attention", "moe"],
|
||||
)
|
||||
config = NemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
|
||||
config._attn_implementation = "flash_attention_2"
|
||||
|
||||
with torch.device("cuda"), default_dtype(torch.bfloat16):
|
||||
model = NemotronHForCausalLM._from_config(config)
|
||||
model = NemotronHForCausalLM(config)
|
||||
|
||||
# Get logits from vanilla head
|
||||
inject_prime_lm_head(model, chunk_size=None)
|
||||
@@ -296,7 +290,7 @@ def test_kl_mismatch_formula_sanity():
|
||||
ref_model.load_state_dict(model.state_dict())
|
||||
_perturb_model(model, scale=0.1)
|
||||
|
||||
input_ids = torch.randint(0, 256, (2, 32), device="cuda")
|
||||
input_ids = torch.randint(0, 256, (1, 32), device="cuda")
|
||||
|
||||
trainer_logprobs = _get_logprobs_vanilla(model, input_ids)
|
||||
inference_logprobs = _get_logprobs_vanilla(ref_model, input_ids)
|
||||
|
||||
@@ -17,25 +17,27 @@ exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for
|
||||
exclude-newer-span = "P7D"
|
||||
|
||||
[options.exclude-newer-package]
|
||||
vllm = false
|
||||
verifiers = false
|
||||
harbor = "2026-08-11T00:00:00Z"
|
||||
prime-pydantic-config = false
|
||||
vllm-router = false
|
||||
deep-ep = false
|
||||
deep-gemm = false
|
||||
dion = false
|
||||
fastokens = false
|
||||
flash-attn-3 = false
|
||||
prime-tunnel = false
|
||||
deep-gemm = false
|
||||
prime-evals = false
|
||||
torchao = false
|
||||
tokenspeed-mla = false
|
||||
harbor = "2026-08-11T00:00:00Z"
|
||||
nixl-cu13 = false
|
||||
deep-ep = false
|
||||
prime-sandboxes = false
|
||||
renderers = false
|
||||
prime-kernels = false
|
||||
prime = false
|
||||
prime-evals = false
|
||||
prime-kernels = false
|
||||
prime-pydantic-config = false
|
||||
prime-runs = false
|
||||
prime-sandboxes = false
|
||||
prime-traces = false
|
||||
prime-tunnel = false
|
||||
renderers = false
|
||||
tokenspeed-mla = false
|
||||
torchao = false
|
||||
verifiers = false
|
||||
vllm = false
|
||||
vllm-router = false
|
||||
|
||||
[manifest]
|
||||
members = [
|
||||
@@ -140,11 +142,17 @@ overrides = [
|
||||
{ name = "nvidia-cudnn-cu13", marker = "sys_platform == 'linux'", specifier = ">=9.15" },
|
||||
{ name = "nvidia-cutlass-dsl", specifier = "==4.6.2" },
|
||||
{ name = "openenv-core" },
|
||||
{ name = "tilelang", specifier = "==0.1.12" },
|
||||
{ name = "torch", marker = "sys_platform != 'linux'", specifier = ">=2.13.0" },
|
||||
{ name = "torch", marker = "sys_platform == 'linux'", specifier = ">=2.13.0", index = "https://download.pytorch.org/whl/cu130" },
|
||||
{ name = "transformers", specifier = "==5.6.2" },
|
||||
]
|
||||
|
||||
[[manifest.dependency-metadata]]
|
||||
name = "ai-dynamo-runtime"
|
||||
version = "1.4.2"
|
||||
requires-dist = ["pydantic>=2.10.6,<=2.13.5", "uvloop>=0.21.0"]
|
||||
|
||||
[[manifest.dependency-metadata]]
|
||||
name = "modelexpress"
|
||||
version = "0.3.0"
|
||||
@@ -178,6 +186,38 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/6a/00/b08f23b7d7e1e14ce01419a467b583edbb93c6cdb8654e54a9cc579cd61f/addict-2.4.0-py3-none-any.whl", hash = "sha256:249bb56bbfd3cdc2a004ea0ff4c2b6ddc84d53bc2194761636eb314d5cfa5dfc", size = 3832, upload-time = "2020-11-21T16:21:29.588Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ai-dynamo"
|
||||
version = "1.4.2"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "ai-dynamo-runtime" },
|
||||
{ name = "aiohttp" },
|
||||
{ name = "kubernetes", version = "32.0.1", source = { registry = "https://pypi.org/simple" } },
|
||||
{ name = "msgspec" },
|
||||
{ name = "prometheus-client" },
|
||||
{ name = "pyzmq" },
|
||||
{ name = "transformers" },
|
||||
{ name = "typing-extensions" },
|
||||
{ name = "zstandard" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/34/21/2c5f23ebcd3d1bcad8c46cd0b25bcfe485acba46935ec30576bafa50179c/ai_dynamo-1.4.2-py3-none-any.whl", hash = "sha256:02b3d386b71c0830254ab0878602b5ea77246cedcd731d0078e863cd4b0dabd2", size = 2943529, upload-time = "2026-08-28T19:03:53.336Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ai-dynamo-runtime"
|
||||
version = "1.4.2"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "pydantic" },
|
||||
{ name = "uvloop" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/9f/22/86780714d43ef43aaea4579a6e1e30b83a08445adf4b2f9bd7aa109cd312/ai_dynamo_runtime-1.4.2-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:195683380b86ce25c4d1316b38359bad1e5a8ec25a2cf8b70ec2c408217f6d15", size = 55694568, upload-time = "2026-08-28T19:04:44.002Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/cd/27/e73597ebd48ce7b8a2a8ff0392af1a7d97040ed967d075a0d821ad1758f7/ai_dynamo_runtime-1.4.2-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:1d0a62998f5d182c7ff7819f9d7d451bbe4c6f7a063f2ff7af662fa0e86e98b9", size = 56273981, upload-time = "2026-08-28T19:05:24.748Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aime24"
|
||||
version = "0.1.0"
|
||||
@@ -357,6 +397,7 @@ dependencies = [
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/6d/3d/4b9226cd45aa800a6904603dda9b323d728f3c3869952a673f3483b78b19/apache_tvm_ffi-0.1.11.tar.gz", hash = "sha256:153cd2c5a9717804cb0bcd9b2709f22a1e5f80ed05b5a490faf5949b136eedba", size = 2798354, upload-time = "2026-05-04T17:48:43.852Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/05/9d/0f81ca556e5836b3ca64818cdae3f47dc7822bd35d22ddef7a54106d801d/apache_tvm_ffi-0.1.11-cp312-abi3-macosx_11_0_arm64.whl", hash = "sha256:6ae51cc7df415b5f373a9df4baa1165a65608e519bea81e7dd23428f00eeb689", size = 2418793, upload-time = "2026-05-04T17:47:57.879Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/2a/a9/f48e5dd4ae1f6f0c5ffac259c0a9531b7d6a7c0a4c45bc2229d55de6adf8/apache_tvm_ffi-0.1.11-cp312-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:da2c8d07fdc737d1ba75f4de25c29f156905b9dc980f1da90c395b4db525f522", size = 2605176, upload-time = "2026-05-04T17:47:59.676Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/36/99/2848df4e8ed5bf51df1d286d1718510584fa61e88adbc9c5b23d71b38f7c/apache_tvm_ffi-0.1.11-cp312-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:78aa1857b04a2ea718317041ab3f01288b3d496e6036eb1b99ebdc9da0fdaef5", size = 2725887, upload-time = "2026-05-04T17:48:01.381Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/7d/80/963c991934a4eb0fa0c0178f51963333fe14a96b732009da642b6bf6b42e/apache_tvm_ffi-0.1.11-cp312-abi3-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a8b845c8dff498fb981c1dda36c954549204191b485a385845e604966594d0b2", size = 2513121, upload-time = "2026-05-04T17:48:03.43Z" },
|
||||
@@ -846,7 +887,8 @@ dependencies = [
|
||||
{ name = "httpx" },
|
||||
{ name = "importlib-resources" },
|
||||
{ name = "jsonschema" },
|
||||
{ name = "kubernetes" },
|
||||
{ name = "kubernetes", version = "32.0.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "kubernetes", version = "36.0.3", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
|
||||
{ name = "mmh3" },
|
||||
{ name = "numpy" },
|
||||
{ name = "onnxruntime" },
|
||||
@@ -2951,34 +2993,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/ab/b5/36c712098e6191d1b4e349304ef73a8d06aed77e56ceaac8c0a306c7bda1/jupyterlab_widgets-3.0.16-py3-none-any.whl", hash = "sha256:45fa36d9c6422cf2559198e4db481aa243c7a32d9926b500781c830c80f7ecf8", size = 914926, upload-time = "2025-11-01T21:11:28.008Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kernels"
|
||||
version = "0.14.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "huggingface-hub", version = "1.28.0", source = { registry = "https://pypi.org/simple" } },
|
||||
{ name = "kernels-data" },
|
||||
{ name = "packaging" },
|
||||
{ name = "pyyaml" },
|
||||
{ name = "tomlkit" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/cd/16/d9c473289d72d07a5c8e00367e5de9326bf0135e65ba74a235e2eb2510f2/kernels-0.14.1.tar.gz", hash = "sha256:ba21b7b509b7a0c2d2c7a0efd546e9dda2b1022ed5ff2b8fde8e94d7637754d3", size = 62800, upload-time = "2026-05-14T06:42:36.234Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/94/94/fb8cbf1427af4b520ad08a458b6696f1958732761bc284b55273fa3aa684/kernels-0.14.1-py3-none-any.whl", hash = "sha256:be1a91116e14be1e012fc8f47afb51173ee052586a570fba3d594ef0d1b38920", size = 57977, upload-time = "2026-05-14T06:42:35.002Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kernels-data"
|
||||
version = "0.14.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/29/15/b071356425b50d8b49d01152b344222d18b4a535cbc352f7d00267dd4ceb/kernels_data-0.14.1.tar.gz", hash = "sha256:35c7d46da843decc1f12f098ca781b8453f21ecbabb4e18b9266c0e0b113fc82", size = 41008, upload-time = "2026-05-14T06:41:15.534Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/63/6d/dc1c2095d858b62dbfe8ccf4bd05ff304450601bef42e4c5e971e3550deb/kernels_data-0.14.1-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d6446304de3bec9d72da88e64717e37ad4ec8bc8b096e0f73a5c5d5e6ae4f153", size = 1162253, upload-time = "2026-05-14T06:40:27.196Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/4e/b5/cabd476a1bdaad270509b48427a4f06a62a717d3aa67a6279ef134e7de60/kernels_data-0.14.1-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:71178b60a4e65791d5421cdf4844e0be4cd0fb4f341051a491cfbe94afc765f0", size = 1176707, upload-time = "2026-05-14T06:40:49.605Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/3b/28/a3b063047af38c17c13e5938cbe1979e2daaaa094a2f44cfc21ac7b7fc19/kernels_data-0.14.1-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:f432b770b22039fa357be6252889ed823b72e753ced9d543ba514b4fe8601e0b", size = 1338286, upload-time = "2026-05-14T06:41:02.1Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/87/ea/fe955e157094d93fe20919441dc709ba7afbcf933de5896b546d5c217938/kernels_data-0.14.1-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:ec694ae26ed8569f613e5cd4269222210cb57b1c16cf8b0c5acbf0082324804f", size = 1414055, upload-time = "2026-05-14T06:41:14.424Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kimina"
|
||||
version = "0.1.0"
|
||||
@@ -3006,10 +3020,39 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/fa/06/7399a607f434119c6e1fdc8ec89a8d51ccccadf3341dee4ead6bd14caaf5/kiwisolver-1.5.0-graalpy312-graalpy250_312_native-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c31c13da98624f957b0fb1b5bae5383b2333c2c3f6793d9825dd5ce79b525cb7", size = 194295, upload-time = "2026-03-09T13:15:38.22Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kubernetes"
|
||||
version = "32.0.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
resolution-markers = [
|
||||
"platform_machine == 'x86_64' and sys_platform == 'linux'",
|
||||
"platform_machine == 'aarch64' and sys_platform == 'linux'",
|
||||
]
|
||||
dependencies = [
|
||||
{ name = "certifi" },
|
||||
{ name = "durationpy" },
|
||||
{ name = "google-auth" },
|
||||
{ name = "oauthlib" },
|
||||
{ name = "python-dateutil" },
|
||||
{ name = "pyyaml" },
|
||||
{ name = "requests" },
|
||||
{ name = "requests-oauthlib" },
|
||||
{ name = "six" },
|
||||
{ name = "urllib3" },
|
||||
{ name = "websocket-client" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/b7/e8/0598f0e8b4af37cd9b10d8b87386cf3173cb8045d834ab5f6ec347a758b3/kubernetes-32.0.1.tar.gz", hash = "sha256:42f43d49abd437ada79a79a16bd48a604d3471a117a8347e87db693f2ba0ba28", size = 946691, upload-time = "2025-02-18T21:06:34.148Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/08/10/9f8af3e6f569685ce3af7faab51c8dd9d93b9c38eba339ca31c746119447/kubernetes-32.0.1-py2.py3-none-any.whl", hash = "sha256:35282ab8493b938b08ab5526c7ce66588232df00ef5e1dbe88a419107dc10998", size = 1988070, upload-time = "2025-02-18T21:06:31.391Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kubernetes"
|
||||
version = "36.0.3"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
resolution-markers = [
|
||||
"platform_machine == 'arm64' and sys_platform == 'darwin'",
|
||||
]
|
||||
dependencies = [
|
||||
{ name = "aiohttp" },
|
||||
{ name = "certifi" },
|
||||
@@ -3270,18 +3313,20 @@ requires-dist = [{ name = "verifiers", specifier = ">=0.3.1" }]
|
||||
|
||||
[[package]]
|
||||
name = "mamba-ssm"
|
||||
version = "2.3.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
version = "2.3.2.post1"
|
||||
source = { git = "https://github.com/state-spaces/mamba?rev=f577286#f577286d052741c35d39cd43bdc3fad27120f22c" }
|
||||
dependencies = [
|
||||
{ name = "apache-tvm-ffi" },
|
||||
{ name = "einops" },
|
||||
{ name = "ninja" },
|
||||
{ name = "packaging" },
|
||||
{ name = "quack-kernels" },
|
||||
{ name = "setuptools" },
|
||||
{ name = "tilelang" },
|
||||
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" } },
|
||||
{ name = "transformers" },
|
||||
{ name = "triton" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/34/67/ec89aa703da194a813e35d2ea2de8f74a7ce6991a120a29f3a0c5e30d4b9/mamba_ssm-2.3.1.tar.gz", hash = "sha256:4d529477ad94753962216d583fc8f1c127c717b7d7c875d6bbb9376366d0d761", size = 121707, upload-time = "2026-03-10T09:27:34.798Z" }
|
||||
|
||||
[[package]]
|
||||
name = "markdown"
|
||||
@@ -3543,6 +3588,7 @@ dependencies = [
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/0e/4a/c27b42ed9b1c7d13d9ba8b6905dece787d6259152f2309338aed29b2447b/ml_dtypes-0.5.4.tar.gz", hash = "sha256:8ab06a50fb9bf9666dd0fe5dfb4676fa2b0ac0f31ecff72a6c3af8e22c063453", size = 692314, upload-time = "2025-11-17T22:32:31.031Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/a8/b8/3c70881695e056f8a32f8b941126cf78775d9a4d7feba8abcb52cb7b04f2/ml_dtypes-0.5.4-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:a174837a64f5b16cab6f368171a1a03a27936b31699d167684073ff1c4237dac", size = 676927, upload-time = "2025-11-17T22:31:48.182Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/54/0f/428ef6881782e5ebb7eca459689448c0394fa0a80bea3aa9262cba5445ea/ml_dtypes-0.5.4-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a7f7c643e8b1320fd958bf098aa7ecf70623a42ec5154e3be3be673f4c34d900", size = 5028464, upload-time = "2025-11-17T22:31:50.135Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/3a/cb/28ce52eb94390dda42599c98ea0204d74799e4d8047a0eb559b6fd648056/ml_dtypes-0.5.4-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9ad459e99793fa6e13bd5b7e6792c8f9190b4e5a1b45c63aba14a4d0a7f1d5ff", size = 5009002, upload-time = "2025-11-17T22:31:52.001Z" },
|
||||
]
|
||||
@@ -4963,6 +5009,7 @@ dependencies = [
|
||||
{ name = "prime" },
|
||||
{ name = "prime-pydantic-config" },
|
||||
{ name = "prime-rl-configs" },
|
||||
{ name = "prime-runs", extra = ["train"] },
|
||||
{ name = "psutil" },
|
||||
{ name = "pyarrow" },
|
||||
{ name = "pybase64" },
|
||||
@@ -4991,6 +5038,7 @@ all = [
|
||||
{ name = "flash-attn-3", marker = "sys_platform == 'linux'" },
|
||||
{ name = "flash-attn-4", marker = "sys_platform == 'linux'" },
|
||||
{ name = "flash-linear-attention", marker = "sys_platform == 'linux'" },
|
||||
{ name = "mamba-ssm", marker = "sys_platform == 'linux'" },
|
||||
{ name = "modelexpress", marker = "sys_platform == 'linux'" },
|
||||
{ name = "mooncake-transfer-engine", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nixl", marker = "sys_platform == 'linux'" },
|
||||
@@ -4998,7 +5046,7 @@ all = [
|
||||
{ name = "nvidia-ml-py", marker = "sys_platform == 'linux'" },
|
||||
{ name = "quack-kernels", marker = "sys_platform == 'linux'" },
|
||||
{ name = "ring-flash-attn", marker = "sys_platform == 'linux'" },
|
||||
{ name = "tilelang", marker = "sys_platform == 'linux'" },
|
||||
{ name = "tilelang" },
|
||||
{ name = "torch", version = "2.13.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
|
||||
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "torchao", version = "0.18.0+git5f2baf9d5", source = { 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 != 'x86_64' and sys_platform == 'linux'" },
|
||||
@@ -5026,6 +5074,9 @@ disagg = [
|
||||
{ name = "vllm-router", version = "0.2.0", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm-router", version = "0.2.0", source = { 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' and sys_platform == 'linux'" },
|
||||
]
|
||||
dynamo = [
|
||||
{ name = "ai-dynamo", marker = "sys_platform == 'linux'" },
|
||||
]
|
||||
flash-attn = [
|
||||
{ name = "flash-attn", version = "2.8.3+cu130torch2.13", source = { url = "https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.47/flash_attn-2.8.3+cu130torch2.13-cp312-cp312-linux_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "flash-attn", version = "2.8.3+cu130torch2.13", source = { url = "https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.48/flash_attn-2.8.3+cu130torch2.13-cp312-cp312-linux_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
|
||||
@@ -5036,18 +5087,16 @@ flash-attn-3 = [
|
||||
flash-attn-cute = [
|
||||
{ name = "flash-attn-4", marker = "sys_platform == 'linux'" },
|
||||
]
|
||||
gpt-oss = [
|
||||
{ name = "kernels", marker = "sys_platform == 'linux'" },
|
||||
]
|
||||
gpu = [
|
||||
{ name = "dion", marker = "sys_platform == 'linux'" },
|
||||
{ name = "flash-linear-attention", marker = "sys_platform == 'linux'" },
|
||||
{ name = "mamba-ssm", marker = "sys_platform == 'linux'" },
|
||||
{ name = "modelexpress", marker = "sys_platform == 'linux'" },
|
||||
{ name = "mooncake-transfer-engine", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nixl-cu13", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nvidia-ml-py", marker = "sys_platform == 'linux'" },
|
||||
{ name = "ring-flash-attn", marker = "sys_platform == 'linux'" },
|
||||
{ name = "tilelang", marker = "sys_platform == 'linux'" },
|
||||
{ name = "tilelang" },
|
||||
{ name = "torch", version = "2.13.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
|
||||
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "torchao", version = "0.18.0+git5f2baf9d5", source = { 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 != 'x86_64' and sys_platform == 'linux'" },
|
||||
@@ -5083,6 +5132,7 @@ mamba-ssm = [
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "ai-dynamo", marker = "sys_platform == 'linux' and extra == 'dynamo'", specifier = "==1.4.2" },
|
||||
{ name = "aiolimiter", specifier = ">=1.2.1" },
|
||||
{ name = "beartype", specifier = ">=0.21.0" },
|
||||
{ name = "datasets", specifier = ">=4.0.0" },
|
||||
@@ -5100,8 +5150,8 @@ requires-dist = [
|
||||
{ name = "flash-attn-4", marker = "sys_platform == 'linux' and extra == 'flash-attn-cute'", git = "https://github.com/Dao-AILab/flash-attention.git?subdirectory=flash_attn%2Fcute&rev=0251105" },
|
||||
{ name = "flash-linear-attention", marker = "sys_platform == 'linux' and extra == 'gpu'", git = "https://github.com/fla-org/flash-linear-attention" },
|
||||
{ name = "jaxtyping", specifier = ">=0.3.2" },
|
||||
{ name = "kernels", marker = "sys_platform == 'linux' and extra == 'gpt-oss'" },
|
||||
{ name = "loguru", specifier = ">=0.7.3" },
|
||||
{ name = "mamba-ssm", marker = "sys_platform == 'linux' and extra == 'gpu'", git = "https://github.com/state-spaces/mamba?rev=f577286" },
|
||||
{ name = "modelexpress", marker = "sys_platform == 'linux' and extra == 'gpu'", specifier = "==0.3.0" },
|
||||
{ name = "mooncake-transfer-engine", marker = "sys_platform == 'linux' and extra == 'gpu'", specifier = ">=0.3.10.post2" },
|
||||
{ name = "msgspec", specifier = ">=0.18" },
|
||||
@@ -5126,6 +5176,7 @@ requires-dist = [
|
||||
{ name = "prime-rl", extras = ["gpu"], marker = "extra == 'all'" },
|
||||
{ name = "prime-rl", extras = ["quack"], marker = "extra == 'all'" },
|
||||
{ name = "prime-rl-configs", editable = "packages/prime-rl-configs" },
|
||||
{ name = "prime-runs", extras = ["train"], specifier = ">=0.1.1" },
|
||||
{ name = "psutil", specifier = ">=7.0.0" },
|
||||
{ name = "pyarrow", specifier = ">=21.0.0" },
|
||||
{ name = "pybase64", specifier = ">=1.4.2" },
|
||||
@@ -5159,7 +5210,7 @@ requires-dist = [
|
||||
{ name = "wandb", specifier = ">=0.26.1" },
|
||||
{ name = "wandb-workspaces", specifier = ">=0.4.3" },
|
||||
]
|
||||
provides-extras = ["gpu", "dashboard", "flash-attn", "flash-attn-3", "flash-attn-cute", "disagg", "gpt-oss", "quack", "kernels", "all"]
|
||||
provides-extras = ["gpu", "dashboard", "dynamo", "flash-attn", "flash-attn-3", "flash-attn-cute", "disagg", "quack", "kernels", "all"]
|
||||
|
||||
[package.metadata.requires-dev]
|
||||
dev = [
|
||||
@@ -5171,7 +5222,7 @@ dev = [
|
||||
{ name = "pytest-asyncio", specifier = ">=0.23" },
|
||||
{ name = "ruff", specifier = ">=0.12.1" },
|
||||
]
|
||||
mamba-ssm = [{ name = "mamba-ssm", marker = "sys_platform == 'linux'", specifier = ">=2.3.0" }]
|
||||
mamba-ssm = [{ name = "mamba-ssm", marker = "sys_platform == 'linux'", git = "https://github.com/state-spaces/mamba?rev=f577286" }]
|
||||
|
||||
[[package]]
|
||||
name = "prime-rl-configs"
|
||||
@@ -5196,6 +5247,24 @@ requires-dist = [
|
||||
{ name = "verifiers", specifier = ">=0.3.0" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prime-runs"
|
||||
version = "0.1.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "httpx" },
|
||||
{ name = "prime-traces" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/85/db/3d5a9362f0d373d10145eaee3ac255cf227bf4164b36d04119b18e226607/prime_runs-0.1.1.tar.gz", hash = "sha256:0be97dcc95b3f1648ca25475efa45a5892fb12a775bf1f61728baec73a0088bb", size = 61110, upload-time = "2026-09-04T17:01:33.379Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/84/52/3fa41ac5e3c8bfa8eb33520f86634ae56474228f85c59b16aa04875efd7d/prime_runs-0.1.1-py3-none-any.whl", hash = "sha256:d512753ff84159a1234d1ea93091857f0a59fba12ef7ab2f69bfb579deb5ce75", size = 43006, upload-time = "2026-09-04T17:01:31.821Z" },
|
||||
]
|
||||
|
||||
[package.optional-dependencies]
|
||||
train = [
|
||||
{ name = "pyarrow" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prime-sandboxes"
|
||||
version = "0.2.39"
|
||||
@@ -5215,6 +5284,19 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/db/a5/8a2a1aefecfc58ca926d6b21e8302a127884bf2a45952ed390b5f702eeda/prime_sandboxes-0.2.39-py3-none-any.whl", hash = "sha256:3ea355158473c1697f9ef6ec2a07f3189e9a2555c80d1c88e1f7e22979772e0a", size = 58161, upload-time = "2026-08-19T23:09:26.69Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prime-traces"
|
||||
version = "0.0.3"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "httpx" },
|
||||
{ name = "pydantic" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/8c/77/13fa99c0fb71909f2f35d048d9724efb9ae432484e47f12386b1542815e8/prime_traces-0.0.3.tar.gz", hash = "sha256:4071833db77a606ccbb718e5c73f2dfaf63982fe801aa096daed0bc605da554f", size = 50874, upload-time = "2026-08-27T19:46:44.672Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/ce/9a/5a917de29a3a839c0ba36d445e3af562f744d9716b509571be643a01476c/prime_traces-0.0.3-py3-none-any.whl", hash = "sha256:0838f60651f1ed38371e383bd88b954e461d20ac424874e694bc83358934f5f3", size = 38345, upload-time = "2026-08-27T19:46:43.396Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prime-tunnel"
|
||||
version = "0.1.10"
|
||||
@@ -7065,7 +7147,9 @@ dependencies = [
|
||||
{ name = "ml-dtypes" },
|
||||
{ name = "numpy" },
|
||||
{ name = "psutil" },
|
||||
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" } },
|
||||
{ name = "setuptools", marker = "sys_platform != 'linux'" },
|
||||
{ name = "torch", version = "2.13.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
|
||||
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" }, marker = "sys_platform == 'linux'" },
|
||||
{ name = "torch-c-dlpack-ext" },
|
||||
{ name = "tqdm" },
|
||||
{ name = "typing-extensions" },
|
||||
@@ -7073,6 +7157,7 @@ dependencies = [
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/6d/9a/5776adb5b6e03e141c8cff020e16c45b87c9b7a7a5bdfe83416d6cc23933/tilelang-0.1.12.tar.gz", hash = "sha256:595b39581d099a53f875bd8d553863e7e4f58998052b58764f5472cbfbb87043", size = 93565090, upload-time = "2026-07-08T04:22:52.901Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/13/51/4ae1fb532406082a4ebf16c890f5f98db14b8588f2c486334ba23578b4bc/tilelang-0.1.12-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:8741d6cd519782645d55c17abd8986402c62948bc2122d3417c445d11de5dd16", size = 38347295, upload-time = "2026-07-08T04:22:35.691Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d1/53/f281a0bd9ee7e03d6a97828fc0e443321ed26ea2b0bd74bf9f1d9451d30f/tilelang-0.1.12-cp38-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bbeb5573cbe2544a51a5c9a6cc737c5e3b5c2d95411caa3687fd9b08eb9d5f97", size = 50501074, upload-time = "2026-07-08T04:22:39.973Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/fb/a4/ff0b14d00d29fe418063cd97490f55aa9cad6f981a6fbbf29124b024637d/tilelang-0.1.12-cp38-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:a1701eba4ad603d73f1b128b88f6a2350f1b1161729e5b2d1e540a1ec7a82d52", size = 46281933, upload-time = "2026-07-08T04:22:44.244Z" },
|
||||
]
|
||||
@@ -7161,15 +7246,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/c7/18/c86eb8e0202e32dd3df50d43d7ff9854f8e0603945ff398974c1d91ac1ef/tomli_w-1.2.0-py3-none-any.whl", hash = "sha256:188306098d013b691fcadc011abd66727d3c414c571bb01b1a174ba8c983cf90", size = 6675, upload-time = "2025-01-15T12:07:22.074Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tomlkit"
|
||||
version = "0.14.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/c3/af/14b24e41977adb296d6bd1fb59402cf7d60ce364f90c890bd2ec65c43b5a/tomlkit-0.14.0.tar.gz", hash = "sha256:cf00efca415dbd57575befb1f6634c4f42d2d87dbba376128adb42c121b87064", size = 187167, upload-time = "2026-01-13T01:14:53.304Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/b5/11/87d6d29fb5d237229d67973a6c9e06e048f01cf4994dee194ab0ea841814/tomlkit-0.14.0-py3-none-any.whl", hash = "sha256:592064ed85b40fa213469f81ac584f67a4f2992509a7c3ea2d632208623a3680", size = 39310, upload-time = "2026-01-13T01:14:51.965Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "torch"
|
||||
version = "2.13.0"
|
||||
@@ -7224,10 +7300,12 @@ name = "torch-c-dlpack-ext"
|
||||
version = "0.1.5"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" } },
|
||||
{ name = "torch", version = "2.13.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
|
||||
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" }, marker = "sys_platform == 'linux'" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/37/de/921b6491efce5c389a5ef9bbed3d2d6660005840dae488124173180859ab/torch_c_dlpack_ext-0.1.5.tar.gz", hash = "sha256:d06f0357d575d22a168cc77acb9020fc4bae30968ceb6718a055dcbe92bacabe", size = 12913, upload-time = "2026-01-12T11:25:08.484Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/b1/67/10d236698525d7b7db4d74ec0a4b01f5b2db33968995fdd9ac6b4635e327/torch_c_dlpack_ext-0.1.5-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:c0f2bd51fcd99c0e5b50314e1985f2728c4941bfa821f065e6c30951d1f995ca", size = 5291237, upload-time = "2026-01-12T11:24:44.011Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/87/06/8d760997307a5c3be4384424667bf31aae0a42060838c532c7d846516175/torch_c_dlpack_ext-0.1.5-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3562ee411258676f9c38b8ad39306d1c8d027b6a86f6a87c920d2d009a9d1510", size = 443069, upload-time = "2026-01-12T11:24:45.451Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e2/79/a914539b4785f3e44f891aa012a886edb8bc10fe081c440981c57543ce21/torch_c_dlpack_ext-0.1.5-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e6f9da4bb9af70e27facc777458be62e10dbbbddda7672d16138db0553c5a524", size = 897846, upload-time = "2026-01-12T11:24:48.168Z" },
|
||||
]
|
||||
@@ -7715,6 +7793,7 @@ dependencies = [
|
||||
{ name = "numpy" },
|
||||
{ name = "openai" },
|
||||
{ name = "prime-pydantic-config", extra = ["toml"] },
|
||||
{ name = "prime-runs" },
|
||||
{ name = "prime-sandboxes" },
|
||||
{ name = "prime-tunnel" },
|
||||
{ name = "pydantic" },
|
||||
@@ -7756,6 +7835,7 @@ requires-dist = [
|
||||
{ name = "openai", specifier = ">=2.54.0,<3.0.0" },
|
||||
{ name = "openenv", marker = "extra == 'openenv'", specifier = ">=0.4.1" },
|
||||
{ name = "prime-pydantic-config", extras = ["toml"], specifier = ">=0.4.3" },
|
||||
{ name = "prime-runs", specifier = ">=0.1.1" },
|
||||
{ name = "prime-sandboxes", specifier = ">=0.2.39" },
|
||||
{ name = "prime-tunnel", specifier = ">=0.1.8" },
|
||||
{ name = "pydantic", specifier = ">=2.12.3" },
|
||||
@@ -8580,6 +8660,7 @@ version = "4.15.4.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/8a/8e/0c8f17309549d2e5cde9a3ccefa6365437f1e7bafe71878eaf9478e47b18/z3_solver-4.15.4.0.tar.gz", hash = "sha256:928c29b58c4eb62106da51c1914f6a4a55d0441f8f48a81b9da07950434a8946", size = 5018600, upload-time = "2025-10-29T18:12:03.062Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/63/33/a3d5d2eaeb0f7b3174d57d405437eabb2075d4d50bd9ea0957696c435c7b/z3_solver-4.15.4.0-py3-none-macosx_13_0_arm64.whl", hash = "sha256:407e825cc9211f95ef46bdc8d151bf630e7ab2d62a21d24cd74c09cc5b73f3aa", size = 37052538, upload-time = "2025-10-29T18:11:46.233Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/21/c9/bb51a96af0091324c81b803f16c49f719f9f6ea0b0bb52200f5c97ec4892/z3_solver-4.15.4.0-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7e103a6f203f505b8b8b8e5c931cc407c95b61556512d4921c1ddc0b3f41b08e", size = 29268352, upload-time = "2025-10-29T18:11:53.032Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/bf/2e/0b49f7e4e53817cfb09a0f6585012b782dfe0b666e8abefcb4fac0570606/z3_solver-4.15.4.0-py3-none-manylinux_2_34_aarch64.whl", hash = "sha256:62c7e9cbdd711932301f29919ad9158de9b2f58b4d281dd259bbcd0a2f408ba1", size = 27226534, upload-time = "2025-10-29T18:11:55.59Z" },
|
||||
]
|
||||
@@ -8592,3 +8673,17 @@ sdist = { url = "https://files.pythonhosted.org/packages/b9/d8/eab98a517c14134c0
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/3a/13/547360d81e6d88d58492968ffda9f9542854f11310ee556fef14260cc886/zipp-4.1.0-py3-none-any.whl", hash = "sha256:25ad4e16390cd314347dd8f1de67a2ac538ae658ed4ab9db16029c07c188e97f", size = 10238, upload-time = "2026-05-18T20:08:57.045Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zstandard"
|
||||
version = "0.25.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/fd/aa/3e0508d5a5dd96529cdc5a97011299056e14c6505b678fd58938792794b1/zstandard-0.25.0.tar.gz", hash = "sha256:7713e1179d162cf5c7906da876ec2ccb9c3a9dcbdffef0cc7f70c3667a205f0b", size = 711513, upload-time = "2025-09-14T22:15:54.002Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/1e/15/efef5a2f204a64bdb5571e6161d49f7ef0fffdbca953a615efbec045f60f/zstandard-0.25.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:6dffecc361d079bb48d7caef5d673c88c8988d3d33fb74ab95b7ee6da42652ea", size = 5063012, upload-time = "2025-09-14T22:17:01.156Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/53/60/7be26e610767316c028a2cbedb9a3beabdbe33e2182c373f71a1c0b88f36/zstandard-0.25.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:5a56ba0db2d244117ed744dfa8f6f5b366e14148e00de44723413b2f3938a902", size = 5546993, upload-time = "2025-09-14T22:17:06.781Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/85/c7/3483ad9ff0662623f3648479b0380d2de5510abf00990468c286c6b04017/zstandard-0.25.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:10ef2a79ab8e2974e2075fb984e5b9806c64134810fac21576f0668e7ea19f8f", size = 5046806, upload-time = "2025-09-14T22:17:08.415Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/08/b3/206883dd25b8d1591a1caa44b54c2aad84badccf2f1de9e2d60a446f9a25/zstandard-0.25.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:aaf21ba8fb76d102b696781bddaa0954b782536446083ae3fdaa6f16b25a1c4b", size = 5576659, upload-time = "2025-09-14T22:17:10.164Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/9d/31/76c0779101453e6c117b0ff22565865c54f48f8bd807df2b00c2c404b8e0/zstandard-0.25.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:1869da9571d5e94a85a5e8d57e4e8807b175c9e4a6294e3b66fa4efb074d90f6", size = 4953933, upload-time = "2025-09-14T22:17:11.857Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/fc/5f/75aafd4b9d11b5407b641b8e41a57864097663699f23e9ad4dbb91dc6bfe/zstandard-0.25.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:474d2596a2dbc241a556e965fb76002c1ce655445e4e3bf38e5477d413165ffa", size = 5360237, upload-time = "2025-09-14T22:17:19.954Z" },
|
||||
]
|
||||
|
||||
Reference in New Issue
Block a user