Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3587b285f5 | ||
|
|
f3827c4ed2 | ||
|
|
93a0fe0d6b | ||
|
|
db2c00e9ed | ||
|
|
4250d895bc | ||
|
|
78bc69ccc4 | ||
|
|
81052082a9 | ||
|
|
b9c0bfe87b | ||
|
|
51879014fc | ||
|
|
52e985ae9d | ||
|
|
63b3e85864 | ||
|
|
7133f8f8f2 | ||
|
|
b029ef253e | ||
|
|
eae8bd9462 |
@@ -13,7 +13,7 @@ concurrency:
|
||||
jobs:
|
||||
unit-tests:
|
||||
name: Unit tests
|
||||
runs-on: vm
|
||||
runs-on: prime-rl-2xh200
|
||||
container:
|
||||
image: pytorch/pytorch:2.10.0-cuda13.0-cudnn9-devel
|
||||
options: --gpus all
|
||||
@@ -61,34 +61,34 @@ jobs:
|
||||
matrix:
|
||||
include:
|
||||
- test: reverse_text_sft
|
||||
runner: vm
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_reverse_text_sft.py"
|
||||
- test: reverse_text_sft_lora
|
||||
runner: vm
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_reverse_text_sft_lora.py"
|
||||
- test: reverse_text
|
||||
runner: vm
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_reverse_text.py"
|
||||
- test: reverse_text_rl_opd
|
||||
runner: vm
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_reverse_text_rl_opd.py"
|
||||
- test: reverse_text_rl_sft
|
||||
runner: vm
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_reverse_text_rl_sft.py"
|
||||
- test: alphabet_sort
|
||||
runner: vm
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_alphabet_sort.py"
|
||||
- test: reverse_text_lora
|
||||
runner: vm
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_reverse_text_lora.py"
|
||||
- test: reverse_text_moe
|
||||
runner: vm
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_reverse_text_moe.py"
|
||||
- test: benchmark_regression
|
||||
runner: 4xa6000
|
||||
pytest_args: "tests/integration/test_benchmark_regression.py"
|
||||
- test: gsm8k_eval
|
||||
runner: vm
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_gsm8k_eval.py"
|
||||
steps:
|
||||
- name: Install Git
|
||||
|
||||
+5
-2
@@ -94,7 +94,7 @@ ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
|
||||
# The runtime dependency image contains no first-party source or editable installs.
|
||||
COPY --from=manifests /manifests /app
|
||||
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
|
||||
uv sync --all-packages --extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --locked --no-dev \
|
||||
uv sync --all-packages --extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra flash-mla --extra disagg --extra quack --extra kernels --locked --no-dev \
|
||||
--no-install-local
|
||||
|
||||
# Build NIXL from source against the UCX 1.19 baked above. The PyPI nixl wheel
|
||||
@@ -243,7 +243,10 @@ COPY --from=builder --chown=appuser:appuser \
|
||||
--exclude=lib/python3.12/site-packages/flash_attn \
|
||||
--exclude=lib/python3.12/site-packages/flash_attn_2_cuda*.so \
|
||||
/app/.venv /app/.venv
|
||||
RUN /app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]'
|
||||
RUN /app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]' \
|
||||
&& if [ "$(uname -m)" = "x86_64" ]; then \
|
||||
/app/.venv/bin/python -c 'from importlib.metadata import version; version("flash-mla")'; \
|
||||
fi
|
||||
|
||||
# Place executables in the environment at the front of the path
|
||||
ENV PATH="/app/.venv/bin:$PATH"
|
||||
|
||||
Vendored
+1
-1
Submodule deps/verifiers updated: 4fd5921071...7ba657f2a4
+1
-1
@@ -187,7 +187,7 @@ dropout = 0.0
|
||||
|
||||
`target_modules` defaults to a reasonable cross-family set (`q_proj`, `k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj`, `experts`, plus a few latent-projection names for Nemotron). Unknown names are silently ignored, so the defaults work across architectures. Add architecture-specific names to extend coverage (e.g. `in_proj` / `out_proj` for Mamba).
|
||||
|
||||
LoRA is supported across SFT and RL. NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. Broadcast dirs of LoRA runs contain the raw adapter (`adapter_model.safetensors` + `adapter_config.json`).
|
||||
LoRA is supported across SFT and RL. NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. Broadcast dirs of LoRA runs contain the raw adapter (`adapter_model.safetensors` + `adapter_config.json`). With LoRA on, the inference server registers the adapter under the model name and serves the base model as `<model>-base`.
|
||||
|
||||
## Disaggregated Prefill/Decode Inference
|
||||
|
||||
|
||||
@@ -25,6 +25,8 @@ uv run eval gsm8k -n 32 -r 4 -c 8 # Prime Infe
|
||||
uv run eval @ configs/debug/eval/single-turn.toml # the same shape as a TOML
|
||||
```
|
||||
|
||||
The default endpoint comes from `PRIME_INFERENCE_URL`, then the Prime CLI's `inference_url`, then the standard Prime Inference URL. An explicit `client.base_url` wins. API keys and environment-backed headers are resolved when clients are built; Prime CLI credential and team fallbacks apply only to Prime Inference hosts, including for a separate admin URL.
|
||||
|
||||
To evaluate a model you serve yourself, start a `uv run inference` vLLM server (or any OpenAI-compatible API) and point the client at it:
|
||||
|
||||
```bash
|
||||
|
||||
+2
-2
@@ -287,7 +287,7 @@ On the CLI the same keys are available as `--inference.vllm.max-num-seqs 256` (o
|
||||
|
||||
Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer↔inference mismatch by an order of magnitude, resulting in more stable training.
|
||||
|
||||
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. Standard deployments use the V2 model runner. Disaggregated P/D remains on V1 because NIXL routed-expert stitching is V1-only.
|
||||
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. Capture runs on vLLM's V2 model runner (forced automatically). Router replay is not supported with disaggregated P/D: vLLM does not capture routed experts across NIXL KV transfer.
|
||||
|
||||
```toml
|
||||
[trainer]
|
||||
@@ -313,6 +313,6 @@ top_k = 512 # optional, defaults to 512 under truncation (bounds each sampling
|
||||
|
||||
That's all — there are no replay flags. Truncated train sampling makes the inference server return sampling masks (`inference.enable_return_sampling_mask`, auto-enabled), and the trainer replays them. Train-sampling `top_k` above 512 is rejected: the trainer pads each micro batch to its largest sampling mask, so the bound caps trainer memory. Configs that would break under renormalized logprobs are rejected: `opd`/`opsd` and truncation knobs smuggled via `extra_body`. Frozen-source envs are exempt.
|
||||
|
||||
Capture runs on vLLM's V2 model runner (forced automatically) and is engine-wide. It can run with router replay on standard deployments. The combination is not supported with disaggregated P/D because NIXL routed-expert capture uses V1. While sampling capture is on, vLLM rejects any request with `temperature <= 0` or without an effective `top_k > 0` — eval sampling against the training server must set `top_k` (the model's generation config often supplies one) and a non-zero temperature.
|
||||
Capture runs on vLLM's V2 model runner (forced automatically) and is engine-wide. It can run together with router replay. While sampling capture is on, vLLM rejects any request with `temperature <= 0` or without an effective `top_k > 0` — eval sampling against the training server must set `top_k` (the model's generation config often supplies one) and a non-zero temperature.
|
||||
|
||||
When launching the inference server standalone, set `inference.enable_return_sampling_mask = true` yourself; clients must sample with `0 < top_k <= 512`.
|
||||
|
||||
@@ -62,6 +62,7 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
|
||||
| `orchestrator.train.group_size` | Rollouts generated per task. |
|
||||
| `orchestrator.max_off_policy_steps` | Maximum staleness of a trained rollout (default 8): the version a batch trains on minus the oldest version that generated the rollout, queue time included. Episodes past the bound are dropped; a group shares one dispatch version, so its episodes age out together. The main off-policy dial on long agentic rollouts — bump for throughput, lower for tighter on-policyness. Watch `off_policy/*` and `mismatch_kl/all/mean` when tuning. |
|
||||
| `[orchestrator.train.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `rae`, `hierarchical_grpo`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
|
||||
| `trainer.model.freeze_moe_router` | Freeze MoE router gates (default `true` for RL, `false` for SFT). Router updates in RL shift the trainer's expert choices away from the ones inference sampled, amplifying the train-inference mismatch, so RL keeps the pretrained router. Set `false` to train it. |
|
||||
| `[[orchestrator.train.source]]` | Training sources. List multiple tables for multi-env training; weight them via `ratio`. See [Configuration § Training sources](configuration.md#training-sources-orchestratortrainsource). |
|
||||
| `[[orchestrator.eval.source]]` + `orchestrator.eval.interval` | Eval environments and cadence (default every 100 steps). |
|
||||
|
||||
|
||||
@@ -40,11 +40,11 @@ import verifiers.v1 as vf
|
||||
from pydantic import Field, model_validator
|
||||
from renderers import AutoRendererConfig, RendererConfig
|
||||
|
||||
from prime_rl.configs.shared import ClientConfig
|
||||
from prime_rl.configs.shared import VLLMClientConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
|
||||
|
||||
class FrozenModelConfig(ClientConfig):
|
||||
class FrozenModelConfig(VLLMClientConfig):
|
||||
"""An externally hosted model behind an OpenAI-compatible endpoint: the
|
||||
client config plus the served model's ``name``.
|
||||
|
||||
@@ -57,14 +57,7 @@ class FrozenModelConfig(ClientConfig):
|
||||
name: str
|
||||
"""Served model name, sent as the ``model`` field of every request."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def require_explicit_endpoint(self):
|
||||
if "base_url" not in self.model_fields_set:
|
||||
raise ValueError(
|
||||
"a frozen model reference needs base_url — frozen models are externally "
|
||||
"hosted; prime-rl only ever hosts the trainable policy."
|
||||
)
|
||||
return self
|
||||
base_url: str
|
||||
|
||||
|
||||
ModelReference: TypeAlias = Literal["policy"] | FrozenModelConfig
|
||||
|
||||
@@ -6,7 +6,14 @@ from pydantic import AliasChoices, Field, model_validator
|
||||
|
||||
from prime_rl.configs.monitors import EvalMonitorsConfig
|
||||
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalSourcesConfig, ScheduledEvalConfig
|
||||
from prime_rl.configs.shared import ClientConfig, HeartbeatConfig, LogConfig, RunConfig, WeightBroadcastConfig
|
||||
from prime_rl.configs.shared import (
|
||||
ClientConfig,
|
||||
HeartbeatConfig,
|
||||
LogConfig,
|
||||
RunConfig,
|
||||
VLLMClientConfig,
|
||||
WeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.utils.config import default_output_dir
|
||||
|
||||
|
||||
@@ -14,7 +21,7 @@ class ServedEvalConfig(EvalSourcesConfig):
|
||||
"""Eval sources run against a live inference server: the server's client and the
|
||||
adaptive concurrency band."""
|
||||
|
||||
client: ClientConfig = ClientConfig()
|
||||
client: VLLMClientConfig = Field(default_factory=VLLMClientConfig)
|
||||
"""Client of the inference server evals run against."""
|
||||
|
||||
concurrency: ConcurrencyConfig = ConcurrencyConfig()
|
||||
@@ -43,9 +50,6 @@ class ServedEvalConfig(EvalSourcesConfig):
|
||||
return {("eval", source.resolved_name): source.serve.address for source in self.source}
|
||||
|
||||
|
||||
PRIME_INFERENCE_URL = "https://api.pinference.ai/api/v1"
|
||||
|
||||
|
||||
class EvalConfig(ServedEvalConfig):
|
||||
"""``uv run eval``: evaluate the configured sources once against a live inference
|
||||
server, then exit. Every source's env server is spawned by the eval process unless
|
||||
@@ -55,7 +59,7 @@ class EvalConfig(ServedEvalConfig):
|
||||
model: str = Field("deepseek/deepseek-v4.1-flash", validation_alias=AliasChoices("model", "m"))
|
||||
"""Model id — the ``model`` field of every eval request and the startup model check."""
|
||||
|
||||
client: ClientConfig = ClientConfig(base_url=PRIME_INFERENCE_URL, api_key_var="PRIME_API_KEY")
|
||||
client: ClientConfig = Field(default_factory=ClientConfig)
|
||||
"""Client of the inference server. Defaults to Prime Inference."""
|
||||
|
||||
select: vf.SelectCLIConfig = vf.SelectCLIConfig()
|
||||
|
||||
@@ -509,16 +509,12 @@ class InferenceConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_disaggregated_combined_replay(self):
|
||||
"""NIXL routed-expert capture uses the V1 runner, while sampling replay needs V2."""
|
||||
if (
|
||||
self.deployment.type == "disaggregated"
|
||||
and self.enable_return_sampling_mask
|
||||
and self.vllm.enable_return_routed_experts
|
||||
):
|
||||
def validate_disaggregated_no_routed_experts(self):
|
||||
"""vLLM rejects routed-expert capture with NIXL KV transfer."""
|
||||
if self.deployment.type == "disaggregated" and self.vllm.enable_return_routed_experts:
|
||||
raise ValueError(
|
||||
"Combined router and sampling replay is not supported with disaggregated P/D: "
|
||||
"NIXL routed-expert capture uses the V1 model runner, while sampling replay needs V2."
|
||||
"Routed-expert return (enable_return_routed_experts) is not supported with disaggregated P/D: "
|
||||
"vLLM does not capture routed experts across NIXL KV transfer."
|
||||
)
|
||||
return self
|
||||
|
||||
@@ -662,6 +658,11 @@ class InferenceConfig(BaseConfig):
|
||||
if self.enable_return_sampling_mask:
|
||||
namespace.return_sampling_mask = True
|
||||
|
||||
# The LoRA adapter is registered under the model name clients send, and vLLM rejects
|
||||
# an adapter named like a served base model, so serve the base under another name.
|
||||
if self.vllm.enable_lora and "served_model_name" not in extra_fields:
|
||||
namespace.served_model_name = [f"{self.vllm.model}-base"]
|
||||
|
||||
kv_transfer_config = self.build_kv_transfer_config()
|
||||
if kv_transfer_config is not None:
|
||||
namespace.kv_transfer_config = kv_transfer_config
|
||||
|
||||
@@ -14,13 +14,13 @@ from prime_rl.configs.algorithm import (
|
||||
from prime_rl.configs.monitors import TrainMonitorsConfig
|
||||
from prime_rl.configs.shared import (
|
||||
BaseModelConfig,
|
||||
ClientConfig,
|
||||
EnvVars,
|
||||
FileSystemWeightBroadcastConfig,
|
||||
HeartbeatConfig,
|
||||
LogConfig,
|
||||
ResumeConfig,
|
||||
TransportConfig,
|
||||
VLLMClientConfig,
|
||||
WeightBroadcastConfig,
|
||||
ZMQTransportConfig,
|
||||
)
|
||||
@@ -40,7 +40,7 @@ class ModelConfig(BaseModelConfig):
|
||||
lora: LoRAConfig | None = None
|
||||
"""Per-run LoRA configuration. If None, LoRA is disabled."""
|
||||
|
||||
client: ClientConfig = ClientConfig()
|
||||
client: VLLMClientConfig = Field(default_factory=VLLMClientConfig)
|
||||
"""Client of the live deployment (``[orchestrator.model.client]``)."""
|
||||
|
||||
|
||||
|
||||
@@ -595,17 +595,17 @@ class RLConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_disaggregated_combined_replay(self):
|
||||
def validate_disaggregated_no_routed_experts(self):
|
||||
"""Runs after ``auto_setup_router_replay``, which sets the inference flag after InferenceConfig's validators."""
|
||||
inference = self.inference
|
||||
if (
|
||||
inference is not None
|
||||
and inference.deployment.type == "disaggregated"
|
||||
and inference.enable_return_sampling_mask
|
||||
and inference.vllm.enable_return_routed_experts
|
||||
):
|
||||
raise ValueError(
|
||||
"Combined router and sampling replay is not supported with disaggregated P/D: "
|
||||
"NIXL routed-expert capture uses the V1 model runner, while sampling replay needs V2."
|
||||
"Router replay (inference.vllm.enable_return_routed_experts / trainer.enable_router_replay) "
|
||||
"is not supported with disaggregated P/D: vLLM does not capture routed experts across NIXL KV transfer."
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
@@ -283,6 +283,13 @@ class SFTConfig(BaseConfig):
|
||||
self.optim.weight_decay = 0.01
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_freeze_moe_router_auto(self):
|
||||
"""Resolve ``model.freeze_moe_router='auto'``: SFT trains the router."""
|
||||
if self.model.freeze_moe_router == "auto":
|
||||
self.model.freeze_moe_router = False
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_run_identity(self):
|
||||
"""Auto-generate the run name (``<dataset>--<model>--<short-id>``) when unset and
|
||||
|
||||
@@ -4,6 +4,7 @@ from pathlib import Path
|
||||
from typing import Annotated, Literal, TypeAlias
|
||||
|
||||
from pydantic import AfterValidator, Field, model_validator
|
||||
from verifiers.v1.configs.client import BaseClientConfig
|
||||
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
|
||||
@@ -212,22 +213,10 @@ class DynamoConfig(BaseConfig):
|
||||
"""Dynamo frontend URL used to discover inference workers for RL control."""
|
||||
|
||||
|
||||
class ClientConfig(BaseConfig):
|
||||
class ClientConfig(BaseClientConfig):
|
||||
wait_for_ready_timeout: int = 3600
|
||||
"""Seconds to wait at startup for the inference pool to become ready."""
|
||||
|
||||
base_url: str = "http://localhost:8000/v1"
|
||||
"""Base URL for the OpenAI API. For multi-replica deployments, point this at a router in front of the replicas."""
|
||||
|
||||
api_key_var: str = "VLLM_API_KEY"
|
||||
"""Environment variable name containing the API key, resolved via ``os.getenv``. Can be any string when the server is not protected by an API key; the same key is used for every URL."""
|
||||
|
||||
headers: dict[str, str] = {}
|
||||
"""Static headers sent with every request."""
|
||||
|
||||
headers_from_env: dict[str, str] = {}
|
||||
"""Maps HTTP header names to environment variable names; each entry is resolved via ``os.getenv`` and merged into request headers. e.g. ``{"X-Prime-Team-ID": "PRIME_TEAM_ID"}``."""
|
||||
|
||||
skip_model_check: bool = False
|
||||
"""Skip checking that the model is available in the inference pool. Useful for external APIs or keys that do not expose ``/models``."""
|
||||
|
||||
@@ -238,6 +227,13 @@ class ClientConfig(BaseConfig):
|
||||
"""Dynamo RL worker-discovery configuration."""
|
||||
|
||||
|
||||
class VLLMClientConfig(ClientConfig):
|
||||
"""Client defaults for the live inference deployment managed by training."""
|
||||
|
||||
base_url: str = "http://localhost:8000/v1"
|
||||
api_key_var: str = "VLLM_API_KEY"
|
||||
|
||||
|
||||
class LogConfig(BaseConfig):
|
||||
level: str = Field(default_factory=lambda: os.environ.get("PRIME_LOG_LEVEL", "info"))
|
||||
"""Log level for the process. Defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``."""
|
||||
|
||||
@@ -332,8 +332,8 @@ class ModelConfig(BaseModelConfig):
|
||||
index_cache: IndexCacheConfig | None = None
|
||||
"""DSA IndexCache sub-configuration. If set, sparse-attention top-k indices are reused across decoder layers per the configured schedule (mirrors vLLM's IndexCache HF overrides). If None, every layer recomputes its own indices."""
|
||||
|
||||
freeze_moe_router: bool = False
|
||||
"""Freeze MoE router parameters during training."""
|
||||
freeze_moe_router: bool | Literal["auto"] = "auto"
|
||||
"""Freeze MoE router gate parameters. ``auto`` (default): ``True`` for RL, ``False`` for SFT; a no-op on non-MoE models. Frozen routers get no optimizer state, so resuming a checkpoint saved with a frozen router with ``freeze_moe_router=false`` fails on missing DCP keys."""
|
||||
|
||||
lora: LoRAConfig | None = None
|
||||
"""LoRA configuration. If None, LoRA is disabled."""
|
||||
@@ -688,6 +688,13 @@ class TrainerConfig(BaseConfig):
|
||||
self.optim.weight_decay = 0.0
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_freeze_moe_router_auto(self):
|
||||
"""Resolve ``model.freeze_moe_router='auto'``: RL keeps the pretrained router."""
|
||||
if self.model.freeze_moe_router == "auto":
|
||||
self.model.freeze_moe_router = True
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def deepep_disables_grad_clipping(self):
|
||||
if self.model.ep != 1 and self.model.moe.dispatch.type == "deepep" and self.optim.max_norm is not None:
|
||||
|
||||
+7
-5
@@ -16,7 +16,7 @@ dependencies = [
|
||||
"wandb>=0.26.1",
|
||||
"wandb-workspaces>=0.4.3",
|
||||
"prime>=0.8.0",
|
||||
"prime-runs[train]>=0.1.3",
|
||||
"prime-runs[train]>=0.1.4",
|
||||
"pyzmq>=27.1.0",
|
||||
"aiolimiter>=1.2.1",
|
||||
"tenacity>=8.2.0",
|
||||
@@ -53,7 +53,7 @@ gpu = [
|
||||
"torchvision ; sys_platform == 'linux'",
|
||||
"torchaudio ; sys_platform == 'linux'",
|
||||
"torchdata>=0.11.0 ; sys_platform == 'linux'",
|
||||
"vllm>=0.30.0 ; sys_platform == 'linux'",
|
||||
"vllm>=0.31.0 ; sys_platform == 'linux'",
|
||||
"mooncake-transfer-engine>=0.3.10.post2 ; sys_platform == 'linux'",
|
||||
"ring-flash-attn>=0.1.8 ; sys_platform == 'linux'",
|
||||
"torchtitan ; sys_platform == 'linux'",
|
||||
@@ -147,7 +147,7 @@ override-dependencies = [
|
||||
# Shared by vLLM, TileLang, and the pinned FlashAttention 4 runtime.
|
||||
"apache-tvm-ffi==0.1.11",
|
||||
"nvidia-cudnn-cu13>=9.15 ; sys_platform == 'linux'",
|
||||
# vLLM 0.30.0 requires this exact CUTLASS DSL version and quack-kernels 0.6.5.
|
||||
# vLLM 0.31.0 requires this exact CUTLASS DSL version and quack-kernels 0.6.5.
|
||||
# Keep this pin aligned with quack-kernels and the flash-attn-4 revision below.
|
||||
"nvidia-cutlass-dsl==4.7.1",
|
||||
"transformers==5.6.2",
|
||||
@@ -229,6 +229,8 @@ requires-dist = [
|
||||
# bounded cutoff mirroring the one in deps/verifiers/pyproject.toml
|
||||
harbor = "2026-08-11T00:00:00Z"
|
||||
tokenspeed-mla = false
|
||||
# vLLM 0.31.0 pins flashinfer-python 0.7.0.post1, published inside the rolling window
|
||||
flashinfer-python = false
|
||||
fastokens = false
|
||||
flash_attn_3 = false
|
||||
# PrimeIntellect-published packages in this project's dependency closure —
|
||||
@@ -278,8 +280,8 @@ vllm-router = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.2/vllm_router-0.2.2-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
vllm = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.31.0/vllm-0.31.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.31.0/vllm-0.31.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
deep-ep = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
|
||||
@@ -113,7 +113,7 @@ HEAVY_PINS_PY
|
||||
echo "[prime-rl] syncing ${DEST} into /app/.venv"
|
||||
( cd "$DEST" && uv sync --inexact --locked --no-dev --all-packages \
|
||||
--extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 \
|
||||
--extra flash-attn-cute --extra disagg --extra quack --extra kernels )
|
||||
--extra flash-attn-cute --extra flash-mla --extra disagg --extra quack --extra kernels )
|
||||
# The chart's `uv run --no-sync <entrypoint>` commands resolve the
|
||||
# project from the cwd; the venv itself stays /app/.venv via
|
||||
# UV_PROJECT_ENVIRONMENT above.
|
||||
|
||||
@@ -7314,6 +7314,8 @@ $("#tm-messages").addEventListener(
|
||||
"scroll",
|
||||
(e) => {
|
||||
if (!e.target.matches?.("#replay-output") || !replay) return;
|
||||
// top and bottom coincide when the output fits; keep the mode Home/End chose
|
||||
if (e.target.scrollHeight - e.target.clientHeight < 24) return;
|
||||
const atBottom = e.target.scrollHeight - e.target.scrollTop - e.target.clientHeight < 24;
|
||||
replay.followOutput = atBottom;
|
||||
$("#replay-top")?.classList.toggle("active", !atBottom);
|
||||
|
||||
@@ -18,11 +18,9 @@ def apply_shared_vllm_patches():
|
||||
_patch_qwen35_moe_lora_format()
|
||||
monkey_patch_nano_v3_reasoning_parser()
|
||||
monkey_patch_minimax_m2_think_end_passthrough()
|
||||
monkey_patch_return_routed_experts_with_nixl_connector()
|
||||
monkey_patch_kv_xfer_finished_tolerate_freed()
|
||||
monkey_patch_online_fp8_parameter_cast()
|
||||
monkey_patch_deepseek_v4_allowed_layer_types()
|
||||
monkey_patch_deepseek_v4_request_tools_placement()
|
||||
monkey_patch_tokenize_params_validation()
|
||||
monkey_patch_strip_routed_experts_from_chat()
|
||||
monkey_patch_dp_coordinator_startup_timeout()
|
||||
@@ -49,64 +47,6 @@ def monkey_patch_deepseek_v4_allowed_layer_types():
|
||||
allow_deepseek_v4_layer_types()
|
||||
|
||||
|
||||
def monkey_patch_deepseek_v4_request_tools_placement():
|
||||
"""Attach request-level tools to the first existing DSV4 system message.
|
||||
|
||||
vLLM 0.29.0's Python DeepSeek-V4 tokenizer always prepends a synthetic
|
||||
system message for request-level tools. That puts the tool schema before
|
||||
an existing system prompt, unlike DeepSeek's reference encoder, vLLM's
|
||||
Rust renderer, and prime-rl's training renderer. Upstream fixed this in
|
||||
https://github.com/vllm-project/vllm/pull/51856 (commit 2909ad8f).
|
||||
The fix is expected to ship in vLLM 0.31.
|
||||
|
||||
Wrap the tokenizer factory so existing-system requests take the corrected
|
||||
path through the stock implementation: shallow-copy the conversation,
|
||||
attach tools to its first system message, and suppress the stock synthetic
|
||||
insertion. Requests without a system message retain the stock behavior.
|
||||
Remove this patch once the vLLM pin includes the upstream fix (likely 0.31).
|
||||
"""
|
||||
import copy
|
||||
|
||||
from vllm.tokenizers import deepseek_v4 as dsv4_tokenizer
|
||||
|
||||
original_get_tokenizer = dsv4_tokenizer.get_deepseek_v4_tokenizer
|
||||
if getattr(original_get_tokenizer, "_prime_rl_places_request_tools", False):
|
||||
return
|
||||
|
||||
def _get_deepseek_v4_tokenizer(tokenizer):
|
||||
wrapped = original_get_tokenizer(tokenizer)
|
||||
tokenizer_cls = wrapped.__class__
|
||||
original_apply_chat_template = tokenizer_cls.apply_chat_template
|
||||
|
||||
# Each factory call creates a fresh dynamic tokenizer subclass, but be
|
||||
# defensive if vLLM starts caching that class in a future release.
|
||||
if getattr(original_apply_chat_template, "_prime_rl_places_request_tools", False):
|
||||
return wrapped
|
||||
|
||||
def _apply_chat_template(self, messages, tools=None, **kwargs):
|
||||
if tools:
|
||||
conversation = kwargs.get("conversation", messages)
|
||||
system_idx = next(
|
||||
(i for i, message in enumerate(conversation) if message.get("role") == "system"),
|
||||
None,
|
||||
)
|
||||
if system_idx is not None:
|
||||
conversation = conversation.copy()
|
||||
conversation[system_idx] = copy.copy(conversation[system_idx])
|
||||
conversation[system_idx]["tools"] = tools
|
||||
kwargs["conversation"] = conversation
|
||||
tools = None
|
||||
|
||||
return original_apply_chat_template(self, messages, tools=tools, **kwargs)
|
||||
|
||||
_apply_chat_template._prime_rl_places_request_tools = True
|
||||
tokenizer_cls.apply_chat_template = _apply_chat_template
|
||||
return wrapped
|
||||
|
||||
_get_deepseek_v4_tokenizer._prime_rl_places_request_tools = True
|
||||
dsv4_tokenizer.get_deepseek_v4_tokenizer = _get_deepseek_v4_tokenizer
|
||||
|
||||
|
||||
def monkey_patch_online_fp8_parameter_cast():
|
||||
"""Pass plain tensors to vLLM's compiled block-FP8 caster.
|
||||
|
||||
@@ -243,51 +183,6 @@ def monkey_patch_minimax_m2_think_end_passthrough():
|
||||
minimax_m2.minimax_m2_config = _patched_config
|
||||
|
||||
|
||||
def monkey_patch_return_routed_experts_with_nixl_connector():
|
||||
from vllm.config.vllm import VllmConfig
|
||||
from vllm.logger import init_logger
|
||||
|
||||
logger = init_logger(__name__)
|
||||
original_post_init = VllmConfig.__post_init__
|
||||
|
||||
if getattr(original_post_init, "_prime_rl_allows_nixl_routed_experts", False):
|
||||
return
|
||||
|
||||
def _is_nixl_routed_experts_pd_config(config: VllmConfig) -> bool:
|
||||
kv_transfer_config = config.kv_transfer_config
|
||||
return (
|
||||
config.model_config is not None
|
||||
and config.model_config.enable_return_routed_experts
|
||||
and kv_transfer_config is not None
|
||||
and kv_transfer_config.kv_connector == "NixlConnector"
|
||||
and kv_transfer_config.is_kv_transfer_instance
|
||||
)
|
||||
|
||||
def _post_init(config: VllmConfig):
|
||||
if not _is_nixl_routed_experts_pd_config(config):
|
||||
return original_post_init(config)
|
||||
|
||||
if config.parallel_config.pipeline_parallel_size > 1:
|
||||
raise ValueError("--enable-return-routed-experts is incompatible with pipeline parallelism (PP > 1).")
|
||||
if config.use_v2_model_runner:
|
||||
raise ValueError(
|
||||
"Routed-expert capture with NIXL requires the V1 model runner. Set VLLM_USE_V2_MODEL_RUNNER=0."
|
||||
)
|
||||
|
||||
# vLLM rejects every KV connector, but our P/D path uses NIXL and
|
||||
# stitches prefill/decode routed experts in the router. CPU KV offload
|
||||
# remains rejected by prime-rl config validation.
|
||||
config.model_config.enable_return_routed_experts = False
|
||||
try:
|
||||
return original_post_init(config)
|
||||
finally:
|
||||
config.model_config.enable_return_routed_experts = True
|
||||
|
||||
_post_init._prime_rl_allows_nixl_routed_experts = True
|
||||
VllmConfig.__post_init__ = _post_init
|
||||
logger.warning("Enabled vLLM routed-experts capture with NIXL connector patch.")
|
||||
|
||||
|
||||
def monkey_patch_strip_routed_experts_from_chat():
|
||||
"""Drop routed_experts from chat-completions responses.
|
||||
|
||||
@@ -431,6 +326,7 @@ def _patch_lora_key_prefix():
|
||||
if skip_prefixes and cls._should_skip_module(lora_module, skip_prefixes):
|
||||
continue
|
||||
module_name, _ = parse_fine_tuned_lora_name(lora_module, weights_mapper)
|
||||
base_name = module_name.rsplit(".", 1)[-1]
|
||||
# Case for expert lora weights.
|
||||
## START PATCHED CODE (upstream only accepts the qualified form)
|
||||
if ".experts" in module_name:
|
||||
@@ -440,7 +336,7 @@ def _patch_lora_key_prefix():
|
||||
unexpected_modules.append(module_name)
|
||||
## END PATCHED CODE
|
||||
|
||||
elif module_name.rsplit(".", 1)[-1] not in expected_lora_modules:
|
||||
elif base_name not in expected_lora_modules and base_name not in (peft_helper.modules_to_save or ()):
|
||||
unexpected_modules.append(module_name)
|
||||
|
||||
if unexpected_modules:
|
||||
|
||||
@@ -10,15 +10,10 @@ def setup_vllm_env(config: InferenceConfig):
|
||||
# spawn is more robust in vLLM nightlies and Qwen3-VL (fork can deadlock with multithreaded processes)
|
||||
os.environ.setdefault("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
|
||||
|
||||
# Standard deployments use V2 for both capture modes. NIXL P/D also uses V2
|
||||
# for sampling-mask capture, but router replay remains on V1 because vLLM
|
||||
# rejects routed-expert capture with KV connectors and prime-rl's stitching
|
||||
# patch is V1-only. setdefault keeps an explicit env-var choice authoritative.
|
||||
if config.enable_return_sampling_mask:
|
||||
# vLLM captures sampling masks and routed experts only on the V2 model runner.
|
||||
# setdefault keeps an explicit env-var choice authoritative.
|
||||
if config.enable_return_sampling_mask or config.vllm.enable_return_routed_experts:
|
||||
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "1")
|
||||
elif config.vllm.enable_return_routed_experts:
|
||||
use_v2_runner = config.deployment.type != "disaggregated"
|
||||
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "1" if use_v2_runner else "0")
|
||||
|
||||
# vLLM 0.24.0 flipped VLLM_ENFORCE_STRICT_TOOL_CALLING's default to True, which
|
||||
# grammar-constrains generation (xgrammar structural tags) for tool_choice
|
||||
|
||||
@@ -62,14 +62,12 @@ async def load_lora_adapter(lora_request: LoadLoRAAdapterRequest, raw_request: R
|
||||
"""Wrapper around vLLM's /v1/load_lora_adapter.
|
||||
|
||||
prime-rl reloads a fixed-name adapter with fresh weights every step (the path
|
||||
changes per policy version; the name is constant — the base model name, which
|
||||
the adapter shadows: ``_maybe_get_adapters`` resolves ``lora_requests`` before
|
||||
the base-model match, so requests keep addressing one stable name. If a future
|
||||
vLLM rejects registering an adapter under a served model name, fall back to a
|
||||
distinct constant adapter name set once at startup.) vLLM's native loader
|
||||
rejects a same-name reload unless ``load_inplace=True``, so we force it here —
|
||||
that makes the worker re-read the new weights during ``add_lora``, reusing the
|
||||
existing ``lora_int_id``.
|
||||
changes per policy version; the name is constant — the model name every client
|
||||
sends. vLLM rejects an adapter named like a served base model, so with LoRA on
|
||||
the base model is served as ``<model>-base``; see ``InferenceConfig.to_namespace``.)
|
||||
vLLM's native loader rejects a same-name reload unless ``load_inplace=True``, so
|
||||
we force it here — that makes the worker re-read the new weights during
|
||||
``add_lora``, reusing the existing ``lora_int_id``.
|
||||
|
||||
We then reset the stored request's flag back to ``False``. ``load_inplace`` is
|
||||
a sticky field on the ``LoRARequest`` that ``_maybe_get_adapters`` hands to
|
||||
|
||||
@@ -66,7 +66,7 @@ class PrimeRlServingTokens(ServingTokens):
|
||||
request_metadata: RequestResponseMetadata,
|
||||
) -> ErrorResponse | GenerateResponse:
|
||||
routed_experts: _GenerateRoutedExpertsCapture | None = None
|
||||
if self.model_config.enable_return_routed_experts:
|
||||
if self.engine_client.vllm_config.aux_output_config.enable_return_routed_experts:
|
||||
routed_experts = _GenerateRoutedExpertsCapture(
|
||||
result_generator,
|
||||
start=request.sampling_params.routed_experts_prompt_start,
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
@@ -12,40 +11,19 @@ from httpx import AsyncClient
|
||||
from openai import AsyncOpenAI
|
||||
from renderers import RendererConfig
|
||||
from tenacity import AsyncRetrying, retry, retry_if_exception, stop_after_attempt, stop_after_delay, wait_exponential
|
||||
from verifiers.v1.configs.client import EvalClientConfig, TrainClientConfig
|
||||
from verifiers.v1.clients.base import build_async_openai
|
||||
from verifiers.v1.configs.client import (
|
||||
BaseClientConfig,
|
||||
EvalClientConfig,
|
||||
TrainClientConfig,
|
||||
resolve_api_key,
|
||||
resolve_headers,
|
||||
)
|
||||
|
||||
from prime_rl.configs.eval import PRIME_INFERENCE_URL
|
||||
from prime_rl.configs.shared import ClientConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
def resolve_api_key(api_key_var: str) -> str:
|
||||
"""The API key named by ``api_key_var``; ``PRIME_API_KEY`` also falls back to the prime
|
||||
CLI config (``prime login``), like the verifiers client does. ``"EMPTY"`` when unset."""
|
||||
api_key = os.environ.get(api_key_var)
|
||||
if not api_key and api_key_var == "PRIME_API_KEY":
|
||||
from prime_sandboxes import Config as PrimeConfig
|
||||
|
||||
api_key = PrimeConfig().api_key
|
||||
return api_key or "EMPTY"
|
||||
|
||||
|
||||
def resolve_headers(client_config: ClientConfig) -> dict[str, str]:
|
||||
"""The static headers plus those read from the environment. A Prime Inference client
|
||||
without a team header gets the team from ``$PRIME_TEAM_ID`` or the prime CLI config,
|
||||
like the verifiers client: a team's internal models are served only under it."""
|
||||
env_headers = {
|
||||
k: v for k, v in ((k, os.getenv(v)) for k, v in client_config.headers_from_env.items()) if v is not None
|
||||
}
|
||||
headers = {**client_config.headers, **env_headers}
|
||||
if client_config.base_url.startswith(PRIME_INFERENCE_URL) and "X-Prime-Team-ID" not in headers:
|
||||
from prime_sandboxes import Config as PrimeConfig
|
||||
|
||||
if team_id := os.environ.get("PRIME_TEAM_ID") or PrimeConfig().team_id:
|
||||
headers["X-Prime-Team-ID"] = team_id
|
||||
return headers
|
||||
|
||||
|
||||
class PrefillScorer:
|
||||
"""Prefill-scores token ids against a pool's endpoint, lazily resolving
|
||||
a single OpenAI client from the pool's train client config."""
|
||||
@@ -55,14 +33,8 @@ class PrefillScorer:
|
||||
|
||||
async def score(self, config: vf.ClientConfig, model: str, token_ids: list[int]) -> list[float]:
|
||||
if self._client is None:
|
||||
# Build the OpenAI client straight from the config fields — works for any
|
||||
# ClientConfig type; resolve_client would hand back an EvalClient (no `.openai`)
|
||||
# for these chat-completions teacher configs.
|
||||
self._client = AsyncOpenAI(
|
||||
base_url=config.base_url,
|
||||
api_key=resolve_api_key(config.api_key_var),
|
||||
default_headers=config.headers or None,
|
||||
)
|
||||
# Prefill scoring uses the SDK even when generation uses the eval relay.
|
||||
self._client = build_async_openai(config)
|
||||
return await prefill_logprobs(self._client, model, token_ids)
|
||||
|
||||
async def aclose(self) -> None:
|
||||
@@ -274,10 +246,7 @@ def setup_client(
|
||||
"renderer": renderer_config,
|
||||
"renderer_model_name": renderer_model_name,
|
||||
}
|
||||
headers = resolve_headers(client_config)
|
||||
return config_cls(
|
||||
base_url=client_config.base_url, api_key_var=client_config.api_key_var, headers=headers, **renderer_extra
|
||||
)
|
||||
return config_cls(**client_config.model_dump(include=set(BaseClientConfig.model_fields)), **renderer_extra)
|
||||
|
||||
|
||||
def setup_admin_clients(client_config: ClientConfig) -> list[AsyncClient]:
|
||||
@@ -290,8 +259,9 @@ def setup_admin_clients(client_config: ClientConfig) -> list[AsyncClient]:
|
||||
urls = client_config.admin_base_url if client_config.admin_base_url else [client_config.base_url]
|
||||
|
||||
def _setup_admin_client(base_url: str) -> httpx.AsyncClient:
|
||||
headers = resolve_headers(client_config)
|
||||
api_key = resolve_api_key(client_config.api_key_var)
|
||||
config = client_config.model_copy(update={"base_url": base_url})
|
||||
headers = resolve_headers(config)
|
||||
api_key = resolve_api_key(config)
|
||||
if api_key != "EMPTY":
|
||||
headers["Authorization"] = f"Bearer {api_key}"
|
||||
|
||||
@@ -324,7 +294,9 @@ async def maybe_check_has_model(
|
||||
f"{result.text[:300]}"
|
||||
)
|
||||
models = body["data"]
|
||||
if not any(model["id"] == model_name for model in models):
|
||||
# A LoRA server lists the model name only once the adapter is loaded; until then
|
||||
# the base model (served as ``<model>-base``) carries it as its ``root``.
|
||||
if not any(model_name in (model["id"], model.get("root")) for model in models):
|
||||
raise ValueError(f"Model {model_name} was not found in the inference pool on {admin_client.base_url}")
|
||||
logger.debug(f"Model {model_name} was found in the inference pool")
|
||||
|
||||
|
||||
@@ -289,9 +289,8 @@ class Orchestrator:
|
||||
|
||||
get_logger().info(f"Initializing weight broadcast ({config.weight_broadcast})")
|
||||
t0 = time.perf_counter()
|
||||
# A LoRA run's adapter is registered under the base model name: the
|
||||
# single adapter shadows it (vLLM resolves lora_requests before the
|
||||
# base-model match), so requests keep addressing one stable name.
|
||||
# A LoRA run's adapter is registered under the model name clients send;
|
||||
# the inference server serves the base model as ``<model>-base``.
|
||||
self.receiver = setup_weight_receiver(
|
||||
get_broadcast_dir(config.output_dir),
|
||||
config.weight_broadcast,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from collections.abc import Callable, Iterator
|
||||
from pathlib import Path
|
||||
from typing import cast
|
||||
|
||||
@@ -16,6 +16,7 @@ import torch.nn as nn
|
||||
from huggingface_hub import snapshot_download
|
||||
from jaxtyping import Int
|
||||
from torch import Tensor
|
||||
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import CheckpointWrapper
|
||||
from torch.distributed.checkpoint.hf_storage import HuggingFaceStorageReader
|
||||
from torch.distributed.checkpoint.state_dict_loader import load as dcp_load
|
||||
from torch.distributed.fsdp import CPUOffloadPolicy, FSDPModule, MixedPrecisionPolicy, OffloadPolicy, fully_shard
|
||||
@@ -125,23 +126,26 @@ def freeze_vision_encoder(model: nn.Module, override_attr: str | None = None) ->
|
||||
logger.info(f"Froze {num_frozen} parameters in vision encoder")
|
||||
|
||||
|
||||
def iter_moe_blocks(model: nn.Module) -> Iterator[MoE]:
|
||||
"""Yield the MoE MLP of each decoder layer, skipping dense layers."""
|
||||
for layer in get_language_model(model).layers:
|
||||
mlp = getattr(layer, "mlp", None)
|
||||
if isinstance(mlp, MoE):
|
||||
yield mlp
|
||||
|
||||
|
||||
def freeze_moe_router(model: nn.Module) -> None:
|
||||
"""Freeze MoE router parameters to maintain stable routing during training."""
|
||||
logger = get_logger()
|
||||
language_model = get_language_model(model)
|
||||
num_frozen = 0
|
||||
for moe in iter_moe_blocks(model):
|
||||
for param in moe.router.parameters():
|
||||
param.requires_grad = False
|
||||
num_frozen += 1
|
||||
|
||||
for layer in language_model.layers:
|
||||
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
|
||||
if isinstance(mlp, MoE):
|
||||
for param in mlp.router.parameters():
|
||||
param.requires_grad = False
|
||||
num_frozen += 1
|
||||
|
||||
if num_frozen == 0:
|
||||
raise ValueError("No MoE router parameters found to freeze. Is this a MoE model?")
|
||||
|
||||
logger.info(f"Froze {num_frozen} MoE router parameters")
|
||||
# No-op for non-MoE models: freeze_moe_router=True is the RL default.
|
||||
if num_frozen > 0:
|
||||
logger.info(f"Froze {num_frozen} MoE router parameters")
|
||||
|
||||
|
||||
def apply_fp32_moe_router(model: nn.Module) -> None:
|
||||
@@ -150,16 +154,12 @@ def apply_fp32_moe_router(model: nn.Module) -> None:
|
||||
The FSDP bf16 cast exemption is applied separately in `setup_fsdp`.
|
||||
"""
|
||||
logger = get_logger()
|
||||
language_model = get_language_model(model)
|
||||
num_routers = 0
|
||||
|
||||
for layer in language_model.layers:
|
||||
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
|
||||
if isinstance(mlp, MoE):
|
||||
mlp.router.to(torch.float32)
|
||||
if isinstance(mlp.router, TokenChoiceTopKRouter):
|
||||
mlp.router.fp32_gate = True
|
||||
num_routers += 1
|
||||
for moe in iter_moe_blocks(model):
|
||||
moe.router.to(torch.float32)
|
||||
if isinstance(moe.router, TokenChoiceTopKRouter):
|
||||
moe.router.fp32_gate = True
|
||||
num_routers += 1
|
||||
|
||||
# No-op for non-MoE models: moe_router_dtype='float32' is the default,
|
||||
# so absence of MoE routers is the common case, not an error.
|
||||
@@ -177,13 +177,10 @@ def get_full_offload_dtype_policy(
|
||||
if config.moe_router_dtype != "float32":
|
||||
return policy
|
||||
|
||||
language_model = get_language_model(model)
|
||||
for layer in language_model.layers:
|
||||
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
|
||||
if isinstance(mlp, MoE):
|
||||
for param in mlp.router.parameters():
|
||||
if param.is_floating_point():
|
||||
policy[id(param)] = (torch.float32, torch.float32)
|
||||
for moe in iter_moe_blocks(model):
|
||||
for param in moe.router.parameters():
|
||||
if param.is_floating_point():
|
||||
policy[id(param)] = (torch.float32, torch.float32)
|
||||
return policy
|
||||
|
||||
|
||||
@@ -215,14 +212,10 @@ def freeze_sparse_indexer(model: nn.Module) -> None:
|
||||
def apply_force_balanced_routing(model: nn.Module) -> None:
|
||||
"""Force MoE token-choice routers into round-robin assignment for fake-data smoke tests."""
|
||||
logger = get_logger()
|
||||
language_model = get_language_model(model)
|
||||
num_routers = 0
|
||||
|
||||
for layer in language_model.layers:
|
||||
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
|
||||
if isinstance(mlp, MoE):
|
||||
mlp.router.force_balanced = True
|
||||
num_routers += 1
|
||||
for moe in iter_moe_blocks(model):
|
||||
moe.router.force_balanced = True
|
||||
num_routers += 1
|
||||
|
||||
if num_routers == 0:
|
||||
raise ValueError("No MoE routers found to force-balance. Is this a MoE model?")
|
||||
@@ -248,13 +241,7 @@ def get_load_balance_stats(
|
||||
"""
|
||||
per_layer_max_vio = []
|
||||
per_layer_routing_confidence = []
|
||||
language_model = get_language_model(model)
|
||||
block_mlps = []
|
||||
for transformer_block in language_model.layers:
|
||||
# This is necessary for models that have mixed dense layers
|
||||
block_mlp = getattr(transformer_block, "mlp", None)
|
||||
if block_mlp is not None and hasattr(block_mlp, "tokens_per_expert"):
|
||||
block_mlps.append(block_mlp)
|
||||
block_mlps = list(iter_moe_blocks(model))
|
||||
if not block_mlps:
|
||||
return {"max_vio": None, "routing_confidence": None, "tokens_per_expert": torch.empty(0, 0)}
|
||||
|
||||
@@ -333,7 +320,7 @@ def compute_expert_load_stats(tokens_per_expert: Tensor) -> dict[str, Tensor]:
|
||||
|
||||
def get_expert_load_stats(tokens_per_expert: Tensor, group: dist.ProcessGroup) -> dict[str, float]:
|
||||
"""Sum a step's per-layer expert counts across the group (every rank routes distinct tokens) and compute load stats."""
|
||||
if tokens_per_expert.numel() == 0: # MoE model without prime-rl MoE layers (HF impl)
|
||||
if tokens_per_expert.numel() == 0:
|
||||
return {}
|
||||
dist.all_reduce(tokens_per_expert, op=dist.ReduceOp.SUM, group=group)
|
||||
return {name: value.item() for name, value in compute_expert_load_stats(tokens_per_expert).items()}
|
||||
@@ -829,12 +816,41 @@ def apply_ac(model: nn.Module, ac_config: ActivationCheckpointConfig):
|
||||
)
|
||||
|
||||
|
||||
# Int args whose value changes between calls. torch.compile treats an int arg as a constant and recompiles
|
||||
# whenever it changes, and every other rank waits in collectives until that rank finishes recompiling. Listed
|
||||
# here, an arg is symbolic from the first compile instead.
|
||||
DYNAMIC_INT_ARGS = (
|
||||
# Longest document in the packed row. FlashAttention uses it to size the attention launch grid.
|
||||
"max_seqlen",
|
||||
)
|
||||
|
||||
|
||||
def mark_dynamic_int_args() -> None:
|
||||
"""Add DYNAMIC_INT_ARGS to torch.compiler.config.dynamic_sources, keeping entries already set."""
|
||||
sources = [source for source in torch.compiler.config.dynamic_sources.split(",") if source]
|
||||
for arg in DYNAMIC_INT_ARGS:
|
||||
# Matches the arg passed directly (L['max_seqlen']) or through a wrapper's kwargs (L['kwargs']['max_seqlen']).
|
||||
pattern = rf".*\['{arg}'\]"
|
||||
if pattern not in sources:
|
||||
sources.append(pattern)
|
||||
torch.compiler.config.dynamic_sources = ",".join(sources)
|
||||
|
||||
|
||||
def apply_compile(model: nn.Module, compile_config: CompileConfig):
|
||||
torch._dynamo.config.capture_scalar_outputs = True
|
||||
mark_dynamic_int_args()
|
||||
language_model = get_language_model(model)
|
||||
for layer_id in range(len(language_model.layers)):
|
||||
layer = language_model.layers[layer_id]
|
||||
if isinstance(layer, CheckpointWrapper) and any(
|
||||
isinstance(module, FSDPModule) for module in layer._checkpoint_wrapped_module.modules()
|
||||
):
|
||||
# A nested FSDP unit's hooks always break the graph, and a break inside a compiled checkpoint
|
||||
# sends the block to eager, so keep AC eager around the compiled block. pytorch/pytorch#196626
|
||||
# removes the fp32 router's nested unit by letting it join the block's FSDP unit.
|
||||
layer = layer._checkpoint_wrapped_module
|
||||
# Doing it in-place avoids mangled fqn which can break checkpoint loading
|
||||
language_model.layers[layer_id].compile(fullgraph=compile_config.fullgraph, mode=compile_config.mode)
|
||||
layer.compile(fullgraph=compile_config.fullgraph, mode=compile_config.mode)
|
||||
get_logger().info(
|
||||
f"Compiled {len(language_model.layers)} layers (fullgraph={compile_config.fullgraph}, mode={compile_config.mode})"
|
||||
)
|
||||
@@ -995,14 +1011,15 @@ def setup_model(
|
||||
override_attr=config.vlm.vision_encoder_attr if config.vlm is not None else None,
|
||||
)
|
||||
|
||||
# the right order is AC -> Compile -> FSDP
|
||||
# the right order is AC -> FSDP -> Compile: compile needs to see which blocks hold nested FSDP units
|
||||
if config.ac is not None:
|
||||
apply_ac(model, config.ac)
|
||||
if config.compile is not None:
|
||||
apply_compile(model, config.compile)
|
||||
|
||||
setup_fsdp(model, config, parallel_dims)
|
||||
|
||||
if config.compile is not None:
|
||||
apply_compile(model, config.compile)
|
||||
|
||||
if loading_from_checkpoint_later:
|
||||
logger.warning(
|
||||
"Skipping loading weights. Initializing an empty model on device, loading from checkpoint later."
|
||||
|
||||
@@ -15,9 +15,9 @@ from transformers.utils import TransformersKwargs
|
||||
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.layers.attn import (
|
||||
flash_attn_3_varlen_func,
|
||||
flash_attn_4_varlen_func,
|
||||
flash_attn_varlen_func,
|
||||
flash_attn_2_varlen_op,
|
||||
flash_attn_3_varlen_op,
|
||||
flash_attn_4_varlen_op,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import FeedForward
|
||||
@@ -87,30 +87,25 @@ class AfmoeFlashAttention(AfmoeAttentionBase):
|
||||
"""AFMoE attention using Flash Attention varlen functions."""
|
||||
|
||||
_funcs = {
|
||||
2: flash_attn_varlen_func,
|
||||
3: flash_attn_3_varlen_func,
|
||||
4: flash_attn_4_varlen_func,
|
||||
2: flash_attn_2_varlen_op,
|
||||
3: flash_attn_3_varlen_op,
|
||||
4: flash_attn_4_varlen_op,
|
||||
}
|
||||
|
||||
def __init__(self, config: AfmoeAttentionConfig, flash_attn_version: int = 4):
|
||||
super().__init__(config)
|
||||
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 _compute_attention(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, cu_seqlens, max_seqlen):
|
||||
"""Run the flash attention kernel. q/k/v are [total_tokens, heads, dim]."""
|
||||
args = [q, k, v, cu_seqlens, cu_seqlens]
|
||||
if self._flash_attn_version != 4:
|
||||
args.extend([max_seqlen, max_seqlen])
|
||||
kwargs: dict = {"causal": True}
|
||||
if self.sliding_window is not None:
|
||||
kwargs["window_size"] = (self.sliding_window - 1, 0)
|
||||
out = self._flash_attn_call(*args, **kwargs)
|
||||
if isinstance(out, tuple):
|
||||
out = out[0]
|
||||
if self._flash_attn_version == 4:
|
||||
out, _ = self.func(q, k, v, cu_seqlens_q=cu_seqlens, cu_seqlens_k=cu_seqlens, **kwargs)
|
||||
else:
|
||||
out = self.func(q, k, v, cu_seqlens, cu_seqlens, max_seqlen, max_seqlen, **kwargs)
|
||||
return out
|
||||
|
||||
def forward(
|
||||
|
||||
@@ -61,8 +61,8 @@ class DeepseekV4Config(PretrainedConfig):
|
||||
num_experts_per_tok: Number of routed experts activated per token.
|
||||
n_routed_experts: Total number of routed experts.
|
||||
n_shared_experts: Number of always-on shared experts.
|
||||
scoring_func: Router activation. Only `sqrtsoftplus` is implemented; any other
|
||||
value is rejected when the MoE layer is built.
|
||||
scoring_func: Router score function, passed to the shared router: `sqrtsoftplus`
|
||||
(V4's checkpoints), `sigmoid`, `softmax` or `topk_softmax`.
|
||||
topk_method: Router top-k selection. Only `noaux_tc` (aux-loss-free bias correction) is
|
||||
implemented; the field is carried because vLLM gates `e_score_correction_bias` on it.
|
||||
norm_topk_prob: Whether to renormalize the top-k routing probabilities.
|
||||
|
||||
@@ -6,96 +6,15 @@ selection with a frozen token-id lookup but keeps the learned gating weights.
|
||||
"""
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.trainer.models.deepseek_v4.configuration_deepseek_v4 import DeepseekV4Config
|
||||
from prime_rl.trainer.models.layers.activations import ClampedSilu
|
||||
from prime_rl.trainer.models.layers.mlp import FeedForward
|
||||
from prime_rl.trainer.models.layers.moe import GroupedExperts, MoE, TokenChoiceTopKRouter
|
||||
|
||||
|
||||
class ClampedSwiglu:
|
||||
"""SwiGLU with both branches clamped, as in HF's `DeepseekV4Experts`.
|
||||
|
||||
Structurally an `Activation`, but with `limit` as instance state: V4 reads its clamp
|
||||
off `config.swiglu_limit`, while the shared `ActivationDispatch` holds stateless
|
||||
classes keyed by name and so has nowhere to put a per-model number.
|
||||
"""
|
||||
|
||||
def __init__(self, limit: float) -> None:
|
||||
self.limit = limit
|
||||
|
||||
def apply(self, gate: torch.Tensor | None, up: torch.Tensor) -> torch.Tensor:
|
||||
assert gate is not None, "V4's routed experts are gated"
|
||||
gate = gate.clamp(max=self.limit)
|
||||
up = up.clamp(min=-self.limit, max=self.limit)
|
||||
return F.silu(gate) * up
|
||||
|
||||
|
||||
class DeepseekV4Router(TokenChoiceTopKRouter):
|
||||
"""Token-choice router scored with `sqrt(softplus(.))`, V4's only scoring function.
|
||||
|
||||
`TokenChoiceTopKRouter.forward` picks its scoring function from an inline
|
||||
`if/elif/else: raise` chain with no hook to extend, and `"sqrtsoftplus"` is outside
|
||||
the `ScoreFuncType` it accepts, so the whole method is restated below. Only the
|
||||
scoring line is new: the `routed_experts` bypass, the selection bias, the
|
||||
normalization, the scaling and the per-expert token count are the base class's,
|
||||
unchanged.
|
||||
"""
|
||||
|
||||
def forward(
|
||||
self, x: torch.Tensor, routed_experts: torch.Tensor | None = None
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
assert routed_experts is None or routed_experts.shape[-1] == self.top_k, (
|
||||
f"routed_experts shape: {routed_experts.shape}, top_k: {self.top_k}"
|
||||
)
|
||||
if self.fp32_gate:
|
||||
gate_bias = self.gate.bias.float() if self.gate.bias is not None else None
|
||||
logits = F.linear(x.float(), self.gate.weight.float(), gate_bias)
|
||||
else:
|
||||
logits = self.gate(x)
|
||||
|
||||
# Scoring runs in float32 to avoid loss explosion, as in the base class. HF scores
|
||||
# in the input dtype instead, so bf16 activations drift from HF by ~1e-3 here.
|
||||
scores = F.softplus(logits.float()).sqrt()
|
||||
|
||||
# NOTE: the selection bias only steers selection. The gating value top_scores is
|
||||
# still derived from the original scores.
|
||||
if routed_experts is not None:
|
||||
top_scores = scores.gather(dim=1, index=routed_experts)
|
||||
selected_experts_indices = routed_experts
|
||||
elif self.force_balanced:
|
||||
num_tokens = scores.shape[0]
|
||||
arange = torch.arange(num_tokens * self.top_k, device=scores.device)
|
||||
selected_experts_indices = (arange % self.num_experts).view(num_tokens, self.top_k)
|
||||
top_scores = scores.gather(dim=1, index=selected_experts_indices)
|
||||
else:
|
||||
selection_scores = scores
|
||||
if self.selection_bias is not None:
|
||||
selection_scores = selection_scores + self.selection_bias
|
||||
_, selected_experts_indices = torch.topk(selection_scores, k=self.top_k, dim=1, sorted=self.topk_sorted)
|
||||
top_scores = scores.gather(dim=1, index=selected_experts_indices)
|
||||
|
||||
with torch.no_grad():
|
||||
selected_probability_mass = top_scores / (scores.sum(dim=-1, keepdim=True) + 1e-20)
|
||||
routing_confidence_sum = selected_probability_mass.sum()
|
||||
|
||||
if self.route_norm:
|
||||
denominator = top_scores.sum(dim=-1, keepdim=True) + 1e-20
|
||||
top_scores = top_scores / denominator
|
||||
top_scores = top_scores * self.route_scale
|
||||
|
||||
num_tokens_per_expert = torch.histc(
|
||||
selected_experts_indices.reshape(-1).float(),
|
||||
bins=self.num_experts,
|
||||
min=0,
|
||||
max=self.num_experts,
|
||||
).to(torch.int64)
|
||||
|
||||
return top_scores, selected_experts_indices, num_tokens_per_expert, routing_confidence_sum
|
||||
|
||||
|
||||
class DeepseekV4HashRouter(DeepseekV4Router):
|
||||
class DeepseekV4HashRouter(TokenChoiceTopKRouter):
|
||||
"""A bootstrap layer's router: selection is a frozen token-id lookup, gating still learned.
|
||||
|
||||
`tid2eid` replaces the top-k of the scores with `tid2eid[token_id]`, read from the checkpoint
|
||||
@@ -105,73 +24,9 @@ class DeepseekV4HashRouter(DeepseekV4Router):
|
||||
unbuilt, keeping the state dict aligned with HF's.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dim: int,
|
||||
num_experts: int,
|
||||
top_k: int,
|
||||
score_func: str,
|
||||
route_norm: bool,
|
||||
route_scale: float,
|
||||
vocab_size: int,
|
||||
) -> None:
|
||||
super().__init__(
|
||||
dim=dim,
|
||||
num_experts=num_experts,
|
||||
top_k=top_k,
|
||||
score_func=score_func,
|
||||
route_norm=route_norm,
|
||||
route_scale=route_scale,
|
||||
selection_bias=False,
|
||||
)
|
||||
self.register_buffer("tid2eid", torch.zeros(vocab_size, top_k, dtype=torch.long), persistent=True)
|
||||
|
||||
|
||||
class DeepseekV4Experts(GroupedExperts):
|
||||
"""Routed experts with V4's clamped SwiGLU.
|
||||
|
||||
The shared `GroupedExperts` already stores the stacked `gate_proj`/`up_proj`/`down_proj`
|
||||
that the on-disk per-expert `w1`/`w2`/`w3` convert into, and its `forward` reaches the
|
||||
activation through `self.activation`, so only that attribute and the initialization
|
||||
spread differ from the base class.
|
||||
"""
|
||||
|
||||
def __init__(self, dim: int, hidden_dim: int, num_experts: int, swiglu_limit: float) -> None:
|
||||
super().__init__(dim, hidden_dim, num_experts, expert_type="gated")
|
||||
self.activation = ClampedSwiglu(swiglu_limit)
|
||||
|
||||
def init_weights(self, init_std: float) -> None:
|
||||
# Both halves of HF's fused gate_up_proj are drawn from the same std=0.02
|
||||
# distribution, so gate and up match that here despite being separate tensors.
|
||||
# The base class scales up_proj by init_std instead.
|
||||
nn.init.trunc_normal_(self.gate_proj, mean=0.0, std=0.02)
|
||||
nn.init.trunc_normal_(self.up_proj, mean=0.0, std=0.02)
|
||||
nn.init.trunc_normal_(self.down_proj, mean=0.0, std=init_std)
|
||||
|
||||
|
||||
class DeepseekV4MLP(FeedForward):
|
||||
"""Dense SwiGLU MLP with V4's clamp, used as the MoE layer's shared expert.
|
||||
|
||||
The shared `FeedForward` already names its projections the way HF's `LlamaMLP` (which
|
||||
HF's `DeepseekV4MLP` subclasses) does, and initializes them the same way, so only the
|
||||
activation changes: gate and up are clamped before the SwiGLU. Unlike the routed
|
||||
experts they are separate tensors here, so there is nothing to chunk.
|
||||
"""
|
||||
|
||||
def __init__(self, config: DeepseekV4Config):
|
||||
# `FeedForward` builds its projections without a bias whatever `bias` says.
|
||||
assert not config.mlp_bias, "mlp_bias is not supported by the shared `FeedForward`"
|
||||
super().__init__(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.moe_intermediate_size,
|
||||
activation=config.hidden_act,
|
||||
)
|
||||
self.limit = config.swiglu_limit
|
||||
|
||||
def forward(self, x: torch.Tensor, routed_experts: torch.Tensor | None = None) -> torch.Tensor:
|
||||
gate = self.gate_proj(x).clamp(max=self.limit)
|
||||
up = self.up_proj(x).clamp(min=-self.limit, max=self.limit)
|
||||
return self.down_proj(F.silu(gate) * up)
|
||||
def __init__(self, *, vocab_size: int, **router_kwargs) -> None:
|
||||
super().__init__(**router_kwargs, selection_bias=False)
|
||||
self.register_buffer("tid2eid", torch.zeros(vocab_size, self.top_k, dtype=torch.long), persistent=True)
|
||||
|
||||
|
||||
class DeepseekV4MoE(MoE):
|
||||
@@ -190,13 +45,9 @@ class DeepseekV4MoE(MoE):
|
||||
|
||||
def __init__(self, config: DeepseekV4Config, layer_idx: int):
|
||||
assert config.hidden_act == "silu", (
|
||||
f"the routed experts hardcode SiLU; hidden_act={config.hidden_act!r} is not supported"
|
||||
f"the experts hardcode SiLU; hidden_act={config.hidden_act!r} is not supported"
|
||||
)
|
||||
if config.scoring_func != "sqrtsoftplus":
|
||||
raise ValueError(
|
||||
f"the router hardcodes sqrt(softplus(.)); scoring_func={config.scoring_func!r} is not supported"
|
||||
)
|
||||
|
||||
assert not config.mlp_bias, "mlp_bias is not supported"
|
||||
is_hash = layer_idx < config.num_hash_layers
|
||||
|
||||
router_kwargs = dict(
|
||||
@@ -212,17 +63,22 @@ class DeepseekV4MoE(MoE):
|
||||
router = (
|
||||
DeepseekV4HashRouter(**router_kwargs, vocab_size=config.vocab_size)
|
||||
if is_hash
|
||||
else DeepseekV4Router(**router_kwargs, selection_bias=True)
|
||||
else TokenChoiceTopKRouter(**router_kwargs, selection_bias=True)
|
||||
)
|
||||
experts = DeepseekV4Experts(
|
||||
activation = ClampedSilu(config.swiglu_limit)
|
||||
experts = GroupedExperts(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.moe_intermediate_size,
|
||||
num_experts=config.n_routed_experts,
|
||||
swiglu_limit=config.swiglu_limit,
|
||||
activation=activation,
|
||||
)
|
||||
# HF sizes its shared expert at `moe_intermediate_size` regardless of
|
||||
# `n_shared_experts`, which therefore only decides whether one exists at all.
|
||||
shared_expert = DeepseekV4MLP(config) if config.n_shared_experts > 0 else None
|
||||
shared_expert = (
|
||||
FeedForward(dim=config.hidden_size, hidden_dim=config.moe_intermediate_size, activation=activation)
|
||||
if config.n_shared_experts > 0
|
||||
else None
|
||||
)
|
||||
|
||||
super().__init__(
|
||||
router=router,
|
||||
@@ -235,6 +91,11 @@ class DeepseekV4MoE(MoE):
|
||||
self.layer_idx = layer_idx
|
||||
self.is_hash = is_hash
|
||||
|
||||
def init_weights(self, init_std: float, buffer_device: torch.device) -> None:
|
||||
super().init_weights(init_std, buffer_device)
|
||||
# HF draws both halves of its fused gate_up_proj from std=0.02; the shared init uses init_std for up.
|
||||
nn.init.trunc_normal_(self.experts.up_proj, mean=0.0, std=0.02)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
|
||||
@@ -18,6 +18,19 @@ class ClampedSwiglu(Activation):
|
||||
return (up + 1) * gate * torch.sigmoid(gate * 1.702)
|
||||
|
||||
|
||||
class ClampedSilu(Activation):
|
||||
"""SwiGLU with the gate clamped to `max=limit` and up to `[-limit, limit]` (DeepSeek V4)."""
|
||||
|
||||
def __init__(self, limit: float) -> None:
|
||||
self.limit = limit
|
||||
|
||||
def apply(self, gate: torch.Tensor | None, up: torch.Tensor) -> torch.Tensor:
|
||||
assert gate is not None
|
||||
gate = gate.clamp(max=self.limit)
|
||||
up = up.clamp(min=-self.limit, max=self.limit)
|
||||
return F.silu(gate) * up
|
||||
|
||||
|
||||
class Relu2(Activation):
|
||||
@staticmethod
|
||||
def apply(gate: torch.Tensor | None, up: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
@@ -13,14 +13,19 @@ from .rotary_emb import apply_rotary_pos_emb
|
||||
# flash-attention-2
|
||||
try:
|
||||
from flash_attn import flash_attn_varlen_func
|
||||
from flash_attn.flash_attn_interface import _flash_attn_varlen_backward, _flash_attn_varlen_forward
|
||||
except ImportError:
|
||||
flash_attn_varlen_func = None # type: ignore
|
||||
_flash_attn_varlen_backward = _flash_attn_varlen_forward = None # type: ignore
|
||||
|
||||
# flash-attention-3
|
||||
try:
|
||||
from flash_attn_interface import _flash_attn_backward as _flash_attn_3_bwd
|
||||
from flash_attn_interface import _flash_attn_forward as _flash_attn_3_fwd
|
||||
from flash_attn_interface import flash_attn_varlen_func as flash_attn_3_varlen_func
|
||||
except ImportError:
|
||||
flash_attn_3_varlen_func = None # type: ignore
|
||||
_flash_attn_3_bwd = _flash_attn_3_fwd = None # type: ignore
|
||||
|
||||
try:
|
||||
from flash_attn.cute import flash_attn_varlen_func as flash_attn_4_varlen_func
|
||||
@@ -30,9 +35,11 @@ except ImportError:
|
||||
_flash_attn_bwd = _flash_attn_fwd = None # type: ignore
|
||||
|
||||
|
||||
# FA4's flash_attn_varlen_func is a Python autograd.Function that Dynamo cannot trace. Inside a
|
||||
# checkpointed block that graph break drops the whole block to eager, so FA4 is exposed as an
|
||||
# opaque custom op instead, which also lets selective activation checkpointing save its output.
|
||||
# Each FlashAttention version's flash_attn_varlen_func is a Python autograd.Function that Dynamo
|
||||
# cannot trace (FA2 and FA3 also reject the same cu_seqlens tensor passed as both cu_seqlens_q and
|
||||
# cu_seqlens_k). Inside a checkpointed block that graph break drops the whole block to eager, so
|
||||
# each version is exposed as an opaque custom op instead, which also lets selective activation
|
||||
# checkpointing save its output.
|
||||
@torch.library.custom_op("prime_rl_attn::flash_attn_4_varlen", mutates_args=())
|
||||
def _flash_attn_4_varlen(
|
||||
q: torch.Tensor,
|
||||
@@ -40,6 +47,8 @@ def _flash_attn_4_varlen(
|
||||
v: torch.Tensor,
|
||||
cu_seqlens_q: torch.Tensor,
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int | None,
|
||||
max_seqlen_k: int | None,
|
||||
causal: bool,
|
||||
window_size_left: int | None,
|
||||
window_size_right: int | None,
|
||||
@@ -50,6 +59,8 @@ def _flash_attn_4_varlen(
|
||||
v,
|
||||
cu_seqlens_q=cu_seqlens_q,
|
||||
cu_seqlens_k=cu_seqlens_k,
|
||||
max_seqlen_q=max_seqlen_q,
|
||||
max_seqlen_k=max_seqlen_k,
|
||||
causal=causal,
|
||||
window_size_left=window_size_left,
|
||||
window_size_right=window_size_right,
|
||||
@@ -59,7 +70,7 @@ def _flash_attn_4_varlen(
|
||||
|
||||
|
||||
@_flash_attn_4_varlen.register_fake
|
||||
def _(q, k, v, cu_seqlens_q, cu_seqlens_k, causal, window_size_left, window_size_right):
|
||||
def _(q, k, v, *args):
|
||||
out = q.new_empty((*q.shape[:-1], v.shape[-1]))
|
||||
lse = q.new_empty((q.shape[1], q.shape[0]), dtype=torch.float32)
|
||||
return out, lse
|
||||
@@ -75,6 +86,8 @@ def _flash_attn_4_varlen_backward(
|
||||
lse: torch.Tensor,
|
||||
cu_seqlens_q: torch.Tensor,
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int | None,
|
||||
max_seqlen_k: int | None,
|
||||
causal: bool,
|
||||
window_size_left: int | None,
|
||||
window_size_right: int | None,
|
||||
@@ -91,19 +104,24 @@ def _flash_attn_4_varlen_backward(
|
||||
window_size_right=window_size_right,
|
||||
cu_seqlens_q=cu_seqlens_q,
|
||||
cu_seqlens_k=cu_seqlens_k,
|
||||
max_seqlen_q=max_seqlen_q,
|
||||
max_seqlen_k=max_seqlen_k,
|
||||
)
|
||||
return dq, dk, dv
|
||||
|
||||
|
||||
@_flash_attn_4_varlen_backward.register_fake
|
||||
def _(dout, q, k, v, out, lse, cu_seqlens_q, cu_seqlens_k, causal, window_size_left, window_size_right):
|
||||
def _(dout, q, k, v, *args):
|
||||
return torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
|
||||
|
||||
|
||||
def _flash_attn_4_varlen_setup_context(ctx, inputs, output) -> None:
|
||||
q, k, v, cu_seqlens_q, cu_seqlens_k, causal, window_size_left, window_size_right = inputs
|
||||
q, k, v, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, causal, window_size_left, window_size_right = (
|
||||
inputs
|
||||
)
|
||||
out, lse = output
|
||||
ctx.save_for_backward(q, k, v, out, lse, cu_seqlens_q, cu_seqlens_k)
|
||||
ctx.max_seqlen = (max_seqlen_q, max_seqlen_k)
|
||||
ctx.causal = causal
|
||||
ctx.window_size = (window_size_left, window_size_right)
|
||||
|
||||
@@ -111,9 +129,9 @@ def _flash_attn_4_varlen_setup_context(ctx, inputs, output) -> None:
|
||||
def _flash_attn_4_varlen_autograd(ctx, dout: torch.Tensor, _dlse: torch.Tensor | None):
|
||||
q, k, v, out, lse, cu_seqlens_q, cu_seqlens_k = ctx.saved_tensors
|
||||
dq, dk, dv = _flash_attn_4_varlen_backward(
|
||||
dout.contiguous(), q, k, v, out, lse, cu_seqlens_q, cu_seqlens_k, ctx.causal, *ctx.window_size
|
||||
dout.contiguous(), q, k, v, out, lse, cu_seqlens_q, cu_seqlens_k, *ctx.max_seqlen, ctx.causal, *ctx.window_size
|
||||
)
|
||||
return dq, dk, dv, None, None, None, None, None
|
||||
return dq, dk, dv, None, None, None, None, None, None, None
|
||||
|
||||
|
||||
_flash_attn_4_varlen.register_autograd(_flash_attn_4_varlen_autograd, setup_context=_flash_attn_4_varlen_setup_context)
|
||||
@@ -126,11 +144,264 @@ def flash_attn_4_varlen_op(
|
||||
*,
|
||||
cu_seqlens_q: torch.Tensor,
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int | None = None,
|
||||
max_seqlen_k: int | None = None,
|
||||
causal: bool = False,
|
||||
window_size: tuple[int | None, int | None] = (None, None),
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Drop-in for FA4's ``flash_attn_varlen_func`` as called by ``FlashAttention``, routed through the custom op."""
|
||||
return _flash_attn_4_varlen(q, k, v, cu_seqlens_q, cu_seqlens_k, causal, window_size[0], window_size[1])
|
||||
return _flash_attn_4_varlen(
|
||||
q, k, v, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, causal, window_size[0], window_size[1]
|
||||
)
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl_attn::flash_attn_3_varlen", mutates_args=())
|
||||
def _flash_attn_3_varlen(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
cu_seqlens_q: torch.Tensor,
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int,
|
||||
max_seqlen_k: int,
|
||||
softmax_scale: float,
|
||||
causal: bool,
|
||||
window_size_left: int,
|
||||
window_size_right: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
out, lse, _, _ = _flash_attn_3_fwd(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
cu_seqlens_q=cu_seqlens_q,
|
||||
cu_seqlens_k=cu_seqlens_k,
|
||||
max_seqlen_q=max_seqlen_q,
|
||||
max_seqlen_k=max_seqlen_k,
|
||||
softmax_scale=softmax_scale,
|
||||
causal=causal,
|
||||
window_size_left=window_size_left,
|
||||
window_size_right=window_size_right,
|
||||
)
|
||||
return out, lse
|
||||
|
||||
|
||||
@_flash_attn_3_varlen.register_fake
|
||||
def _(q, k, v, *args):
|
||||
out = q.new_empty((*q.shape[:-1], v.shape[-1]))
|
||||
lse = q.new_empty((q.shape[1], q.shape[0]), dtype=torch.float32)
|
||||
return out, lse
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl_attn::flash_attn_3_varlen_backward", mutates_args=())
|
||||
def _flash_attn_3_varlen_backward(
|
||||
dout: torch.Tensor,
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
out: torch.Tensor,
|
||||
lse: torch.Tensor,
|
||||
cu_seqlens_q: torch.Tensor,
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int,
|
||||
max_seqlen_k: int,
|
||||
softmax_scale: float,
|
||||
causal: bool,
|
||||
window_size_left: int,
|
||||
window_size_right: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
|
||||
_flash_attn_3_bwd(
|
||||
dout,
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
out,
|
||||
lse,
|
||||
cu_seqlens_q=cu_seqlens_q,
|
||||
cu_seqlens_k=cu_seqlens_k,
|
||||
max_seqlen_q=max_seqlen_q,
|
||||
max_seqlen_k=max_seqlen_k,
|
||||
dq=dq,
|
||||
dk=dk,
|
||||
dv=dv,
|
||||
softmax_scale=softmax_scale,
|
||||
is_causal=causal,
|
||||
window_size_left=window_size_left,
|
||||
window_size_right=window_size_right,
|
||||
)
|
||||
return dq, dk, dv
|
||||
|
||||
|
||||
@_flash_attn_3_varlen_backward.register_fake
|
||||
def _(dout, q, k, v, *args):
|
||||
return torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
|
||||
|
||||
|
||||
# FA2's public flash_attn_varlen_func pads the head dim to a multiple of 8 around its kernels; these ops call
|
||||
# the kernels directly, so they pad the same way.
|
||||
def pad_head_dim_to_multiple_of_8_for_fa2(t: torch.Tensor) -> torch.Tensor:
|
||||
head_dim = t.shape[-1]
|
||||
if head_dim % 8 == 0:
|
||||
return t
|
||||
return torch.nn.functional.pad(t, [0, 8 - head_dim % 8])
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl_attn::flash_attn_2_varlen", mutates_args=())
|
||||
def _flash_attn_2_varlen(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
cu_seqlens_q: torch.Tensor,
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int,
|
||||
max_seqlen_k: int,
|
||||
softmax_scale: float,
|
||||
causal: bool,
|
||||
window_size_left: int,
|
||||
window_size_right: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
head_dim = q.shape[-1]
|
||||
q, k, v = (pad_head_dim_to_multiple_of_8_for_fa2(t) for t in (q, k, v))
|
||||
out_padded, lse, _, _ = _flash_attn_varlen_forward(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
cu_seqlens_q,
|
||||
cu_seqlens_k,
|
||||
max_seqlen_q,
|
||||
max_seqlen_k,
|
||||
0.0,
|
||||
softmax_scale,
|
||||
causal=causal,
|
||||
window_size_left=window_size_left,
|
||||
window_size_right=window_size_right,
|
||||
)
|
||||
return out_padded[..., :head_dim], lse
|
||||
|
||||
|
||||
# FA2's kernel allocates its outputs with empty_like on the padded inputs, so the fakes keep their strides and padding.
|
||||
@_flash_attn_2_varlen.register_fake
|
||||
def _(q, k, v, *args):
|
||||
head_dim = q.shape[-1]
|
||||
out = torch.empty_like(pad_head_dim_to_multiple_of_8_for_fa2(q))[..., :head_dim]
|
||||
lse = q.new_empty((q.shape[1], q.shape[0]), dtype=torch.float32)
|
||||
return out, lse
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl_attn::flash_attn_2_varlen_backward", mutates_args=())
|
||||
def _flash_attn_2_varlen_backward(
|
||||
dout: torch.Tensor,
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
out: torch.Tensor,
|
||||
lse: torch.Tensor,
|
||||
cu_seqlens_q: torch.Tensor,
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int,
|
||||
max_seqlen_k: int,
|
||||
softmax_scale: float,
|
||||
causal: bool,
|
||||
window_size_left: int,
|
||||
window_size_right: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
head_dim = q.shape[-1]
|
||||
dout, q, k, v, out = (pad_head_dim_to_multiple_of_8_for_fa2(t) for t in (dout, q, k, v, out))
|
||||
dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
|
||||
_flash_attn_varlen_backward(
|
||||
dout,
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
out,
|
||||
lse,
|
||||
dq,
|
||||
dk,
|
||||
dv,
|
||||
cu_seqlens_q,
|
||||
cu_seqlens_k,
|
||||
max_seqlen_q,
|
||||
max_seqlen_k,
|
||||
0.0,
|
||||
softmax_scale,
|
||||
causal,
|
||||
window_size_left,
|
||||
window_size_right,
|
||||
0.0,
|
||||
None,
|
||||
False,
|
||||
)
|
||||
return dq[..., :head_dim], dk[..., :head_dim], dv[..., :head_dim]
|
||||
|
||||
|
||||
@_flash_attn_2_varlen_backward.register_fake
|
||||
def _(dout, q, k, v, *args):
|
||||
head_dim = q.shape[-1]
|
||||
return tuple(torch.empty_like(pad_head_dim_to_multiple_of_8_for_fa2(t))[..., :head_dim] for t in (q, k, v))
|
||||
|
||||
|
||||
def _flash_attn_varlen_setup_context(ctx, inputs, output) -> None:
|
||||
q, k, v, cu_seqlens_q, cu_seqlens_k, *scalar_args = inputs
|
||||
out, lse = output
|
||||
ctx.save_for_backward(q, k, v, out, lse, cu_seqlens_q, cu_seqlens_k)
|
||||
ctx.scalar_args = scalar_args
|
||||
|
||||
|
||||
def _flash_attn_varlen_autograd(backward_op, ctx, dout: torch.Tensor, _dlse: torch.Tensor | None):
|
||||
dq, dk, dv = backward_op(dout.contiguous(), *ctx.saved_tensors, *ctx.scalar_args)
|
||||
return dq, dk, dv, None, None, None, None, None, None, None, None
|
||||
|
||||
|
||||
_flash_attn_2_varlen.register_autograd(
|
||||
functools.partial(_flash_attn_varlen_autograd, _flash_attn_2_varlen_backward),
|
||||
setup_context=_flash_attn_varlen_setup_context,
|
||||
)
|
||||
_flash_attn_3_varlen.register_autograd(
|
||||
functools.partial(_flash_attn_varlen_autograd, _flash_attn_3_varlen_backward),
|
||||
setup_context=_flash_attn_varlen_setup_context,
|
||||
)
|
||||
|
||||
|
||||
def flash_attn_2_varlen_op(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
cu_seqlens_q: torch.Tensor,
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int,
|
||||
max_seqlen_k: int,
|
||||
softmax_scale: float | None = None,
|
||||
causal: bool = False,
|
||||
window_size: tuple[int, int] = (-1, -1),
|
||||
) -> torch.Tensor:
|
||||
"""Drop-in for FA2's ``flash_attn_varlen_func``, routed through the custom op."""
|
||||
if softmax_scale is None:
|
||||
softmax_scale = q.shape[-1] ** -0.5
|
||||
out, _ = _flash_attn_2_varlen(
|
||||
q, k, v, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, softmax_scale, causal, *window_size
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def flash_attn_3_varlen_op(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
cu_seqlens_q: torch.Tensor,
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int,
|
||||
max_seqlen_k: int,
|
||||
softmax_scale: float | None = None,
|
||||
causal: bool = False,
|
||||
window_size: tuple[int, int] = (-1, -1),
|
||||
) -> torch.Tensor:
|
||||
"""Drop-in for FA3's ``flash_attn_varlen_func``, routed through the custom op."""
|
||||
if softmax_scale is None:
|
||||
softmax_scale = q.shape[-1] ** -0.5
|
||||
out, _ = _flash_attn_3_varlen(
|
||||
q, k, v, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, softmax_scale, causal, *window_size
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -158,8 +429,8 @@ class FlashAttention(nn.Module):
|
||||
supported_fusions = {"qkv": fuse_qkv_projections}
|
||||
|
||||
_funcs = {
|
||||
2: flash_attn_varlen_func,
|
||||
3: flash_attn_3_varlen_func,
|
||||
2: flash_attn_2_varlen_op,
|
||||
3: flash_attn_3_varlen_op,
|
||||
4: flash_attn_4_varlen_op,
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ from typing import Literal
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.trainer.models.layers.activations import ActivationDispatch, ActivationType
|
||||
from prime_rl.trainer.models.layers.activations import Activation, ActivationDispatch, ActivationType
|
||||
|
||||
ExpertType = Literal["gated", "non_gated"]
|
||||
|
||||
@@ -17,14 +17,14 @@ class FeedForward(nn.Module):
|
||||
hidden_dim: int,
|
||||
*,
|
||||
expert_type: ExpertType = "gated",
|
||||
activation: ActivationType = "silu",
|
||||
activation: ActivationType | Activation = "silu",
|
||||
bias: bool = False,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.gate_proj = nn.Linear(dim, hidden_dim, bias=bias) if expert_type == "gated" else None
|
||||
self.up_proj = nn.Linear(dim, hidden_dim, bias=bias)
|
||||
self.down_proj = nn.Linear(hidden_dim, dim, bias=bias)
|
||||
self.activation = ActivationDispatch[activation]
|
||||
self.activation = ActivationDispatch[activation] if isinstance(activation, str) else activation
|
||||
|
||||
def forward(self, x: torch.Tensor, routed_experts: torch.Tensor | None = None) -> torch.Tensor:
|
||||
gate = self.gate_proj(x) if self.gate_proj is not None else None
|
||||
|
||||
@@ -13,11 +13,11 @@ from torch import nn
|
||||
|
||||
from prime_rl.trainer.distributed.token_dispatcher import LocalTokenDispatcher, TokenDispatcher
|
||||
from prime_rl.trainer.models.fusions import fuse_gate_up_projections
|
||||
from prime_rl.trainer.models.layers.activations import ActivationDispatch, ActivationType
|
||||
from prime_rl.trainer.models.layers.activations import Activation, ActivationDispatch, ActivationType
|
||||
from prime_rl.trainer.models.layers.expert_compute import BF16ExpertCompute, ExpertCompute
|
||||
from prime_rl.trainer.models.layers.mlp import ExpertType, FeedForward
|
||||
|
||||
ScoreFuncType = Literal["softmax", "sigmoid", "topk_softmax"]
|
||||
ScoreFuncType = Literal["softmax", "sigmoid", "topk_softmax", "sqrtsoftplus"]
|
||||
|
||||
|
||||
@torch.library.custom_op(
|
||||
@@ -76,7 +76,7 @@ class GroupedExperts(nn.Module):
|
||||
num_experts: int,
|
||||
*,
|
||||
expert_type: ExpertType = "gated",
|
||||
activation: ActivationType = "silu",
|
||||
activation: ActivationType | Activation = "silu",
|
||||
bias: bool = False,
|
||||
compute: ExpertCompute | None = None,
|
||||
):
|
||||
@@ -93,7 +93,7 @@ class GroupedExperts(nn.Module):
|
||||
self.up_proj_bias = nn.Parameter(torch.empty(num_experts, hidden_dim)) if bias else None
|
||||
self.down_proj_bias = nn.Parameter(torch.empty(num_experts, dim)) if bias else None
|
||||
|
||||
self.activation = ActivationDispatch[activation]
|
||||
self.activation = ActivationDispatch[activation] if isinstance(activation, str) else activation
|
||||
if expert_type == "non_gated":
|
||||
self.supported_fusions = {}
|
||||
self.set_compute(compute or BF16ExpertCompute())
|
||||
@@ -136,8 +136,8 @@ class TokenChoiceTopKRouter(nn.Module):
|
||||
dim (int): Dimension of input tokens.
|
||||
num_experts (int): Number of experts in each moe layer.
|
||||
top_k (int): Number of experts each token will be routed to in token-choice routing.
|
||||
score_func (Literal["softmax", "sigmoid", "topk_softmax"]): Score transform. ``topk_softmax``
|
||||
selects experts from the logits and normalizes only the selected logits.
|
||||
score_func (ScoreFuncType): Score transform. ``topk_softmax`` selects experts from the logits
|
||||
and normalizes only the selected logits. ``sqrtsoftplus`` is DeepSeek V4's ``sqrt(softplus(.))``.
|
||||
route_norm (bool): Whether to normalize the routing scores when using sigmoid.
|
||||
route_scale (float): Scaling factor applied to the routing scores.
|
||||
gate_bias (bool): Whether the gate has a trainable logit bias.
|
||||
@@ -151,7 +151,7 @@ class TokenChoiceTopKRouter(nn.Module):
|
||||
dim: int,
|
||||
num_experts: int,
|
||||
top_k: int,
|
||||
score_func: Literal["softmax", "sigmoid", "topk_softmax"],
|
||||
score_func: ScoreFuncType,
|
||||
route_norm: bool,
|
||||
route_scale: float,
|
||||
*,
|
||||
@@ -214,6 +214,8 @@ class TokenChoiceTopKRouter(nn.Module):
|
||||
scores = F.softmax(logits.float(), dim=1)
|
||||
elif self.score_func == "topk_softmax":
|
||||
scores = logits
|
||||
elif self.score_func == "sqrtsoftplus":
|
||||
scores = F.softplus(logits.float()).sqrt()
|
||||
else:
|
||||
raise NotImplementedError(f"Unknown score function {self.score_func}")
|
||||
|
||||
|
||||
@@ -176,15 +176,15 @@ def substitute_ulysses_attn(
|
||||
|
||||
# Resolve flash kernel + version from attn_impl.
|
||||
if attn_impl == "flash_attention_4":
|
||||
from flash_attn.cute import flash_attn_varlen_func as flash_fn
|
||||
from prime_rl.trainer.models.layers.attn import flash_attn_4_varlen_op as flash_fn
|
||||
|
||||
flash_attn_version = 4
|
||||
elif attn_impl == "flash_attention_3":
|
||||
from flash_attn_interface import flash_attn_varlen_func as flash_fn
|
||||
from prime_rl.trainer.models.layers.attn import flash_attn_3_varlen_op as flash_fn
|
||||
|
||||
flash_attn_version = 3
|
||||
else:
|
||||
from flash_attn import flash_attn_varlen_func as flash_fn
|
||||
from prime_rl.trainer.models.layers.attn import flash_attn_2_varlen_op as flash_fn
|
||||
|
||||
flash_attn_version = 2
|
||||
|
||||
|
||||
@@ -6,9 +6,9 @@ from torch import nn
|
||||
from transformers.modeling_outputs import BaseModelOutputWithPooling
|
||||
|
||||
from prime_rl.trainer.models.layers.attn import (
|
||||
flash_attn_3_varlen_func,
|
||||
flash_attn_4_varlen_func,
|
||||
flash_attn_varlen_func,
|
||||
flash_attn_2_varlen_op,
|
||||
flash_attn_3_varlen_op,
|
||||
flash_attn_4_varlen_op,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.rotary_emb import rotate_half
|
||||
from prime_rl.trainer.models.qwen3_5.configuration_qwen3_5 import Qwen3_5VisionConfig
|
||||
@@ -69,9 +69,9 @@ class Qwen3_5VisionMLP(nn.Module):
|
||||
|
||||
class Qwen3_5VisionAttention(nn.Module):
|
||||
FLASH_ATTENTION_FUNCTIONS = {
|
||||
"flash_attention_2": flash_attn_varlen_func,
|
||||
"flash_attention_3": flash_attn_3_varlen_func,
|
||||
"flash_attention_4": flash_attn_4_varlen_func,
|
||||
"flash_attention_2": flash_attn_2_varlen_op,
|
||||
"flash_attention_3": flash_attn_3_varlen_op,
|
||||
"flash_attention_4": flash_attn_4_varlen_op,
|
||||
}
|
||||
|
||||
def __init__(self, config: Qwen3_5VisionConfig) -> None:
|
||||
|
||||
@@ -143,11 +143,12 @@ def setup_logger(
|
||||
if json_logging and tag:
|
||||
logger = logger.bind(tag=tag)
|
||||
|
||||
# diagnose=False: repr()-ing frame locals that hold multi-GB tensors makes a crash look like a hang.
|
||||
# Install console handler (enqueue=True only for JSON mode to avoid blocking in async contexts)
|
||||
if json_logging:
|
||||
logger.add(json_sink, level=(console_level or log_level).upper(), enqueue=True)
|
||||
logger.add(json_sink, level=(console_level or log_level).upper(), enqueue=True, diagnose=False)
|
||||
else:
|
||||
logger.add(sys.stdout, format=format, level=(console_level or log_level).upper(), colorize=True)
|
||||
logger.add(sys.stdout, format=format, level=(console_level or log_level).upper(), colorize=True, diagnose=False)
|
||||
if log_file is not None:
|
||||
# The console format carries raw ANSI codes; the file gets a plain layout.
|
||||
logger.add(
|
||||
@@ -155,6 +156,7 @@ def setup_logger(
|
||||
format="{time:HH:mm:ss} {level: >7} " + f"{tag_prefix}{{message}}",
|
||||
level=log_level.upper(),
|
||||
colorize=False,
|
||||
diagnose=False,
|
||||
)
|
||||
|
||||
# Disable critical logging
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import os
|
||||
import signal
|
||||
import socket
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from typing import Callable, Generator
|
||||
@@ -46,14 +45,6 @@ def cleanup_zombies():
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def free_port() -> int:
|
||||
"""Fixture to get a free port per tests"""
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
s.bind(("", 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def user() -> str:
|
||||
"""Fixture for current user from environment for test session."""
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
import copy
|
||||
|
||||
from vllm.tokenizers.deepseek_v4_encoding import encode_messages
|
||||
|
||||
from prime_rl.inference.patches import monkey_patch_deepseek_v4_request_tools_placement
|
||||
|
||||
|
||||
class _StubTokenizer:
|
||||
def get_added_vocab(self):
|
||||
return {}
|
||||
|
||||
def encode(self, text, **_kwargs):
|
||||
return text
|
||||
|
||||
|
||||
def _request_tools():
|
||||
return [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"description": "Get weather for a city",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {"city": {"type": "string"}},
|
||||
"required": ["city"],
|
||||
},
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
def _tokenizer():
|
||||
from vllm.tokenizers import deepseek_v4
|
||||
|
||||
monkey_patch_deepseek_v4_request_tools_placement()
|
||||
return deepseek_v4.get_deepseek_v4_tokenizer(_StubTokenizer())
|
||||
|
||||
|
||||
def _render(messages, tools):
|
||||
return _tokenizer().apply_chat_template(
|
||||
messages,
|
||||
tools=tools,
|
||||
tokenize=False,
|
||||
thinking=True,
|
||||
reasoning_effort="low",
|
||||
)
|
||||
|
||||
|
||||
def _reference(messages):
|
||||
return encode_messages(messages, thinking_mode="thinking", reasoning_effort="low")
|
||||
|
||||
|
||||
def test_request_tools_attach_to_first_existing_system_without_mutation():
|
||||
messages = [
|
||||
{"role": "user", "content": "This may precede the system message."},
|
||||
{"role": "system", "content": "You are helpful.", "tools": []},
|
||||
{"role": "system", "content": "A later system message."},
|
||||
{"role": "user", "content": "Weather in Paris?"},
|
||||
]
|
||||
snapshot = copy.deepcopy(messages)
|
||||
tools = _request_tools()
|
||||
|
||||
prompt = _render(messages, tools)
|
||||
|
||||
expected_messages = messages.copy()
|
||||
expected_messages[1] = {**messages[1], "tools": tools}
|
||||
assert prompt == _reference(expected_messages)
|
||||
assert prompt.count("## Tools") == 1
|
||||
assert messages == snapshot
|
||||
|
||||
|
||||
def test_request_tools_synthesize_system_only_when_none_exists():
|
||||
messages = [{"role": "user", "content": "Weather in Paris?"}]
|
||||
tools = _request_tools()
|
||||
|
||||
prompt = _render(messages, tools)
|
||||
|
||||
assert prompt == _reference([{"role": "system", "tools": tools}, *messages])
|
||||
@@ -93,6 +93,8 @@ def test_setup_client_creates_renderer_client():
|
||||
base_url="http://worker-a:8000/v1",
|
||||
api_key_var="PRIME_API_KEY",
|
||||
headers={"X-Test": "test"},
|
||||
headers_from_env={"X-Token": "PROVIDER_TOKEN"},
|
||||
timeout={"read": 12},
|
||||
)
|
||||
|
||||
renderer_settings = Qwen3VLRendererConfig()
|
||||
@@ -108,6 +110,8 @@ def test_setup_client_creates_renderer_client():
|
||||
assert client.base_url == "http://worker-a:8000/v1"
|
||||
assert "X-data-parallel-rank" not in client.headers
|
||||
assert client.headers["X-Test"] == "test"
|
||||
assert client.headers_from_env == {"X-Token": "PROVIDER_TOKEN"}
|
||||
assert client.timeout.read == 12
|
||||
|
||||
|
||||
def test_check_health_retries_non_success_status():
|
||||
|
||||
@@ -18,6 +18,9 @@ from prime_rl.configs.orchestrator import (
|
||||
ScheduledEvalConfig,
|
||||
TrainConfig,
|
||||
)
|
||||
from prime_rl.configs.orchestrator import (
|
||||
ModelConfig as OrchestratorModelConfig,
|
||||
)
|
||||
from prime_rl.configs.rl import RLConfig
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
from prime_rl.configs.trainer import ModelConfig as TrainerModelConfig
|
||||
@@ -340,6 +343,16 @@ def test_moe_router_dtype_auto_resolves_per_trainer():
|
||||
assert config_cls.model_validate({"model": {"moe_router_dtype": dtype}}).model.moe_router_dtype == dtype
|
||||
|
||||
|
||||
def test_freeze_moe_router_auto_resolves_per_trainer():
|
||||
"""``freeze_moe_router='auto'`` (the default) freezes the router for RL, not SFT; explicit values are kept."""
|
||||
assert TrainerConfig.model_validate({}).model.freeze_moe_router is True
|
||||
assert SFTConfig.model_validate({}).model.freeze_moe_router is False
|
||||
|
||||
for config_cls in (TrainerConfig, SFTConfig):
|
||||
for freeze in (True, False):
|
||||
assert config_cls.model_validate({"model": {"freeze_moe_router": freeze}}).model.freeze_moe_router is freeze
|
||||
|
||||
|
||||
@pytest.mark.parametrize("config_cls", [TrainerConfig, SFTConfig])
|
||||
def test_full_optimizer_offload_disables_gradient_clipping(config_cls):
|
||||
with pytest.warns(UserWarning, match="Gradient clipping prevents optimizer-in-backward"):
|
||||
@@ -393,6 +406,36 @@ def test_resolved_json_roundtrips_explicit_none(tmp_path):
|
||||
assert reloaded == config
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"config_class,source_args,expected_url,expected_key",
|
||||
[
|
||||
(
|
||||
EvalConfig,
|
||||
["--source", '[{"env":{"id":"single_agent"}}]'],
|
||||
"https://configured.pinference.ai/api/v1",
|
||||
"PRIME_API_KEY",
|
||||
),
|
||||
(
|
||||
SFTOnlineEvalConfig,
|
||||
["--source", '[{"env":{"id":"single_agent"}}]'],
|
||||
"http://localhost:8000/v1",
|
||||
"VLLM_API_KEY",
|
||||
),
|
||||
(OrchestratorModelConfig, [], "http://localhost:8000/v1", "VLLM_API_KEY"),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("overrides", [[], ["--client.skip-model-check"], ["--client.wait-for-ready-timeout", "10"]])
|
||||
def test_client_defaults_survive_partial_overrides(
|
||||
monkeypatch, config_class, source_args, expected_url, expected_key, overrides
|
||||
):
|
||||
monkeypatch.setenv("PRIME_INFERENCE_URL", "https://configured.pinference.ai/api/v1")
|
||||
config = cli(config_class, args=source_args + overrides)
|
||||
assert config.client.base_url == expected_url
|
||||
assert config.client.api_key_var == expected_key
|
||||
reloaded = config_class.model_validate_json(config.model_dump_json())
|
||||
assert reloaded.client == config.client
|
||||
|
||||
|
||||
def test_env_algo_inherits_the_group_algo():
|
||||
config = OrchestratorConfig.model_validate(
|
||||
{
|
||||
|
||||
@@ -1,132 +0,0 @@
|
||||
# coding=utf-8
|
||||
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
from transformers.configuration_utils import PretrainedConfig, layer_type_validation
|
||||
from transformers.utils import logging
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
|
||||
class AfmoeConfig(PretrainedConfig):
|
||||
"""
|
||||
n_group (`int`, *optional*, defaults to 1):
|
||||
Number of groups for routed experts.
|
||||
topk_group (`int`, *optional*, defaults to 1):
|
||||
Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
|
||||
"""
|
||||
|
||||
model_type = "afmoe"
|
||||
base_model_pp_plan = {
|
||||
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
||||
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
|
||||
"norm": (["hidden_states"], ["hidden_states"]),
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
num_hidden_layers: int = 32,
|
||||
vocab_size: int = 200192,
|
||||
hidden_size: int = 2048,
|
||||
intermediate_size: int = 6144,
|
||||
moe_intermediate_size=1408,
|
||||
num_dense_layers=1,
|
||||
num_attention_heads=16,
|
||||
num_key_value_heads=None,
|
||||
head_dim=128,
|
||||
hidden_act="silu",
|
||||
max_position_embeddings=16384,
|
||||
initializer_range=0.02,
|
||||
rms_norm_eps=1e-5,
|
||||
use_cache=True,
|
||||
tie_word_embeddings=False,
|
||||
rope_theta=10000.0,
|
||||
rope_scaling=None,
|
||||
num_experts=64,
|
||||
num_experts_per_tok=6,
|
||||
num_shared_experts=2,
|
||||
num_expert_groups=1,
|
||||
num_limited_groups=1,
|
||||
score_func="sigmoid",
|
||||
route_norm=True,
|
||||
route_scale=1.0,
|
||||
load_balance_coeff: float | None = None,
|
||||
use_grouped_mm: bool = True,
|
||||
global_attn_every_n_layers=4,
|
||||
sliding_window=1024,
|
||||
mup_enabled=False,
|
||||
layer_types=None,
|
||||
attention_dropout: float = 0.0,
|
||||
n_group: int = 1,
|
||||
topk_group: int = 1,
|
||||
pad_token_id: int | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
self.vocab_size = vocab_size
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
self.hidden_size = hidden_size
|
||||
self.intermediate_size = intermediate_size
|
||||
self.num_hidden_layers = num_hidden_layers
|
||||
self.num_dense_layers = num_dense_layers
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.head_dim = head_dim
|
||||
self.hidden_act = hidden_act
|
||||
self.initializer_range = initializer_range
|
||||
self.rms_norm_eps = rms_norm_eps
|
||||
self.use_cache = use_cache
|
||||
self.rope_theta = rope_theta
|
||||
self.rope_scaling = rope_scaling
|
||||
|
||||
# MoE specific
|
||||
self.moe_intermediate_size = moe_intermediate_size
|
||||
self.num_experts_per_tok = num_experts_per_tok
|
||||
self.n_group = n_group
|
||||
self.topk_group = topk_group
|
||||
self.num_experts = num_experts
|
||||
self.num_shared_experts = num_shared_experts
|
||||
self.num_expert_groups = num_expert_groups
|
||||
self.num_limited_groups = num_limited_groups
|
||||
self.score_func = score_func
|
||||
self.route_norm = route_norm
|
||||
self.route_scale = route_scale
|
||||
self.load_balance_coeff = load_balance_coeff
|
||||
self.use_grouped_mm = use_grouped_mm
|
||||
|
||||
# Attention specific
|
||||
self.attention_dropout = attention_dropout
|
||||
self.global_attn_every_n_layers = global_attn_every_n_layers
|
||||
self.sliding_window = sliding_window
|
||||
self.layer_types = layer_types
|
||||
if self.layer_types is None:
|
||||
self.layer_types = [
|
||||
"sliding_attention" if bool((i + 1) % global_attn_every_n_layers) else "full_attention"
|
||||
for i in range(self.num_hidden_layers)
|
||||
]
|
||||
layer_type_validation(self.layer_types)
|
||||
|
||||
# muP specific
|
||||
self.mup_enabled = mup_enabled
|
||||
|
||||
if num_key_value_heads is None:
|
||||
num_key_value_heads = num_attention_heads
|
||||
|
||||
self.num_key_value_heads = num_key_value_heads
|
||||
self.pad_token_id = pad_token_id
|
||||
|
||||
super().__init__(
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["AfmoeConfig"]
|
||||
@@ -1,645 +0,0 @@
|
||||
from typing import Callable, Optional, Tuple, Union
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import nn
|
||||
from transformers.activations import ACT2FN
|
||||
from transformers.cache_utils import Cache, DynamicCache
|
||||
from transformers.generation import GenerationMixin
|
||||
from transformers.integrations import use_kernel_forward_from_hub
|
||||
from transformers.masking_utils import (
|
||||
create_causal_mask,
|
||||
create_sliding_window_causal_mask,
|
||||
)
|
||||
from transformers.modeling_layers import GradientCheckpointingLayer
|
||||
from transformers.modeling_outputs import (
|
||||
MoeCausalLMOutputWithPast,
|
||||
MoeModelOutputWithPast,
|
||||
)
|
||||
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
|
||||
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
||||
from transformers.processing_utils import Unpack
|
||||
from transformers.utils import TransformersKwargs
|
||||
|
||||
try:
|
||||
from .configuration_afmoe import AfmoeConfig
|
||||
except:
|
||||
from configuration_afmoe import AfmoeConfig
|
||||
|
||||
|
||||
class AfmoeRotaryEmbedding(nn.Module):
|
||||
def __init__(self, config: AfmoeConfig, device=None):
|
||||
super().__init__()
|
||||
# BC: "rope_type" was originally "type"
|
||||
if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
|
||||
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
||||
else:
|
||||
self.rope_type = "default"
|
||||
self.max_seq_len_cached = config.max_position_embeddings
|
||||
self.original_max_seq_len = config.max_position_embeddings
|
||||
|
||||
self.config = config
|
||||
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
||||
|
||||
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
||||
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
||||
self.original_inv_freq = self.inv_freq
|
||||
|
||||
def compute_default_rope_parameters(self, config=None, device=None, seq_len=None, layer_type=None):
|
||||
"""Required by transformers 5.0.0 for weight initialization when rope_type is 'default'."""
|
||||
cfg = config or self.config
|
||||
cfg.standardize_rope_params()
|
||||
rope_params = cfg.rope_parameters[layer_type] if layer_type is not None else cfg.rope_parameters
|
||||
base = rope_params["rope_theta"]
|
||||
partial_rotary_factor = rope_params.get("partial_rotary_factor", 1.0)
|
||||
head_dim = getattr(cfg, "head_dim", None) or cfg.hidden_size // cfg.num_attention_heads
|
||||
dim = int(head_dim * partial_rotary_factor)
|
||||
inv_freq = 1.0 / (
|
||||
base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
|
||||
)
|
||||
return inv_freq, 1.0
|
||||
|
||||
def _dynamic_frequency_update(self, position_ids, device):
|
||||
"""
|
||||
dynamic RoPE layers should recompute `inv_freq` in the following situations:
|
||||
1 - growing beyond the cached sequence length (allow scaling)
|
||||
2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
|
||||
"""
|
||||
seq_len = torch.max(position_ids) + 1
|
||||
if seq_len > self.max_seq_len_cached: # growth
|
||||
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
|
||||
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
||||
self.max_seq_len_cached = seq_len
|
||||
|
||||
if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
|
||||
# This .to() is needed if the model has been moved to a device after being initialized (because
|
||||
# the buffer is automatically moved, but not the original copy)
|
||||
self.original_inv_freq = self.original_inv_freq.to(device)
|
||||
self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
|
||||
self.max_seq_len_cached = self.original_max_seq_len
|
||||
|
||||
@torch.no_grad()
|
||||
def forward(self, x, position_ids):
|
||||
if "dynamic" in self.rope_type:
|
||||
self._dynamic_frequency_update(position_ids, device=x.device)
|
||||
|
||||
# Core RoPE block
|
||||
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
||||
position_ids_expanded = position_ids[:, None, :].float()
|
||||
# Force float32 (see https://github.com/huggingface/transformers/pull/29285)
|
||||
device_type = x.device.type
|
||||
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
|
||||
with torch.autocast(device_type=device_type, enabled=False):
|
||||
freqs = (inv_freq_expanded.float().to(x.device) @ position_ids_expanded.float()).transpose(1, 2)
|
||||
emb = torch.cat((freqs, freqs), dim=-1)
|
||||
cos = emb.cos()
|
||||
sin = emb.sin()
|
||||
|
||||
# Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
|
||||
cos = cos * self.attention_scaling
|
||||
sin = sin * self.attention_scaling
|
||||
|
||||
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
||||
|
||||
|
||||
def rotate_half(x):
|
||||
"""Rotates half the hidden dims of the input."""
|
||||
x1 = x[..., : x.shape[-1] // 2]
|
||||
x2 = x[..., x.shape[-1] // 2 :]
|
||||
return torch.cat((-x2, x1), dim=-1)
|
||||
|
||||
|
||||
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
||||
"""Applies Rotary Position Embedding to the query and key tensors.
|
||||
Args:
|
||||
q (`torch.Tensor`): The query tensor.
|
||||
k (`torch.Tensor`): The key tensor.
|
||||
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
||||
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
||||
position_ids (`torch.Tensor`, *optional*):
|
||||
Deprecated and unused.
|
||||
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
||||
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
||||
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
||||
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
||||
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
||||
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
||||
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
||||
Returns:
|
||||
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
||||
"""
|
||||
cos = cos.unsqueeze(unsqueeze_dim)
|
||||
sin = sin.unsqueeze(unsqueeze_dim)
|
||||
q_embed = (q * cos) + (rotate_half(q) * sin)
|
||||
k_embed = (k * cos) + (rotate_half(k) * sin)
|
||||
return q_embed, k_embed
|
||||
|
||||
|
||||
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
||||
"""
|
||||
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
||||
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
||||
"""
|
||||
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
||||
if n_rep == 1:
|
||||
return hidden_states
|
||||
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
||||
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
||||
|
||||
|
||||
@use_kernel_forward_from_hub("RMSNorm")
|
||||
class AfmoeRMSNorm(nn.Module):
|
||||
def __init__(self, hidden_size: int, eps: float):
|
||||
"""
|
||||
AfmoeRMSNorm is equivalent to T5LayerNorm
|
||||
"""
|
||||
super().__init__()
|
||||
self.weight = nn.Parameter(torch.ones(hidden_size))
|
||||
self.variance_epsilon = eps
|
||||
|
||||
def forward(self, hidden_states):
|
||||
input_dtype = hidden_states.dtype
|
||||
hidden_states = hidden_states.to(torch.float32)
|
||||
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
||||
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
||||
return self.weight * hidden_states.to(input_dtype)
|
||||
|
||||
def extra_repr(self):
|
||||
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
||||
|
||||
|
||||
def eager_attention_forward(
|
||||
module: nn.Module,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
attention_mask: Optional[torch.Tensor],
|
||||
scaling: float,
|
||||
dropout: float = 0.0,
|
||||
**kwargs,
|
||||
):
|
||||
key_states = repeat_kv(key, module.num_key_value_groups)
|
||||
value_states = repeat_kv(value, module.num_key_value_groups)
|
||||
|
||||
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
||||
if attention_mask is not None:
|
||||
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
||||
attn_weights = attn_weights + causal_mask
|
||||
|
||||
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
||||
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
||||
attn_output = torch.matmul(attn_weights, value_states)
|
||||
attn_output = attn_output.transpose(1, 2).contiguous()
|
||||
|
||||
return attn_output, attn_weights
|
||||
|
||||
|
||||
class AfmoeMLP(nn.Module):
|
||||
def __init__(self, config, intermediate_size=None):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.hidden_size = config.hidden_size
|
||||
self.intermediate_size = intermediate_size or config.intermediate_size
|
||||
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
||||
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
||||
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
||||
self.act_fn = ACT2FN[config.hidden_act]
|
||||
|
||||
def forward(self, x):
|
||||
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
||||
|
||||
|
||||
class AfmoeTokenChoiceRouter(nn.Module):
|
||||
"""Token-choice top-K router for MoE routing."""
|
||||
|
||||
def __init__(self, config):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.top_k = config.num_experts_per_tok
|
||||
self.num_experts = config.num_experts
|
||||
self.score_func = config.score_func
|
||||
self.route_norm = config.route_norm
|
||||
self.route_scale = config.route_scale
|
||||
self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=False)
|
||||
|
||||
def forward(self, hidden_states, expert_bias: torch.Tensor | None):
|
||||
_, _, hidden_dim = hidden_states.shape
|
||||
hidden_states = hidden_states.view(-1, hidden_dim)
|
||||
|
||||
scores = self.gate(hidden_states)
|
||||
|
||||
# Apply scoring function in float32 for stability
|
||||
if self.score_func == "sigmoid":
|
||||
scores = torch.sigmoid(scores.to(torch.float32))
|
||||
else:
|
||||
scores = F.softmax(scores.to(torch.float32), dim=-1)
|
||||
|
||||
if expert_bias is not None:
|
||||
_, selected_experts = torch.topk(scores + expert_bias, k=self.top_k, dim=1)
|
||||
top_scores = scores.gather(dim=1, index=selected_experts)
|
||||
else:
|
||||
top_scores, selected_experts = torch.topk(scores, k=self.top_k, dim=1)
|
||||
|
||||
# Normalize weights if using sigmoid
|
||||
if self.score_func == "sigmoid" and self.route_norm:
|
||||
denominator = top_scores.sum(dim=-1, keepdim=True) + 1e-20
|
||||
top_scores = top_scores / denominator
|
||||
|
||||
top_scores = top_scores * self.route_scale
|
||||
return top_scores, selected_experts
|
||||
|
||||
|
||||
class AfmoeMoE(nn.Module):
|
||||
def __init__(self, config):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.router = AfmoeTokenChoiceRouter(config)
|
||||
|
||||
self.shared_experts = None
|
||||
if config.num_shared_experts > 0:
|
||||
self.shared_experts = AfmoeMLP(config, config.moe_intermediate_size * config.num_shared_experts)
|
||||
self.experts = nn.ModuleList(
|
||||
[AfmoeMLP(config, intermediate_size=config.moe_intermediate_size) for _ in range(config.num_experts)]
|
||||
)
|
||||
self.expert_bias = nn.Parameter(torch.zeros(config.num_experts, dtype=torch.float32), requires_grad=False)
|
||||
|
||||
def forward(self, hidden_states):
|
||||
batch_size, seq_len, hidden_dim = hidden_states.shape
|
||||
hidden_states_flat = hidden_states.view(-1, hidden_dim)
|
||||
|
||||
# Get routing decisions
|
||||
top_scores, selected_experts = self.router(hidden_states, self.expert_bias)
|
||||
|
||||
# Process through shared experts
|
||||
if self.shared_experts is not None:
|
||||
shared_output = self.shared_experts(hidden_states_flat)
|
||||
else:
|
||||
shared_output = torch.zeros_like(hidden_states_flat)
|
||||
|
||||
# Reorder tokens by expert for efficient processing
|
||||
token_indices_sorted = torch.argsort(selected_experts.view(-1), stable=True)
|
||||
top_scores_sorted = top_scores.view(-1)[token_indices_sorted]
|
||||
token_to_expert = selected_experts.view(-1)[token_indices_sorted]
|
||||
token_indices_sorted = token_indices_sorted // self.config.num_experts_per_tok
|
||||
|
||||
# Gather input tokens
|
||||
token_indices_expanded = token_indices_sorted.unsqueeze(-1).expand(-1, hidden_dim)
|
||||
routed_input = torch.gather(hidden_states_flat, dim=0, index=token_indices_expanded)
|
||||
|
||||
routed_output = torch.zeros_like(routed_input)
|
||||
for expert_id in range(self.config.num_experts):
|
||||
mask = token_to_expert == expert_id
|
||||
if mask.any():
|
||||
expert_input = routed_input[mask]
|
||||
expert_out = self.experts[expert_id](expert_input)
|
||||
routed_output[mask] = expert_out
|
||||
|
||||
routed_output = (routed_output.to(torch.float32) * top_scores_sorted.unsqueeze(-1)).to(hidden_states.dtype)
|
||||
|
||||
# Scatter back to original positions
|
||||
output = shared_output.scatter_add(dim=0, index=token_indices_expanded, src=routed_output)
|
||||
|
||||
return output.view(batch_size, seq_len, hidden_dim)
|
||||
|
||||
|
||||
class AfmoeAttention(nn.Module):
|
||||
"""Multi-headed attention with local/global pattern and gating."""
|
||||
|
||||
def __init__(self, config: AfmoeConfig, layer_idx: int):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.layer_idx = layer_idx
|
||||
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
||||
self.num_heads = config.num_attention_heads
|
||||
self.num_key_value_heads = config.num_key_value_heads
|
||||
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
||||
|
||||
self.scaling = self.head_dim**-0.5
|
||||
self.attention_dropout = config.attention_dropout
|
||||
self.is_local_attention = config.layer_types[layer_idx] == "sliding_attention"
|
||||
self.sliding_window = config.sliding_window if self.is_local_attention else None
|
||||
|
||||
self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim, bias=False)
|
||||
self.k_proj = nn.Linear(config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
||||
self.v_proj = nn.Linear(config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
||||
self.o_proj = nn.Linear(self.num_heads * self.head_dim, config.hidden_size, bias=False)
|
||||
|
||||
self.q_norm = AfmoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
||||
self.k_norm = AfmoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
||||
|
||||
self.gate_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim, bias=False)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
attention_mask: Optional[torch.Tensor],
|
||||
past_key_value: Optional[Cache] = None,
|
||||
cache_position: Optional[torch.LongTensor] = None,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> torch.Tensor:
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
hidden_shape = (*input_shape, -1, self.head_dim)
|
||||
|
||||
query_states = self.q_proj(hidden_states).view(hidden_shape)
|
||||
key_states = self.k_proj(hidden_states).view(hidden_shape)
|
||||
value_states = self.v_proj(hidden_states).view(hidden_shape)
|
||||
gate_states = self.gate_proj(hidden_states)
|
||||
|
||||
query_states = self.q_norm(query_states)
|
||||
key_states = self.k_norm(key_states)
|
||||
|
||||
query_states = query_states.transpose(1, 2)
|
||||
key_states = key_states.transpose(1, 2)
|
||||
value_states = value_states.transpose(1, 2)
|
||||
|
||||
if self.is_local_attention:
|
||||
cos, sin = position_embeddings
|
||||
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
||||
|
||||
if past_key_value is not None:
|
||||
cache_kwargs = {"cache_position": cache_position}
|
||||
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
||||
|
||||
attention_interface: Callable = eager_attention_forward
|
||||
if self.config._attn_implementation != "eager":
|
||||
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
||||
|
||||
output, _ = attention_interface(
|
||||
self,
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
attention_mask=attention_mask,
|
||||
dropout=0.0 if not self.training else self.attention_dropout,
|
||||
scaling=self.scaling,
|
||||
sliding_window=self.sliding_window,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
output = output.view(*input_shape, -1).contiguous()
|
||||
output = output * F.sigmoid(gate_states)
|
||||
return self.o_proj(output)
|
||||
|
||||
|
||||
class AfmoeDecoderLayer(GradientCheckpointingLayer):
|
||||
def __init__(self, config: AfmoeConfig, layer_idx: int):
|
||||
super().__init__()
|
||||
self.hidden_size = config.hidden_size
|
||||
self.layer_idx = layer_idx
|
||||
|
||||
self.self_attn = AfmoeAttention(config=config, layer_idx=layer_idx)
|
||||
self.attention_type = config.layer_types[layer_idx]
|
||||
|
||||
# Dual normalization for attention
|
||||
self.input_layernorm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.post_attention_layernorm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
|
||||
# Dual normalization for FFN
|
||||
self.pre_mlp_layernorm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.post_mlp_layernorm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
|
||||
# MoE or dense FFN
|
||||
self.moe_enabled = layer_idx >= config.num_dense_layers
|
||||
if self.moe_enabled:
|
||||
self.mlp = AfmoeMoE(config)
|
||||
else:
|
||||
self.mlp = AfmoeMLP(config)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
attention_mask: Optional[torch.Tensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
past_key_value: Optional[Cache] = None,
|
||||
use_cache: Optional[bool] = None,
|
||||
cache_position: Optional[torch.LongTensor] = None,
|
||||
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> torch.FloatTensor:
|
||||
residual = hidden_states
|
||||
|
||||
# Self Attention with dual normalization
|
||||
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_value=past_key_value,
|
||||
use_cache=use_cache,
|
||||
cache_position=cache_position,
|
||||
position_embeddings=position_embeddings,
|
||||
**kwargs,
|
||||
)
|
||||
hidden_states = self.post_attention_layernorm(hidden_states)
|
||||
hidden_states = residual + hidden_states
|
||||
|
||||
# FFN with dual normalization
|
||||
residual = hidden_states
|
||||
hidden_states = self.pre_mlp_layernorm(hidden_states)
|
||||
|
||||
if self.moe_enabled:
|
||||
hidden_states = self.mlp(hidden_states)
|
||||
else:
|
||||
hidden_states = self.mlp(hidden_states)
|
||||
|
||||
hidden_states = self.post_mlp_layernorm(hidden_states)
|
||||
hidden_states = residual + hidden_states
|
||||
return hidden_states
|
||||
|
||||
|
||||
class AfmoePreTrainedModel(PreTrainedModel):
|
||||
config_class = AfmoeConfig
|
||||
base_model_prefix = "model"
|
||||
_no_split_modules = ["AfmoeDecoderLayer"]
|
||||
_skip_keys_device_placement = ["past_key_values"]
|
||||
_keep_in_fp32_modules = [
|
||||
"input_layernorm",
|
||||
"post_attention_layernorm",
|
||||
"pre_mlp_layernorm",
|
||||
"post_mlp_layernorm",
|
||||
"q_norm",
|
||||
"k_norm",
|
||||
"norm",
|
||||
]
|
||||
_supports_sdpa = True
|
||||
_supports_attention_backend = True
|
||||
supports_gradient_checkpointing = True
|
||||
|
||||
|
||||
class AfmoeModel(AfmoePreTrainedModel):
|
||||
_no_split_modules = ["AfmoeDecoderLayer"]
|
||||
|
||||
def __init__(self, config: AfmoeConfig):
|
||||
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(
|
||||
[AfmoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
||||
)
|
||||
self.norm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.rotary_emb = AfmoeRotaryEmbedding(config=config)
|
||||
self.gradient_checkpointing = False
|
||||
|
||||
self.post_init()
|
||||
|
||||
def get_input_embeddings(self):
|
||||
return self.embed_tokens
|
||||
|
||||
def set_input_embeddings(self, value):
|
||||
self.embed_tokens = value
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.LongTensor,
|
||||
attention_mask: Optional[torch.Tensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
past_key_values: Optional[list[torch.FloatTensor]] = None,
|
||||
inputs_embeds: Optional[torch.FloatTensor] = None,
|
||||
use_cache: Optional[bool] = None,
|
||||
cache_position: Optional[torch.LongTensor] = 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")
|
||||
|
||||
if use_cache and past_key_values is None:
|
||||
past_key_values = DynamicCache()
|
||||
|
||||
if inputs_embeds is None:
|
||||
inputs_embeds = self.embed_tokens(input_ids)
|
||||
|
||||
if cache_position is None:
|
||||
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
||||
cache_position = torch.arange(
|
||||
past_seen_tokens,
|
||||
past_seen_tokens + inputs_embeds.shape[1],
|
||||
device=inputs_embeds.device,
|
||||
)
|
||||
if position_ids is None:
|
||||
position_ids = cache_position.unsqueeze(0)
|
||||
|
||||
# It may already have been prepared by e.g. `generate`
|
||||
if not isinstance(causal_mask_mapping := attention_mask, dict):
|
||||
mask_kwargs = {
|
||||
"config": self.config,
|
||||
"inputs_embeds": inputs_embeds,
|
||||
"attention_mask": attention_mask,
|
||||
"cache_position": cache_position,
|
||||
"past_key_values": past_key_values,
|
||||
}
|
||||
causal_mask_mapping = {
|
||||
"full_attention": create_causal_mask(**mask_kwargs),
|
||||
"sliding_attention": create_sliding_window_causal_mask(**mask_kwargs),
|
||||
}
|
||||
|
||||
hidden_states = inputs_embeds
|
||||
|
||||
# Apply muP input scaling if enabled
|
||||
if self.config.mup_enabled:
|
||||
hidden_states = hidden_states * (self.config.hidden_size**0.5)
|
||||
|
||||
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
||||
|
||||
for decoder_layer in self.layers:
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
attention_mask=causal_mask_mapping[decoder_layer.attention_type],
|
||||
position_ids=position_ids,
|
||||
past_key_value=past_key_values,
|
||||
use_cache=use_cache,
|
||||
cache_position=cache_position,
|
||||
position_embeddings=position_embeddings,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
hidden_states = self.norm(hidden_states)
|
||||
return MoeModelOutputWithPast(
|
||||
last_hidden_state=hidden_states,
|
||||
past_key_values=past_key_values,
|
||||
)
|
||||
|
||||
|
||||
class AfmoeForCausalLM(AfmoePreTrainedModel, GenerationMixin):
|
||||
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
||||
_tp_plan = {"lm_head": "colwise_rep"}
|
||||
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
||||
|
||||
def __init__(self, config):
|
||||
super().__init__(config)
|
||||
self.model = AfmoeModel(config)
|
||||
self.vocab_size = config.vocab_size
|
||||
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
||||
|
||||
# Initialize weights and apply final processing
|
||||
self.post_init()
|
||||
|
||||
def get_input_embeddings(self):
|
||||
return self.model.embed_tokens
|
||||
|
||||
def set_input_embeddings(self, value):
|
||||
self.model.embed_tokens = value
|
||||
|
||||
def get_output_embeddings(self):
|
||||
return self.lm_head
|
||||
|
||||
def set_output_embeddings(self, new_embeddings):
|
||||
self.lm_head = new_embeddings
|
||||
|
||||
def set_decoder(self, decoder):
|
||||
self.model = decoder
|
||||
|
||||
def get_decoder(self):
|
||||
return self.model
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.LongTensor,
|
||||
attention_mask: Optional[torch.Tensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
past_key_values: Optional[Cache] = None,
|
||||
inputs_embeds: Optional[torch.FloatTensor] = None,
|
||||
labels: Optional[torch.LongTensor] = None,
|
||||
use_cache: Optional[bool] = None,
|
||||
cache_position: Optional[torch.LongTensor] = None,
|
||||
logits_to_keep: Union[int, torch.Tensor] = 0,
|
||||
token_type_ids: Optional[torch.Tensor] = None, # will be ignored
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> Union[Tuple, MoeCausalLMOutputWithPast]:
|
||||
outputs: MoeModelOutputWithPast = 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,
|
||||
cache_position=cache_position,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
hidden_states = outputs.last_hidden_state
|
||||
# Only compute necessary logits
|
||||
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
||||
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
||||
|
||||
loss = None
|
||||
if labels is not None:
|
||||
loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
|
||||
|
||||
return MoeCausalLMOutputWithPast(
|
||||
loss=loss,
|
||||
logits=logits,
|
||||
past_key_values=outputs.past_key_values,
|
||||
hidden_states=outputs.hidden_states,
|
||||
attentions=outputs.attentions,
|
||||
router_logits=outputs.router_logits,
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"AfmoeForCausalLM",
|
||||
"AfmoeModel",
|
||||
"AfmoePreTrainedModel",
|
||||
]
|
||||
@@ -1,183 +0,0 @@
|
||||
import pytest
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.trainer.models.afmoe import AfmoeForCausalLM as PrimeRLAfmoeForCausalLM
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
from prime_rl.utils.utils import default_dtype
|
||||
from tests.unit.train.models.afmoe_hf_modeling.configuration_afmoe import AfmoeConfig
|
||||
from tests.unit.train.models.afmoe_hf_modeling.modeling_afmoe import (
|
||||
AfmoeForCausalLM as HFAfmoeForCausalLM,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.skip(reason="HF afmoe model does not support flash attention 2")]
|
||||
|
||||
|
||||
def get_model_pairs():
|
||||
hf_config = AfmoeConfig(
|
||||
architectures=["AfmoeForCausalLM"],
|
||||
attention_dropout=0.0,
|
||||
global_attn_every_n_layers=2,
|
||||
head_dim=64,
|
||||
hidden_act="silu",
|
||||
hidden_size=256,
|
||||
initializer_range=0.02,
|
||||
intermediate_size=512,
|
||||
layer_types=[
|
||||
"sliding_attention",
|
||||
"full_attention",
|
||||
"sliding_attention",
|
||||
"full_attention",
|
||||
],
|
||||
load_balance_coeff=0.001,
|
||||
max_position_embeddings=512,
|
||||
moe_intermediate_size=128,
|
||||
mup_enabled=True,
|
||||
n_group=1,
|
||||
num_attention_heads=4,
|
||||
num_dense_layers=2,
|
||||
num_expert_groups=1,
|
||||
num_experts=4,
|
||||
num_experts_per_tok=2,
|
||||
num_hidden_layers=4,
|
||||
num_key_value_heads=2,
|
||||
num_limited_groups=1,
|
||||
num_shared_experts=1,
|
||||
rms_norm_eps=1e-5,
|
||||
rope_scaling=None,
|
||||
rope_theta=10000.0,
|
||||
route_norm=True,
|
||||
route_scale=2.826,
|
||||
score_func="sigmoid",
|
||||
sliding_window=128,
|
||||
tie_word_embeddings=False,
|
||||
topk_group=1,
|
||||
use_cache=True,
|
||||
use_grouped_mm=False,
|
||||
vocab_size=256,
|
||||
)
|
||||
hf_config._attn_implementation = "flash_attention_2"
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
hf_model = HFAfmoeForCausalLM._from_config(hf_config)
|
||||
prime_model = PrimeRLAfmoeForCausalLM._from_config(hf_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
|
||||
|
||||
|
||||
class _IdentityMLP(nn.Identity):
|
||||
def forward(self, x, **kwargs):
|
||||
return super().forward(x)
|
||||
|
||||
|
||||
def test_afmoe_attn_only() -> None:
|
||||
hf_model, prime_model = get_model_pairs()
|
||||
for layer in hf_model.model.layers:
|
||||
layer.mlp = nn.Identity()
|
||||
for layer in prime_model.model.layers:
|
||||
layer.mlp = _IdentityMLP()
|
||||
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
input_ids = torch.randint(0, hf_model.config.vocab_size, (1, 100))
|
||||
position_ids = torch.arange(1, 101).unsqueeze(0)
|
||||
|
||||
hf_output = hf_model(input_ids, position_ids=position_ids)
|
||||
prime_output = prime_model(
|
||||
input_ids,
|
||||
position_ids=position_ids,
|
||||
seq_lens=torch.tensor([input_ids.shape[1]], device="cuda"),
|
||||
)
|
||||
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=2e-2), (
|
||||
f"Max logits diff: {logits_diff.abs().max()}"
|
||||
)
|
||||
grad_diff = hf_model.model.embed_tokens.weight.grad - prime_model.model.embed_tokens.weight.grad
|
||||
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
|
||||
|
||||
|
||||
def test_afmoe_mlp_only() -> None:
|
||||
hf_model, prime_model = get_model_pairs()
|
||||
|
||||
# HF AfmoeAttention.forward() returns a single tensor
|
||||
def identity_attn_hf(hidden_states: torch.Tensor, *args, **kwargs) -> torch.Tensor:
|
||||
return hidden_states
|
||||
|
||||
# PrimeRL attention returns a tuple (output, attn_weights)
|
||||
def identity_attn_prime(hidden_states: torch.Tensor, *args, **kwargs) -> tuple[torch.Tensor, None]:
|
||||
return hidden_states, None
|
||||
|
||||
for layer in hf_model.model.layers:
|
||||
layer.self_attn.forward = identity_attn_hf
|
||||
for layer in prime_model.model.layers:
|
||||
layer.self_attn.forward = identity_attn_prime
|
||||
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
input_ids = torch.randint(0, hf_model.config.vocab_size, (1, 100))
|
||||
position_ids = torch.arange(1, 101).unsqueeze(0)
|
||||
|
||||
hf_output = hf_model(input_ids, position_ids=position_ids)
|
||||
prime_output = prime_model(
|
||||
input_ids,
|
||||
position_ids=position_ids,
|
||||
seq_lens=torch.tensor([input_ids.shape[1]], device="cuda"),
|
||||
)
|
||||
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=2e-2), (
|
||||
f"Max logits diff: {logits_diff.abs().max()}"
|
||||
)
|
||||
grad_diff = hf_model.model.embed_tokens.weight.grad - prime_model.model.embed_tokens.weight.grad
|
||||
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
|
||||
|
||||
|
||||
def test_afmoe() -> None:
|
||||
hf_model, prime_model = get_model_pairs()
|
||||
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
input_ids = torch.randint(0, hf_model.config.vocab_size, (1, 100))
|
||||
position_ids = torch.arange(1, 101).unsqueeze(0)
|
||||
|
||||
hf_output = hf_model(input_ids, position_ids=position_ids)
|
||||
prime_output = prime_model(
|
||||
input_ids,
|
||||
position_ids=position_ids,
|
||||
seq_lens=torch.tensor([input_ids.shape[1]], device="cuda"),
|
||||
)
|
||||
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=2e-2), (
|
||||
f"Max logits diff: {logits_diff.abs().max()}"
|
||||
)
|
||||
grad_diff = hf_model.model.embed_tokens.weight.grad - prime_model.model.embed_tokens.weight.grad
|
||||
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
|
||||
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
hf_from_prime_model = HFAfmoeForCausalLM._from_config(hf_model.config)
|
||||
converted_state_dict = prime_model.convert_to_hf(prime_model.state_dict())
|
||||
hf_from_prime_model.load_state_dict(converted_state_dict)
|
||||
|
||||
hf_from_prime_output = hf_from_prime_model(input_ids, position_ids=position_ids)
|
||||
hf_from_prime_output.logits.sum().backward()
|
||||
|
||||
logits_diff = hf_from_prime_output.logits - hf_output.logits
|
||||
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
|
||||
f"Max logits diff: {logits_diff.abs().max()}"
|
||||
)
|
||||
grad_diff = hf_from_prime_model.model.embed_tokens.weight.grad - hf_model.model.embed_tokens.weight.grad
|
||||
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_afmoe()
|
||||
@@ -5,9 +5,8 @@ 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.model import compute_expert_load_stats, is_tt_moe_model
|
||||
from prime_rl.trainer.models.deepseek_v4.moe import DeepseekV4Experts
|
||||
from prime_rl.trainer.models.fusions import fuse_gate_up_projections
|
||||
from prime_rl.trainer.models.layers.activations import ActivationDispatch
|
||||
from prime_rl.trainer.models.layers.activations import ActivationDispatch, ClampedSilu
|
||||
from prime_rl.trainer.models.layers.expert_compute import BF16ExpertCompute, GroupedGemmExpertCompute
|
||||
from prime_rl.trainer.models.layers.mlp import FeedForward
|
||||
from prime_rl.trainer.models.layers.moe import (
|
||||
@@ -69,7 +68,7 @@ def test_unselected_moe_uses_bf16_without_loading_compute_backend(selection, com
|
||||
pytest.param(GroupedExperts, {"activation": "relu2"}, True, "standard SwiGLU", id="relu2"),
|
||||
pytest.param(GroupedExperts, {"activation": "clamped_swiglu"}, True, "standard SwiGLU", id="clamped-swiglu"),
|
||||
pytest.param(GroupedExperts, {"bias": True}, True, "bias-free", id="bias"),
|
||||
pytest.param(DeepseekV4Experts, {"swiglu_limit": 10.0}, True, "standard SwiGLU", id="deepseek-v4"),
|
||||
pytest.param(GroupedExperts, {"activation": ClampedSilu(10.0)}, True, "standard SwiGLU", id="deepseek-v4"),
|
||||
],
|
||||
)
|
||||
def test_set_compute_validates_sonic_expert_structure(expert_cls, kwargs, fused, error):
|
||||
|
||||
@@ -5,7 +5,7 @@ from transformers.models.qwen3.configuration_qwen3 import Qwen3Config
|
||||
from prime_rl.trainer.models import cast_float_and_contiguous
|
||||
from prime_rl.trainer.models.layers.lm_head import FusedOutputLinear, VanillaOutputLinear, inject_prime_lm_head
|
||||
from prime_rl.trainer.models.qwen3 import Qwen3ForCausalLM
|
||||
from prime_rl.trainer.rl.loss import compute_entropy, selective_log_softmax, shift_tensor_left, shift_tensor_right
|
||||
from prime_rl.trainer.rl.loss import compute_entropy, shift_tensor_left, shift_tensor_right
|
||||
from prime_rl.utils.utils import default_dtype
|
||||
|
||||
|
||||
@@ -160,95 +160,6 @@ def test_fused_vs_vanilla_integration():
|
||||
torch.testing.assert_close(fused_out["entropy"], vanilla_entropy, rtol=1e-3, atol=1e-4)
|
||||
|
||||
|
||||
@pytest.mark.gpu
|
||||
@pytest.mark.skip(reason="Produces NaNs in bf16 with FA3; needs investigation")
|
||||
def test_full_model_fused_vs_vanilla():
|
||||
"""Full model integration test comparing fused vs vanilla LM head across multiple training steps."""
|
||||
torch.manual_seed(123)
|
||||
|
||||
# Create tiny Qwen3 model for fast testing
|
||||
config = Qwen3Config(
|
||||
hidden_size=128,
|
||||
intermediate_size=256,
|
||||
max_position_embeddings=512,
|
||||
num_attention_heads=4,
|
||||
num_key_value_heads=2,
|
||||
head_dim=32,
|
||||
num_hidden_layers=2,
|
||||
vocab_size=1000,
|
||||
rms_norm_eps=1e-5,
|
||||
rope_theta=10000.0,
|
||||
attention_bias=False,
|
||||
)
|
||||
|
||||
with torch.device("cuda"), default_dtype(torch.bfloat16):
|
||||
# Create two identical models
|
||||
model_vanilla = Qwen3ForCausalLM._from_config(config)
|
||||
model_fused = Qwen3ForCausalLM._from_config(config)
|
||||
|
||||
# Share weights between models
|
||||
model_fused.load_state_dict(model_vanilla.state_dict())
|
||||
|
||||
# Wrap with different LM heads
|
||||
inject_prime_lm_head(model_vanilla, chunk_size=None) # Vanilla
|
||||
inject_prime_lm_head(model_fused, chunk_size=32) # Fused with chunking
|
||||
|
||||
# Setup optimizers
|
||||
optimizer_vanilla = torch.optim.AdamW(model_vanilla.parameters(), lr=1e-4)
|
||||
optimizer_fused = torch.optim.AdamW(model_fused.parameters(), lr=1e-4)
|
||||
|
||||
# Run a few training steps
|
||||
num_steps = 3
|
||||
batch_size, seq_len = 2, 64
|
||||
temp_value = 1.5
|
||||
|
||||
for step in range(num_steps):
|
||||
# Generate random batch
|
||||
with torch.device("cuda"):
|
||||
labels = torch.randint(0, config.vocab_size, (batch_size, seq_len))
|
||||
position_ids = torch.arange(seq_len).unsqueeze(0).expand(batch_size, -1)
|
||||
temperature = torch.full((batch_size, seq_len), temp_value, dtype=torch.float32, device="cuda")
|
||||
seq_lens = torch.tensor([seq_len])
|
||||
|
||||
# Vanilla forward (returns logits, compute logprobs/entropy using RL train functions)
|
||||
optimizer_vanilla.zero_grad()
|
||||
out_vanilla = cast_float_and_contiguous(
|
||||
model_vanilla(labels, position_ids, labels=labels, temperature=temperature, seq_lens=seq_lens)
|
||||
)
|
||||
if out_vanilla.get("logprobs") is None:
|
||||
assert out_vanilla.get("logits") is not None
|
||||
logits = out_vanilla["logits"] / temp_value
|
||||
out_vanilla["logprobs"] = selective_log_softmax(logits, labels)
|
||||
out_vanilla["entropy"] = compute_entropy(logits)
|
||||
loss_vanilla = -out_vanilla["logprobs"].mean()
|
||||
loss_vanilla.backward()
|
||||
optimizer_vanilla.step()
|
||||
|
||||
# Fused forward (returns logprobs and entropy directly)
|
||||
optimizer_fused.zero_grad()
|
||||
out_fused = cast_float_and_contiguous(
|
||||
model_fused(labels, position_ids, labels=labels, temperature=temperature, seq_lens=seq_lens)
|
||||
)
|
||||
if out_fused.get("logprobs") is None:
|
||||
assert out_fused.get("logits") is not None
|
||||
logits = out_fused["logits"] / temp_value
|
||||
out_fused["logprobs"] = selective_log_softmax(logits, labels)
|
||||
out_fused["entropy"] = compute_entropy(logits)
|
||||
loss_fused = -out_fused["logprobs"].mean()
|
||||
loss_fused.backward()
|
||||
optimizer_fused.step()
|
||||
|
||||
# Compare outputs (should be very close since models started identical)
|
||||
torch.testing.assert_close(out_fused["logprobs"], out_vanilla["logprobs"], rtol=1e-3, atol=1e-4)
|
||||
torch.testing.assert_close(out_fused["entropy"], out_vanilla["entropy"], rtol=1e-3, atol=1e-4)
|
||||
torch.testing.assert_close(loss_fused, loss_vanilla, rtol=1e-3, atol=1e-4)
|
||||
|
||||
# After training, weights should still be close (optimizer steps should be similar)
|
||||
for (name_v, param_v), (name_f, param_f) in zip(model_vanilla.named_parameters(), model_fused.named_parameters()):
|
||||
if "lm_head" not in name_v: # Compare non-lm_head params
|
||||
torch.testing.assert_close(param_f, param_v, rtol=1e-3, atol=1e-4)
|
||||
|
||||
|
||||
def test_fused_lm_head_correct_shift():
|
||||
"""
|
||||
End-to-end test that the fused LM head with shifted labels, after shift_tensor_right,
|
||||
|
||||
@@ -69,61 +69,6 @@ def test_model_with_position_ids(model):
|
||||
assert logits.shape == (BS, SEQ_LEN, model.config.vocab_size)
|
||||
|
||||
|
||||
@pytest.mark.skip(reason="Sequence packing for Qwen not working.")
|
||||
@pytest.mark.parametrize("correct_position_ids", [True, False])
|
||||
def test_model_with_sequence_packing(model, correct_position_ids):
|
||||
"""
|
||||
The goal of this test is to check that the sequence packing works correctly.
|
||||
|
||||
The idea is that is to check that the logits is the same when doing
|
||||
|
||||
[B, seq] and doing [1, B*seq] with the proper masking.
|
||||
|
||||
"""
|
||||
if model.config.attn != "flash_attention_2":
|
||||
pytest.skip("Test only works with flash attention")
|
||||
|
||||
model = model.to("cuda")
|
||||
inputs = [0, 1, 2, 3]
|
||||
|
||||
with torch.autocast("cuda", dtype=torch.bfloat16):
|
||||
inputs_ids = torch.Tensor(inputs).repeat(1, 1).int().to("cuda")
|
||||
outputs = model(input_ids=inputs_ids, seq_lens=torch.tensor([len(inputs)], device="cuda"))
|
||||
output_base = outputs["logits"]
|
||||
|
||||
assert output_base.shape == (1, len(inputs), model.config.vocab_size)
|
||||
|
||||
with torch.autocast("cuda", dtype=torch.bfloat16):
|
||||
inputs_ids = torch.Tensor(inputs + inputs).repeat(1, 1).int().to("cuda")
|
||||
if correct_position_ids:
|
||||
position_ids = torch.Tensor([0, 1, 2, 3, 0, 1, 2, 3]).repeat(1, 1).int().to("cuda")
|
||||
# should work
|
||||
else:
|
||||
position_ids = torch.Tensor([0, 1, 2, 3, 4, 5, 6, 7]).repeat(1, 1).int().to("cuda")
|
||||
# should fail
|
||||
outputs = model(
|
||||
input_ids=inputs_ids,
|
||||
position_ids=position_ids,
|
||||
seq_lens=torch.tensor([len(inputs), len(inputs)], device="cuda"),
|
||||
)
|
||||
outputs_packed = outputs["logits"]
|
||||
|
||||
assert outputs_packed.shape == (1, 2 * len(inputs), model.config.vocab_size)
|
||||
|
||||
output_packed_left = outputs_packed[:, : len(inputs), :]
|
||||
output_packed_right = outputs_packed[:, len(inputs) :, :]
|
||||
|
||||
assert output_packed_left.shape == output_base.shape == output_packed_right.shape
|
||||
|
||||
if correct_position_ids:
|
||||
torch.testing.assert_close(output_packed_left, output_base)
|
||||
torch.testing.assert_close(output_packed_right, output_base)
|
||||
else:
|
||||
torch.testing.assert_close(output_packed_left, output_base)
|
||||
with pytest.raises(AssertionError):
|
||||
torch.testing.assert_close(output_packed_right, output_base)
|
||||
|
||||
|
||||
def test_moe_custom_impl():
|
||||
config = ModelConfig(name="PrimeIntellect/GLM-0.5B", attn="flash_attention_2")
|
||||
model = get_model(config)
|
||||
@@ -136,19 +81,3 @@ def test_moe_custom_impl():
|
||||
logits = outputs["logits"]
|
||||
|
||||
assert logits.shape == (BS, SEQ_LEN, model.config.vocab_size)
|
||||
|
||||
|
||||
@pytest.mark.skip(reason="need special token for meta stuff in ci")
|
||||
@pytest.mark.parametrize("model_name", ["meta-llama/Llama-3.2-1B-Instruct"])
|
||||
def test_model_forward_custom_impl(model_name):
|
||||
config = ModelConfig(name=model_name, attn="flash_attention_2")
|
||||
model = get_model(config)
|
||||
# we need to wrap the lm head as custom forward only works with it, this is done in setup_model
|
||||
inject_prime_lm_head(model, chunk_size=None)
|
||||
model = model.to("cuda")
|
||||
with torch.autocast("cuda", dtype=torch.bfloat16):
|
||||
inputs_ids = torch.randint(0, 100, (BS, SEQ_LEN)).to("cuda")
|
||||
outputs = model(input_ids=inputs_ids, seq_lens=torch.tensor([SEQ_LEN], device="cuda"))
|
||||
logits = outputs["logits"]
|
||||
|
||||
assert logits.shape == (BS, SEQ_LEN, model.config.vocab_size)
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
import multiprocessing as mp
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from prime_rl.inference.vllm.worker.nccl import NCCLWeightBroadcastReceiver
|
||||
from prime_rl.transports.weights.nccl import NCCLBroadcaster
|
||||
|
||||
pytestmark = [pytest.mark.gpu]
|
||||
|
||||
|
||||
@pytest.mark.skip(reason="Skipping NCCL broadcast as it fail only in ci")
|
||||
def test_nccl_broadcast(free_port):
|
||||
host = "localhost"
|
||||
free_port = free_port()
|
||||
|
||||
def send():
|
||||
device = torch.device(f"cuda:{0}")
|
||||
nccl_broadcast = NCCLBroadcaster(host=host, port=free_port, rank=0, world_size=2, device=device, timeout=10)
|
||||
|
||||
class SubModel(torch.nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
self.layers = torch.nn.ModuleList([torch.nn.Linear(10, 10) for _ in range(10)])
|
||||
|
||||
def forward(self, x):
|
||||
for layer in self.layers:
|
||||
x = layer(x)
|
||||
return x
|
||||
|
||||
class Model(torch.nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.model = SubModel()
|
||||
|
||||
def forward(self, x):
|
||||
return self.model(x)
|
||||
|
||||
model = Model().to(device)
|
||||
for param in model.parameters():
|
||||
param.data = torch.ones_like(param.data)
|
||||
|
||||
nccl_broadcast.send(model)
|
||||
|
||||
def receive():
|
||||
device = torch.device(f"cuda:{1}")
|
||||
nccl_broadcast = NCCLWeightBroadcastReceiver(
|
||||
host=host, port=free_port, rank=1, world_size=2, device=device, timeout=10
|
||||
)
|
||||
|
||||
for key, value in nccl_broadcast.receive_state_dict():
|
||||
assert value.allclose(torch.ones_like(value))
|
||||
|
||||
processes = [mp.Process(target=send), mp.Process(target=receive)]
|
||||
|
||||
for process in processes:
|
||||
process.start()
|
||||
|
||||
for process in processes:
|
||||
process.join()
|
||||
assert process.exitcode == 0, f"Process {process.name} exited with code {process.exitcode}"
|
||||
@@ -23,6 +23,7 @@ dion = false
|
||||
fastokens = false
|
||||
flash-attn-3 = false
|
||||
flash-mla = false
|
||||
flashinfer-python = false
|
||||
harbor = "2026-08-11T00:00:00Z"
|
||||
nixl-cu13 = false
|
||||
prime = false
|
||||
@@ -1871,7 +1872,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "flashinfer-python"
|
||||
version = "0.6.18.post1"
|
||||
version = "0.7.0.post1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "apache-tvm-ffi" },
|
||||
@@ -1879,6 +1880,7 @@ dependencies = [
|
||||
{ name = "cuda-python" },
|
||||
{ name = "cuda-tile" },
|
||||
{ name = "einops" },
|
||||
{ name = "nccl-extensions" },
|
||||
{ name = "nccl4py" },
|
||||
{ name = "ninja" },
|
||||
{ name = "numpy" },
|
||||
@@ -1891,9 +1893,9 @@ dependencies = [
|
||||
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" } },
|
||||
{ name = "tqdm" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/ad/7e/a756567c193b2af546f98c08158505e998c2dd4a7f8fc6fe6c72105dce8b/flashinfer_python-0.6.18.post1.tar.gz", hash = "sha256:1ebfb8ff3fa3a896e5abbd0dec123a5f3e3734029871349dad6968b252b82097", size = 13294037, upload-time = "2026-09-05T03:26:09.049Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/14/b0/2f27f2645056b0e671b3bcf8a934e73ed89ca5c5df9ebe651f21c0d218e2/flashinfer_python-0.7.0.post1.tar.gz", hash = "sha256:2e67b38a9af1d4eedff96f7f5d79c6a4d9f0f97cb4a30f71e4ffd717f1ad9af4", size = 26061698, upload-time = "2026-09-29T23:34:14.797Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/64/3f/bd0a74bfbb4f3813bfe61267ff696fb229ab70c0f1f44848287221928c95/flashinfer_python-0.6.18.post1-py3-none-any.whl", hash = "sha256:adb6d2952b47131138e108bd2999b1fe18b71f1a4c0b2684f168753db9563991", size = 18348022, upload-time = "2026-09-05T03:26:06.084Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/00/7d/16237087a2af99086ef4ae9808dff9b24f0a4db4cfd673233836821a32e0/flashinfer_python-0.7.0.post1-py3-none-any.whl", hash = "sha256:c7adf826568d61fc1b7d3aadd4cae387a35a138bfc08e2deca2f34ecfa280716", size = 33659854, upload-time = "2026-09-29T23:34:11.137Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2459,23 +2461,22 @@ requires-dist = [{ name = "verifiers", specifier = ">=0.3.1" }]
|
||||
|
||||
[[package]]
|
||||
name = "humming-kernels"
|
||||
version = "0.1.12"
|
||||
version = "0.1.16"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "cuda-bindings" },
|
||||
{ name = "jinja2" },
|
||||
{ name = "numpy" },
|
||||
{ name = "nvidia-ml-py" },
|
||||
{ name = "safetensors" },
|
||||
{ name = "tabulate" },
|
||||
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" } },
|
||||
{ name = "tqdm" },
|
||||
{ name = "triton" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/93/b9/53797fff4b1b31b4567453a365646d724469b1bb0d76c07f8746617d0cb6/humming_kernels-0.1.12.tar.gz", hash = "sha256:c96c37c95f74379067d2d2d0c5154d12ee9a8cfa29a7c3370a7f3e34f207ca72", size = 259323, upload-time = "2026-07-31T14:28:23.124Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/70/d2/e286acb9f594f998bbc2d99617966a4f01a603c699d829793a86a42c2440/humming_kernels-0.1.16.tar.gz", hash = "sha256:a5356a63c4adf6c16c46f541749dec90fc2d49cf29ebc33ac05e23c744731809", size = 317590, upload-time = "2026-09-22T02:41:16.516Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/58/0f/01f871dc26f8d7e1683df9464890d48cfd5c4e46c4a264d7ee0868749197/humming_kernels-0.1.12-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:988e8b9da41e3679ae2816bdfb51acab53c05cc56254b5ca98e847f4efcf24fd", size = 318019, upload-time = "2026-07-31T14:28:19.925Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ec/a2/f96912ee7d68f56e61c15555657ffa057b8afbaa21241c63342b5969bb74/humming_kernels-0.1.12-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:cd3ef712a93f3a9075ea99de2c72bcd3ec89dab3759b3a248d869f5507b60331", size = 322656, upload-time = "2026-07-31T14:28:21.511Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/71/47/43794faeb47fe2067bef5c7d830fac4244bf872625b0bfddf116fd7a0a0d/humming_kernels-0.1.16-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:fa1a86e31fc3c0fede5bceb3dc2f088e6bdda636a8f405fd71def853f12049e1", size = 417732, upload-time = "2026-09-22T02:41:12.611Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a2/7f/08aad5a947d549aa21af5b93e711aad3d5689d39e8439c7fa72eab9773de/humming_kernels-0.1.16-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:683212692f5e1339961e4322aff1ba116523e2681b2aafeaf7c081bc4e1f5627", size = 426040, upload-time = "2026-09-22T02:41:14.541Z" },
|
||||
]
|
||||
|
||||
[package.optional-dependencies]
|
||||
@@ -3810,6 +3811,22 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/1f/b6/e7cdde7b8e90d5dff25b622f95833ef26567ad184c977278b93a1cbd5717/narwhals-2.22.0-py3-none-any.whl", hash = "sha256:1421797ede01789cc1537619dbc3f36f840737240f748fdb24a60a0225fc80be", size = 453815, upload-time = "2026-06-01T13:34:34.127Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nccl-extensions"
|
||||
version = "0.1.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "cuda-core" },
|
||||
{ name = "cuda-pathfinder" },
|
||||
{ name = "nccl4py" },
|
||||
{ name = "numpy" },
|
||||
{ name = "packaging" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/24/77/a02842f3e7d6aef181733f94d313a1ff4b3db2726e2c067d7946e8f34cc3/nccl_extensions-0.1.0-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d85e203e284b50dad3846d6fb0d35560378537689f23d92a16c67f7d854025d7", size = 22282239, upload-time = "2026-09-02T15:38:26.362Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f3/3c/b043c1f8ca2766d48e30e9cc5a0d65d51aef77e3a8d18dbbaa95fd5386e2/nccl_extensions-0.1.0-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:54d46bee108f0bc18cdc35dbe17bba6452d6a38a270fa5e8ccde03267460fa87", size = 22589285, upload-time = "2026-09-02T15:38:53.213Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nccl4py"
|
||||
version = "0.4.1"
|
||||
@@ -4564,6 +4581,21 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/df/e5/4d2d8af06f788329b4f78f8cc3679bb395392fcaa1e4d8d3c33e85308fa4/orjson-3.11.9-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:71e63adb0e1f1ed5d9e168f50a91ceb93ae6420731d222dc7da5c69409aa47aa", size = 136943, upload-time = "2026-05-06T15:10:14.405Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "oss-harmony"
|
||||
version = "0.0.11"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "pydantic" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/43/88/ca56e5b17df4763bbb552c7be3abe432b51db3c51f6327a3848b88ad7c08/oss_harmony-0.0.11.tar.gz", hash = "sha256:ccad467b71d61490df1f2204b7a064990833338615ac135536c5b3a8e2d03a15", size = 2198780, upload-time = "2026-05-13T20:49:11.767Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/fd/e9/0b33d4c592e1422c9faeaf1cfe10731328ecf3504e900dc7921109affd55/oss_harmony-0.0.11-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f1f74ef7f8be32fa1dcfe1644839af5f0873acce78b5668c2aa39f26d83218ff", size = 3493239, upload-time = "2026-05-13T20:48:49.588Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/89/68/001d7429a692b2db0c03bd49b756f834716b64afc0bbbece96824e8f0af8/oss_harmony-0.0.11-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d877c6b526cdbdf55068bae8f05c60398e929c9e296c7f69a1d533339708be80", size = 3567858, upload-time = "2026-05-13T20:48:57.904Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/4b/c9/720aed1527d87f82e07a7f35c3c81c6d9198a8d1223bdbd298b3c66a72db/oss_harmony-0.0.11-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:036505bfb39c6b50edcf717349518d269bb375207f7f8e95f517e938b8f2e0c8", size = 3695703, upload-time = "2026-05-13T20:49:02.857Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/48/9a/ad24d20ea1e8b3167744f5d357d48a116086258ca58540986a0896781864/oss_harmony-0.0.11-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:0d1545203973abb3002dcc6c5cffd14ca4a376b655c14ce190c78eb6aaf5f6fd", size = 3807882, upload-time = "2026-05-13T20:49:09.767Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "outlines-core"
|
||||
version = "0.2.14"
|
||||
@@ -5016,8 +5048,8 @@ all = [
|
||||
{ name = "torchdata", marker = "sys_platform == 'linux'" },
|
||||
{ name = "torchtitan", marker = "sys_platform == 'linux'" },
|
||||
{ name = "torchvision", marker = "sys_platform == 'linux'" },
|
||||
{ name = "vllm", version = "0.30.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm", version = "0.30.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm", version = "0.31.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.31.0/vllm-0.31.0-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm", version = "0.31.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.31.0/vllm-0.31.0-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm-router", version = "0.2.2", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.2/vllm_router-0.2.2-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm-router", version = "0.2.2", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.2/vllm_router-0.2.2-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
]
|
||||
@@ -5069,8 +5101,8 @@ gpu = [
|
||||
{ name = "torchdata", marker = "sys_platform == 'linux'" },
|
||||
{ name = "torchtitan", marker = "sys_platform == 'linux'" },
|
||||
{ name = "torchvision", marker = "sys_platform == 'linux'" },
|
||||
{ name = "vllm", version = "0.30.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm", version = "0.30.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm", version = "0.31.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.31.0/vllm-0.31.0-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm", version = "0.31.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.31.0/vllm-0.31.0-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
]
|
||||
kernels = [
|
||||
{ name = "prime-kernels", version = "0.1.0+cu130torch2.13.0", source = { url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.0-6f48176/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
|
||||
@@ -5141,7 +5173,7 @@ requires-dist = [
|
||||
{ name = "prime-rl", extras = ["quack"], marker = "extra == 'all'" },
|
||||
{ name = "prime-rl", extras = ["sonic-moe"], marker = "extra == 'all'" },
|
||||
{ name = "prime-rl-configs", editable = "packages/prime-rl-configs" },
|
||||
{ name = "prime-runs", extras = ["train"], specifier = ">=0.1.3" },
|
||||
{ name = "prime-runs", extras = ["train"], specifier = ">=0.1.4" },
|
||||
{ name = "prometheus-client", specifier = ">=0.20.0" },
|
||||
{ name = "psutil", specifier = ">=7.0.0" },
|
||||
{ name = "pybase64", specifier = ">=1.4.2" },
|
||||
@@ -5167,9 +5199,9 @@ requires-dist = [
|
||||
{ name = "uvicorn", marker = "extra == 'dashboard'", specifier = ">=0.30" },
|
||||
{ name = "uvloop", specifier = ">=0.21.0" },
|
||||
{ name = "verifiers", extras = ["harbor"], editable = "deps/verifiers" },
|
||||
{ name = "vllm", marker = "platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'gpu'", url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_aarch64.whl" },
|
||||
{ name = "vllm", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64' and sys_platform == 'linux' and extra == 'gpu'", specifier = ">=0.30.0" },
|
||||
{ name = "vllm", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'gpu'", url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_x86_64.whl" },
|
||||
{ name = "vllm", marker = "platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'gpu'", url = "https://github.com/vllm-project/vllm/releases/download/v0.31.0/vllm-0.31.0-cp38-abi3-manylinux_2_28_aarch64.whl" },
|
||||
{ name = "vllm", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64' and sys_platform == 'linux' and extra == 'gpu'", specifier = ">=0.31.0" },
|
||||
{ name = "vllm", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'gpu'", url = "https://github.com/vllm-project/vllm/releases/download/v0.31.0/vllm-0.31.0-cp38-abi3-manylinux_2_28_x86_64.whl" },
|
||||
{ name = "vllm-router", marker = "platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.2/vllm_router-0.2.2-cp38-abi3-manylinux_2_28_aarch64.whl" },
|
||||
{ name = "vllm-router", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64' and sys_platform == 'linux' and extra == 'disagg'" },
|
||||
{ name = "vllm-router", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.2/vllm_router-0.2.2-cp38-abi3-manylinux_2_28_x86_64.whl" },
|
||||
@@ -5214,15 +5246,15 @@ requires-dist = [
|
||||
|
||||
[[package]]
|
||||
name = "prime-runs"
|
||||
version = "0.1.3"
|
||||
version = "0.1.4"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "httpx" },
|
||||
{ name = "prime-traces" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/3f/ba/3d38aeafc0ef885eef7b99bbe26fe350b4248af8d3fa89d4ca8a249f0f04/prime_runs-0.1.3.tar.gz", hash = "sha256:181ab1c720ed9113abbf3719ba6863c9ee23c55309101c0b7f4021ff9dafbe20", size = 65541, upload-time = "2026-09-17T15:31:42.319Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/6c/de/6fb503ce854315d096982b79340b02eb5a978b139a7c719d39df77e7f211/prime_runs-0.1.4.tar.gz", hash = "sha256:f06c2bc7db28f0ed99ca6b06aa5186245ca94009872eb861ab0be7cff25484bd", size = 67282, upload-time = "2026-10-08T00:23:59.354Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/6e/93/5fff685470a6cb12fc93192432951a081de70e271aef1cebc506fba4ccc5/prime_runs-0.1.3-py3-none-any.whl", hash = "sha256:86c3d5183ed5848854a194233b4a9451deabea56a9063771244c5c54c00d69df", size = 45087, upload-time = "2026-09-17T15:31:40.913Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ba/51/8f300ac057c95afa9df591172b2e8374743afdeeae300771fd78c91a5f75/prime_runs-0.1.4-py3-none-any.whl", hash = "sha256:f33b477c2d53eca08524a3d469810943eee31af8f60ceffc38ef2b9c90596d1b", size = 46253, upload-time = "2026-10-08T00:23:57.736Z" },
|
||||
]
|
||||
|
||||
[package.optional-dependencies]
|
||||
@@ -7813,8 +7845,8 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "vllm"
|
||||
version = "0.30.0"
|
||||
source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_aarch64.whl" }
|
||||
version = "0.31.0"
|
||||
source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.31.0/vllm-0.31.0-cp38-abi3-manylinux_2_28_aarch64.whl" }
|
||||
resolution-markers = [
|
||||
"platform_machine == 'aarch64' and sys_platform == 'linux'",
|
||||
]
|
||||
@@ -7852,12 +7884,12 @@ dependencies = [
|
||||
{ name = "nvidia-cutlass-dsl" },
|
||||
{ name = "nvtx" },
|
||||
{ name = "openai" },
|
||||
{ name = "openai-harmony" },
|
||||
{ name = "opencv-python-headless" },
|
||||
{ name = "opentelemetry-api" },
|
||||
{ name = "opentelemetry-exporter-otlp" },
|
||||
{ name = "opentelemetry-sdk" },
|
||||
{ name = "opentelemetry-semantic-conventions-ai" },
|
||||
{ name = "oss-harmony" },
|
||||
{ name = "outlines-core" },
|
||||
{ name = "partial-json-parser" },
|
||||
{ name = "pillow" },
|
||||
@@ -7896,7 +7928,7 @@ dependencies = [
|
||||
{ name = "xgrammar" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:eb3e11bab695d085098579a6eda2d602419adec3826ebfbcce9a3ffa543eb62e" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.31.0/vllm-0.31.0-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:56edd19c798510b6da5ae4dd38b3bdf55ea7ae261b339a906df006dc3faf751d" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
@@ -7918,10 +7950,10 @@ requires-dist = [
|
||||
{ name = "fastsafetensors", specifier = ">=0.3.3" },
|
||||
{ name = "fastsafetensors", marker = "extra == 'fastsafetensors'", specifier = ">=0.3.3" },
|
||||
{ name = "filelock", specifier = ">=3.16.1" },
|
||||
{ name = "flashinfer-python", specifier = "==0.6.18.post1" },
|
||||
{ name = "flashinfer-python", specifier = "==0.7.0.post1" },
|
||||
{ name = "helion", marker = "extra == 'helion'", specifier = "==1.4.0" },
|
||||
{ name = "huggingface-hub", specifier = ">=1.31.0" },
|
||||
{ name = "humming-kernels", extras = ["cu13"], specifier = "==0.1.12" },
|
||||
{ name = "humming-kernels", extras = ["cu13"], specifier = "==0.1.16" },
|
||||
{ name = "ijson" },
|
||||
{ name = "instanttensor", specifier = ">=0.1.9" },
|
||||
{ name = "instanttensor", marker = "extra == 'instanttensor'", specifier = ">=0.1.9" },
|
||||
@@ -7943,7 +7975,6 @@ requires-dist = [
|
||||
{ name = "nvidia-deepstream-videodecode-cu13", marker = "extra == 'deepstream'", specifier = ">=9.0.2" },
|
||||
{ name = "nvtx", specifier = "==0.2.15" },
|
||||
{ name = "openai", specifier = ">=2.25.0" },
|
||||
{ name = "openai-harmony", specifier = ">=0.0.3" },
|
||||
{ name = "opencv-python-headless", specifier = ">=4.13.0" },
|
||||
{ name = "opentelemetry-api", specifier = ">=1.27.0" },
|
||||
{ name = "opentelemetry-api", marker = "extra == 'otel'", specifier = ">=1.26.0" },
|
||||
@@ -7953,6 +7984,7 @@ requires-dist = [
|
||||
{ name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.26.0" },
|
||||
{ name = "opentelemetry-semantic-conventions-ai", specifier = ">=0.4.1" },
|
||||
{ name = "opentelemetry-semantic-conventions-ai", marker = "extra == 'otel'", specifier = ">=0.4.1" },
|
||||
{ name = "oss-harmony", specifier = ">=0.0.11" },
|
||||
{ name = "outlines-core", specifier = "==0.2.14" },
|
||||
{ name = "pandas", marker = "extra == 'bench'" },
|
||||
{ name = "partial-json-parser" },
|
||||
@@ -7960,7 +7992,8 @@ requires-dist = [
|
||||
{ name = "plotly", marker = "extra == 'bench'" },
|
||||
{ name = "prometheus-client", specifier = ">=0.18.0" },
|
||||
{ name = "prometheus-fastapi-instrumentator", specifier = ">=8.0.0" },
|
||||
{ name = "protobuf", specifier = ">=5.29.6,!=6.30.*,!=6.31.*,!=6.32.*,!=6.33.0.*,!=6.33.1.*,!=6.33.2.*,!=6.33.3.*,!=6.33.4.*" },
|
||||
{ name = "protobuf", marker = "platform_machine != 's390x'", specifier = ">=5.29.6,!=6.30.*,!=6.31.*,!=6.32.*,!=6.33.0.*,!=6.33.1.*,!=6.33.2.*,!=6.33.3.*,!=6.33.4.*" },
|
||||
{ name = "protobuf", marker = "platform_machine == 's390x'", specifier = "==7.36.1" },
|
||||
{ name = "psutil" },
|
||||
{ name = "py-cpuinfo" },
|
||||
{ name = "pybase64" },
|
||||
@@ -7995,19 +8028,19 @@ requires-dist = [
|
||||
{ name = "torchcodec", specifier = ">=0.14" },
|
||||
{ name = "torchvision", specifier = "==0.28.0" },
|
||||
{ name = "tqdm" },
|
||||
{ name = "transformers", specifier = ">=5.10.4" },
|
||||
{ name = "transformers", specifier = ">=5.10.4,<5.18.0" },
|
||||
{ name = "typing-extensions", specifier = ">=4.10" },
|
||||
{ name = "vllm-gguf-plugin", marker = "extra == 'extra-quant'", specifier = ">=0.0.2" },
|
||||
{ name = "watchfiles" },
|
||||
{ name = "xgrammar", marker = "platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'ppc64le' or platform_machine == 's390x' or platform_machine == 'x86_64'", specifier = ">=0.2.1,<1.0.0" },
|
||||
{ name = "zentorch", marker = "extra == 'zen'", specifier = "==2.13.0.0" },
|
||||
{ name = "xgrammar", marker = "platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'ppc64le' or platform_machine == 's390x' or platform_machine == 'x86_64'", specifier = "==0.2.7" },
|
||||
{ name = "zentorch", marker = "extra == 'zen'", specifier = "==2.13.0.1" },
|
||||
]
|
||||
provides-extras = ["zen", "bench", "tensorizer", "fastsafetensors", "instanttensor", "runai", "audio", "video", "deepstream", "flashinfer", "b12x", "helion", "grpc", "otel", "extra-quant"]
|
||||
|
||||
[[package]]
|
||||
name = "vllm"
|
||||
version = "0.30.0"
|
||||
source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_x86_64.whl" }
|
||||
version = "0.31.0"
|
||||
source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.31.0/vllm-0.31.0-cp38-abi3-manylinux_2_28_x86_64.whl" }
|
||||
resolution-markers = [
|
||||
"platform_machine == 'x86_64' and sys_platform == 'linux'",
|
||||
]
|
||||
@@ -8045,12 +8078,12 @@ dependencies = [
|
||||
{ name = "nvidia-cutlass-dsl" },
|
||||
{ name = "nvtx" },
|
||||
{ name = "openai" },
|
||||
{ name = "openai-harmony" },
|
||||
{ name = "opencv-python-headless" },
|
||||
{ name = "opentelemetry-api" },
|
||||
{ name = "opentelemetry-exporter-otlp" },
|
||||
{ name = "opentelemetry-sdk" },
|
||||
{ name = "opentelemetry-semantic-conventions-ai" },
|
||||
{ name = "oss-harmony" },
|
||||
{ name = "outlines-core" },
|
||||
{ name = "partial-json-parser" },
|
||||
{ name = "pillow" },
|
||||
@@ -8089,7 +8122,7 @@ dependencies = [
|
||||
{ name = "xgrammar" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:ef52ee58c410ead0b8afb190838fa4cbcb52075596f67862a03859d984966ac4" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.31.0/vllm-0.31.0-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:39132b433967f0962d03d8a5f633b9bee6b32708f566c7d5637b79f8d0ef3433" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
@@ -8111,10 +8144,10 @@ requires-dist = [
|
||||
{ name = "fastsafetensors", specifier = ">=0.3.3" },
|
||||
{ name = "fastsafetensors", marker = "extra == 'fastsafetensors'", specifier = ">=0.3.3" },
|
||||
{ name = "filelock", specifier = ">=3.16.1" },
|
||||
{ name = "flashinfer-python", specifier = "==0.6.18.post1" },
|
||||
{ name = "flashinfer-python", specifier = "==0.7.0.post1" },
|
||||
{ name = "helion", marker = "extra == 'helion'", specifier = "==1.4.0" },
|
||||
{ name = "huggingface-hub", specifier = ">=1.31.0" },
|
||||
{ name = "humming-kernels", extras = ["cu13"], specifier = "==0.1.12" },
|
||||
{ name = "humming-kernels", extras = ["cu13"], specifier = "==0.1.16" },
|
||||
{ name = "ijson" },
|
||||
{ name = "instanttensor", specifier = ">=0.1.9" },
|
||||
{ name = "instanttensor", marker = "extra == 'instanttensor'", specifier = ">=0.1.9" },
|
||||
@@ -8136,7 +8169,6 @@ requires-dist = [
|
||||
{ name = "nvidia-deepstream-videodecode-cu13", marker = "extra == 'deepstream'", specifier = ">=9.0.2" },
|
||||
{ name = "nvtx", specifier = "==0.2.15" },
|
||||
{ name = "openai", specifier = ">=2.25.0" },
|
||||
{ name = "openai-harmony", specifier = ">=0.0.3" },
|
||||
{ name = "opencv-python-headless", specifier = ">=4.13.0" },
|
||||
{ name = "opentelemetry-api", specifier = ">=1.27.0" },
|
||||
{ name = "opentelemetry-api", marker = "extra == 'otel'", specifier = ">=1.26.0" },
|
||||
@@ -8146,6 +8178,7 @@ requires-dist = [
|
||||
{ name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.26.0" },
|
||||
{ name = "opentelemetry-semantic-conventions-ai", specifier = ">=0.4.1" },
|
||||
{ name = "opentelemetry-semantic-conventions-ai", marker = "extra == 'otel'", specifier = ">=0.4.1" },
|
||||
{ name = "oss-harmony", specifier = ">=0.0.11" },
|
||||
{ name = "outlines-core", specifier = "==0.2.14" },
|
||||
{ name = "pandas", marker = "extra == 'bench'" },
|
||||
{ name = "partial-json-parser" },
|
||||
@@ -8153,7 +8186,8 @@ requires-dist = [
|
||||
{ name = "plotly", marker = "extra == 'bench'" },
|
||||
{ name = "prometheus-client", specifier = ">=0.18.0" },
|
||||
{ name = "prometheus-fastapi-instrumentator", specifier = ">=8.0.0" },
|
||||
{ name = "protobuf", specifier = ">=5.29.6,!=6.30.*,!=6.31.*,!=6.32.*,!=6.33.0.*,!=6.33.1.*,!=6.33.2.*,!=6.33.3.*,!=6.33.4.*" },
|
||||
{ name = "protobuf", marker = "platform_machine != 's390x'", specifier = ">=5.29.6,!=6.30.*,!=6.31.*,!=6.32.*,!=6.33.0.*,!=6.33.1.*,!=6.33.2.*,!=6.33.3.*,!=6.33.4.*" },
|
||||
{ name = "protobuf", marker = "platform_machine == 's390x'", specifier = "==7.36.1" },
|
||||
{ name = "psutil" },
|
||||
{ name = "py-cpuinfo" },
|
||||
{ name = "pybase64" },
|
||||
@@ -8188,12 +8222,12 @@ requires-dist = [
|
||||
{ name = "torchcodec", specifier = ">=0.14" },
|
||||
{ name = "torchvision", specifier = "==0.28.0" },
|
||||
{ name = "tqdm" },
|
||||
{ name = "transformers", specifier = ">=5.10.4" },
|
||||
{ name = "transformers", specifier = ">=5.10.4,<5.18.0" },
|
||||
{ name = "typing-extensions", specifier = ">=4.10" },
|
||||
{ name = "vllm-gguf-plugin", marker = "extra == 'extra-quant'", specifier = ">=0.0.2" },
|
||||
{ name = "watchfiles" },
|
||||
{ name = "xgrammar", marker = "platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'ppc64le' or platform_machine == 's390x' or platform_machine == 'x86_64'", specifier = ">=0.2.1,<1.0.0" },
|
||||
{ name = "zentorch", marker = "extra == 'zen'", specifier = "==2.13.0.0" },
|
||||
{ name = "xgrammar", marker = "platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'ppc64le' or platform_machine == 's390x' or platform_machine == 'x86_64'", specifier = "==0.2.7" },
|
||||
{ name = "zentorch", marker = "extra == 'zen'", specifier = "==2.13.0.1" },
|
||||
]
|
||||
provides-extras = ["zen", "bench", "tensorizer", "fastsafetensors", "instanttensor", "runai", "audio", "video", "deepstream", "flashinfer", "b12x", "helion", "grpc", "otel", "extra-quant"]
|
||||
|
||||
@@ -8495,7 +8529,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "xgrammar"
|
||||
version = "0.2.1"
|
||||
version = "0.2.7"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "apache-tvm-ffi" },
|
||||
@@ -8506,10 +8540,10 @@ dependencies = [
|
||||
{ name = "triton", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/d8/ea/6394caddd078d33772070eefaaf77cb0a826a3047b908b688dece7d040b5/xgrammar-0.2.1.tar.gz", hash = "sha256:4c48c251b75d211e9ffa7f4f4ac8b5b0164f89fd5f0d1883ad7ff4554922030d", size = 2427065, upload-time = "2026-05-17T21:39:26.576Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/81/e8/21a1661542d541c3c11e56062a213f6405824845a7fc8d3874447d5c6775/xgrammar-0.2.7.tar.gz", hash = "sha256:7674afeee5e6eff9672627b62d5ab0aa2347ea51674f4d78a5c160029f92bc3e", size = 2663916, upload-time = "2026-09-15T15:51:07.444Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/44/60/7c6194b66e043f36a7fbdbf7e6e0e4c94b151f7e53ad1b197f53e711f5d1/xgrammar-0.2.1-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9e8dd9853958a263b4015ce79133a0ff4eaa9d22ef781fb2350c7dfc40c2c012", size = 44218929, upload-time = "2026-05-17T21:37:56.155Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/96/4b/327b3cf702b685a2be28d15490faa4beeac00c4fbcf9bb2d7db0fda32931/xgrammar-0.2.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cbc6014dc1c92fc317b14519121c8163fe35fd934179e5a45d83f780ff231826", size = 44678489, upload-time = "2026-05-17T21:38:00.791Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ad/35/5d56e9dbe6f0ccefebcb5212b7ded0af17bec7f2d148dd6403c7d247d063/xgrammar-0.2.7-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2df1a2292f6b1c5cdc4b176ef2f22c58a837ac99fd854d93856160f31f14a4b0", size = 1113117, upload-time = "2026-09-15T15:50:26.492Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/9d/f2/cb90cfbcca316b3fa98b0928ec989f3fb75f6439bc5269c5c2121d361301/xgrammar-0.2.7-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e4397798f73512ab5abccbadf0a7b6aaf0753ccc4f3171c43b14c4d22df1ed28", size = 1265122, upload-time = "2026-09-15T15:50:28.098Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
Reference in New Issue
Block a user