Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
448f8c09ad | ||
|
|
4076a0e457 | ||
|
|
ad8d775fc3 | ||
|
|
c2027a79d0 | ||
|
|
944163ac68 | ||
|
|
1e7561668d | ||
|
|
fd78f21f79 | ||
|
|
7eade4f7e1 | ||
|
|
bf0f903b86 | ||
|
|
8ffa00c648 | ||
|
|
bc740de6dc | ||
|
|
c8fdcbb39c | ||
|
|
f87be6ba76 | ||
|
|
192035e52c |
@@ -59,5 +59,8 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
|
||||
- **`dump_config`**: Added `--dump-config <path>` flag to the `rl` command. When set, writes the resolved subconfigs (trainer, orchestrator, inference, teacher_inference) to the given directory and exits without starting any processes (2026-02-12)
|
||||
- **`client.api_key_var`**: Changed default from "OPENAI_API_KEY" to "VLLM_API_KEY" (2026-02-12)
|
||||
- **`orchestrator.filters`**: Added orchestrator-side rollout filters for detecting degenerate generations. Supports `[[filters]] type = "gibberish"` (rare tokens at high entropy) and `[[filters]] type = "repetition"` (high-confidence token streaks). Detected rollouts get reward zeroed and completion mask cleared (2026-02-13)
|
||||
- **`inference.model.tool_call_parser`**: Changed default from `"hermes"` to auto-detection from model name. Uses `MODEL_TOOL_CALL_PARSER` dict to infer the correct vLLM tool call parser (e.g. Qwen3→`hermes`, GLM-4.5→`glm45`, GLM-4.7→`glm47`, MiniMax-M2→`minimax_m2`, INTELLECT-3→`hermes`). Unknown models default to `None`. Explicit values still take priority. (#1795, 2026-02-16)
|
||||
- **`orchestrator.eval.cancel_inflight_rollouts_on_eval`**: Added flag to optionally cancel in-flight training rollouts before starting online evals. When enabled, avoids congestion by preventing training and eval rollouts from running simultaneously, but slows training as the rollout pipeline must refill after each eval (default: False) (2026-02-16)
|
||||
- **`orchestrator.use_token_client`**: Added flag to use the token-in-token-out (TITO) client for training across all environments. When enabled, uses `openai_chat_completions_token` client type instead of `openai_chat_completions`. Only use when environments have linear history and the chat template has the extension property (default: False) (2026-02-21)
|
||||
- **`inference.enable_expert_parallel`**, **`inference.all2all_backend`**, and **`inference.enable_eplb`**: Added expert-parallel inference controls passed to vLLM as `--enable-expert-parallel`, `--all2all-backend`, and `--enable-eplb` (defaults: `False`, `"allgather_reducescatter"`, `False`) (2026-02-23)
|
||||
|
||||
|
||||
+18
-4
@@ -1,6 +1,8 @@
|
||||
# SLURM
|
||||
|
||||
For SLURM clusters, use the `rl_slurm` entrypoint. It resolves the full config (trainer, orchestrator, inference), dumps sub-configs as TOML files, renders a SLURM batch script from a Jinja2 template, and submits it with `sbatch`.
|
||||
## RL
|
||||
|
||||
For RL on SLURM clusters, use the `rl_slurm` entrypoint. It resolves the full config (trainer, orchestrator, inference), dumps sub-configs as TOML files, renders a SLURM batch script from a Jinja2 template, and submits it with `sbatch`.
|
||||
|
||||
```bash
|
||||
uv run rl_slurm @ examples/slurm/hendrycks_math.toml
|
||||
@@ -118,9 +120,9 @@ tp = 4
|
||||
dp = 2
|
||||
```
|
||||
|
||||
## Custom SLURM Templates
|
||||
### Custom SLURM Templates
|
||||
|
||||
The default template handles a standard multi-node setup with NCCL weight broadcast, InfiniBand detection, and `srun`-based process dispatch. For more advanced use cases (custom partitions, account settings, module loads, different networking setups, etc.), provide your own Jinja2 template:
|
||||
The default RL template handles a standard multi-node setup with NCCL weight broadcast, InfiniBand detection, and `srun`-based process dispatch. For more advanced use cases (custom partitions, account settings, module loads, different networking setups, etc.), provide your own Jinja2 template:
|
||||
|
||||
```bash
|
||||
uv run rl_slurm \
|
||||
@@ -130,7 +132,7 @@ uv run rl_slurm \
|
||||
|
||||
The template receives the following variables: `job_name`, `project_dir`, `output_dir`, `config_dir`, `num_train_nodes`, `num_infer_nodes`, `gpus_per_node`, `hf_hub_offline`. See `src/prime_rl/slurm/rl_slurm.sh.j2` for the default template as a starting point.
|
||||
|
||||
## Monitoring
|
||||
### Monitoring
|
||||
|
||||
After submission, the logs are available at:
|
||||
|
||||
@@ -152,3 +154,15 @@ This creates a tmux session `slurm-my-rl-job` with two windows:
|
||||
- **Window 1 (Logs)**: three vertical panes tailing trainer, orchestrator, and inference logs
|
||||
|
||||
The trainer and inference panes use glob patterns (`latest_train_node_rank_*.log`, `latest_infer_node_rank_*.log`) to follow logs from all node ranks. Re-running the same command attaches to the existing session.
|
||||
|
||||
---
|
||||
|
||||
## SFT
|
||||
|
||||
For SFT on SLURM, use the `sft_slurm` entrypoint. It works the same way as `rl_slurm` but only needs a trainer config — no inference or orchestrator nodes.
|
||||
|
||||
```bash
|
||||
uv run sft_slurm @ examples/slurm/sft_moe.toml
|
||||
```
|
||||
|
||||
See [`examples/slurm/sft_moe.toml`](../examples/slurm/sft_moe.toml) for a MoE example with activation checkpointing, CPU offload, and compilation. Use `--dry-run` to generate the script without submitting.
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
job_name = "sft-moe-math"
|
||||
output_dir = "/shared/outputs/sft-moe-math"
|
||||
num_nodes = 1
|
||||
gpus_per_node = 8
|
||||
|
||||
max_steps = 500
|
||||
|
||||
[wandb]
|
||||
project = "sft-moe-intellect"
|
||||
name = "sft-moe-math"
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-30B-A3B-Thinking-2507"
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
optim_cpu_offload = true
|
||||
|
||||
[model.compile]
|
||||
|
||||
[model.ac_offloading]
|
||||
max_inflight_activations = 5
|
||||
|
||||
[model.ac]
|
||||
freq = 1
|
||||
|
||||
[data]
|
||||
type = "sft"
|
||||
name = "PrimeIntellect/INTELLECT-3-SFT-10K"
|
||||
subsets = ["default"]
|
||||
splits = ["math"]
|
||||
batch_size = 128
|
||||
seq_len = 8192
|
||||
+3
-1
@@ -34,6 +34,7 @@ dependencies = [
|
||||
"verifiers",
|
||||
"dion",
|
||||
"reverse-text",
|
||||
"tilelang>=0.1.8",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
@@ -44,6 +45,7 @@ orchestrator = "prime_rl.orchestrator.orchestrator:main"
|
||||
inference = "prime_rl.inference.server:main"
|
||||
env-server = "prime_rl.orchestrator.env_server.env_server:main"
|
||||
sft = "prime_rl.trainer.sft.train:main"
|
||||
sft_slurm = "prime_rl.slurm.sft:main"
|
||||
|
||||
[project.entry-points."vllm.general_plugins"]
|
||||
prime_rl = "prime_rl.inference.patches:transformers_v5_compat"
|
||||
@@ -83,7 +85,7 @@ override-dependencies = [
|
||||
[tool.uv.sources]
|
||||
torch = { index = "pytorch-cu128" }
|
||||
math-env = { index = "primeintellect" }
|
||||
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "013d4da" }
|
||||
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "3f555af" }
|
||||
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
|
||||
transformers = { git = "https://github.com/huggingface/transformers.git", rev = "609e3d5" }
|
||||
|
||||
+3
-2
@@ -87,6 +87,7 @@ ARCH_PRESETS = {
|
||||
"prime_model_class": PrimeRLMiniMaxM2ForCausalLM,
|
||||
"tokenizer_source": "MiniMaxAI/MiniMax-M2.1",
|
||||
},
|
||||
# glm_moe_dsa: HF implementation is incorrect, not supported here
|
||||
}
|
||||
|
||||
|
||||
@@ -159,7 +160,7 @@ def verify(arch: str, model_dir: Path) -> None:
|
||||
input_ids = torch.randint(0, config.vocab_size, (1, 64))
|
||||
position_ids = torch.arange(1, 65).unsqueeze(0)
|
||||
|
||||
hf_output = hf_model(input_ids, position_ids)
|
||||
hf_output = hf_model(input_ids=input_ids, position_ids=position_ids)
|
||||
prime_output = prime_model(input_ids, position_ids)
|
||||
|
||||
logits_diff = prime_output["logits"] - hf_output.logits
|
||||
@@ -173,7 +174,7 @@ def verify(arch: str, model_dir: Path) -> None:
|
||||
hf_roundtrip = _create_hf_model_from_config(preset, config)
|
||||
hf_roundtrip.load_state_dict(roundtrip_state_dict)
|
||||
|
||||
hf_roundtrip_output = hf_roundtrip(input_ids, position_ids)
|
||||
hf_roundtrip_output = hf_roundtrip(input_ids=input_ids, position_ids=position_ids)
|
||||
roundtrip_diff = hf_roundtrip_output.logits - hf_output.logits
|
||||
max_roundtrip_diff = roundtrip_diff.abs().max().item()
|
||||
print(f" HF -> PrimeRL -> HF roundtrip max logits diff: {max_roundtrip_diff:.6f}")
|
||||
|
||||
@@ -6,6 +6,84 @@ from pydantic import Field, model_validator
|
||||
from prime_rl.utils.pydantic_config import BaseConfig, BaseSettings, get_all_fields
|
||||
from prime_rl.utils.utils import rgetattr, rsetattr
|
||||
|
||||
MODEL_TOOL_CALL_PARSER: dict[str, str] = {
|
||||
# GLM-4.5
|
||||
"zai-org/GLM-4.5": "glm45",
|
||||
"zai-org/GLM-4.5-FP8": "glm45",
|
||||
"zai-org/GLM-4.5-Base": "glm45",
|
||||
"zai-org/GLM-4.5-Air": "glm45",
|
||||
"zai-org/GLM-4.5-Air-FP8": "glm45",
|
||||
"zai-org/GLM-4.5-Air-Base": "glm45",
|
||||
"zai-org/GLM-4.5V": "glm45",
|
||||
"zai-org/GLM-4.5V-FP8": "glm45",
|
||||
# GLM-4.7
|
||||
"zai-org/GLM-4.7": "glm47",
|
||||
"zai-org/GLM-4.7-FP8": "glm47",
|
||||
"zai-org/GLM-4.7-Flash": "glm47",
|
||||
# MiniMax M2
|
||||
"MiniMaxAI/MiniMax-M2": "minimax_m2",
|
||||
"MiniMaxAI/MiniMax-M2.1": "minimax_m2",
|
||||
"MiniMaxAI/MiniMax-M2.5": "minimax_m2",
|
||||
# INTELLECT-3
|
||||
"PrimeIntellect/INTELLECT-3": "hermes",
|
||||
"PrimeIntellect/INTELLECT-3-FP8": "hermes",
|
||||
"PrimeIntellect/INTELLECT-3.1": "hermes",
|
||||
# Qwen3 dense
|
||||
"Qwen/Qwen3-0.6B": "hermes",
|
||||
"Qwen/Qwen3-0.6B-Base": "hermes",
|
||||
"Qwen/Qwen3-0.6B-FP8": "hermes",
|
||||
"Qwen/Qwen3-1.7B": "hermes",
|
||||
"Qwen/Qwen3-1.7B-Base": "hermes",
|
||||
"Qwen/Qwen3-1.7B-FP8": "hermes",
|
||||
"Qwen/Qwen3-4B": "hermes",
|
||||
"Qwen/Qwen3-4B-Base": "hermes",
|
||||
"Qwen/Qwen3-4B-FP8": "hermes",
|
||||
"Qwen/Qwen3-8B": "hermes",
|
||||
"Qwen/Qwen3-8B-Base": "hermes",
|
||||
"Qwen/Qwen3-8B-FP8": "hermes",
|
||||
"Qwen/Qwen3-14B": "hermes",
|
||||
"Qwen/Qwen3-14B-Base": "hermes",
|
||||
"Qwen/Qwen3-14B-FP8": "hermes",
|
||||
"Qwen/Qwen3-32B": "hermes",
|
||||
"Qwen/Qwen3-32B-FP8": "hermes",
|
||||
# Qwen3 MoE
|
||||
"Qwen/Qwen3-30B-A3B": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Base": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-FP8": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-FP8": "hermes",
|
||||
# Qwen3 2507
|
||||
"Qwen/Qwen3-4B-Instruct-2507": "hermes",
|
||||
"Qwen/Qwen3-4B-Thinking-2507": "hermes",
|
||||
"Qwen/Qwen3-4B-Instruct-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-4B-Thinking-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Instruct-2507": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Thinking-2507": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Instruct-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Thinking-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Instruct-2507": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Thinking-2507": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Instruct-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Thinking-2507-FP8": "hermes",
|
||||
# Qwen3-Next
|
||||
"Qwen/Qwen3-Next-80B-A3B-Instruct": "hermes",
|
||||
"Qwen/Qwen3-Next-80B-A3B-Thinking": "hermes",
|
||||
"Qwen/Qwen3-Next-80B-A3B-Instruct-FP8": "hermes",
|
||||
"Qwen/Qwen3-Next-80B-A3B-Thinking-FP8": "hermes",
|
||||
# Qwen3-Coder
|
||||
"Qwen/Qwen3-Coder-480B-A35B-Instruct": "hermes",
|
||||
"Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8": "hermes",
|
||||
"Qwen/Qwen3-Coder-30B-A3B-Instruct": "hermes",
|
||||
"Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8": "hermes",
|
||||
# Qwen3-Coder-Next
|
||||
"Qwen/Qwen3-Coder-Next": "hermes",
|
||||
"Qwen/Qwen3-Coder-Next-Base": "hermes",
|
||||
"Qwen/Qwen3-Coder-Next-FP8": "hermes",
|
||||
# Qwen3.5
|
||||
"Qwen/Qwen3.5-397B-A17B": "hermes",
|
||||
"Qwen/Qwen3.5-397B-A17B-FP8": "hermes",
|
||||
}
|
||||
|
||||
# TODO: Set thinking/ solution budget
|
||||
|
||||
|
||||
@@ -79,16 +157,18 @@ class ModelConfig(BaseConfig):
|
||||
enable_auto_tool_choice: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to enable auto tool choice. Passed to vLLM as `--enable-auto-tool-choice`",
|
||||
description="Whether to enable auto tool choice. Passed to vLLM as `--enable-auto-tool-choice`. "
|
||||
"Automatically set to True when tool_call_parser is configured.",
|
||||
),
|
||||
] = False
|
||||
|
||||
tool_call_parser: Annotated[
|
||||
str,
|
||||
str | None,
|
||||
Field(
|
||||
description="The tool call parser to use. Passed to vLLM as `--tool-call-parser`",
|
||||
description="The tool call parser to use. Passed to vLLM as `--tool-call-parser`. "
|
||||
"If not set, automatically inferred from the model name.",
|
||||
),
|
||||
] = "hermes"
|
||||
] = None
|
||||
|
||||
reasoning_parser: Annotated[
|
||||
str | None,
|
||||
@@ -104,6 +184,18 @@ class ModelConfig(BaseConfig):
|
||||
),
|
||||
] = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_tool_call_parser(self):
|
||||
if self.tool_call_parser is None:
|
||||
parser = MODEL_TOOL_CALL_PARSER.get(self.name)
|
||||
if parser is not None:
|
||||
self.tool_call_parser = parser
|
||||
|
||||
if self.tool_call_parser is not None:
|
||||
self.enable_auto_tool_choice = True
|
||||
|
||||
return self
|
||||
|
||||
|
||||
class WeightBroadcastConfig(BaseSettings):
|
||||
"""Configures weight broadcast settings."""
|
||||
@@ -117,6 +209,16 @@ class WeightBroadcastConfig(BaseSettings):
|
||||
# TODO: on newer vLLM, can import via `get_args(vllm.config.lora.MaxLoRARanks)`
|
||||
VALID_VLLM_LORA_RANKS = (8, 16, 32, 64, 128, 256, 320, 512)
|
||||
|
||||
# vLLM all2all backend options for expert-parallel deployments.
|
||||
All2AllBackend = Literal[
|
||||
"allgather_reducescatter",
|
||||
"deepep_high_throughput",
|
||||
"deepep_low_latency",
|
||||
"flashinfer_all2allv",
|
||||
"naive",
|
||||
"pplx",
|
||||
]
|
||||
|
||||
|
||||
class InferenceConfig(BaseSettings):
|
||||
"""Configures inference."""
|
||||
@@ -125,7 +227,7 @@ class InferenceConfig(BaseSettings):
|
||||
server: ServerConfig = ServerConfig()
|
||||
|
||||
# The model configuration
|
||||
model: ModelConfig = ModelConfig()
|
||||
model: ModelConfig = Field(default_factory=ModelConfig)
|
||||
|
||||
# The parallel configuration
|
||||
parallel: ParallelConfig = ParallelConfig()
|
||||
@@ -190,6 +292,27 @@ class InferenceConfig(BaseSettings):
|
||||
),
|
||||
] = 0
|
||||
|
||||
enable_expert_parallel: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Enable expert parallelism for MoE models. Passed to vLLM as `--enable-expert-parallel`.",
|
||||
),
|
||||
] = False
|
||||
|
||||
all2all_backend: Annotated[
|
||||
All2AllBackend,
|
||||
Field(
|
||||
description="All-to-all backend for expert parallel communication. Passed to vLLM as `--all2all-backend`.",
|
||||
),
|
||||
] = "allgather_reducescatter"
|
||||
|
||||
enable_eplb: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Enable expert parallel load balancer (EPLB). Passed to vLLM as `--enable-eplb`.",
|
||||
),
|
||||
] = False
|
||||
|
||||
weight_broadcast: Annotated[WeightBroadcastConfig, Field(description="The weight broadcast config.")] = (
|
||||
WeightBroadcastConfig()
|
||||
)
|
||||
@@ -250,6 +373,9 @@ class InferenceConfig(BaseSettings):
|
||||
"max_lora_rank": "max_lora_rank",
|
||||
"gpu_memory_utilization": "gpu_memory_utilization",
|
||||
"api_server_count": "api_server_count",
|
||||
"enable_expert_parallel": "enable_expert_parallel",
|
||||
"all2all_backend": "all2all_backend",
|
||||
"enable_eplb": "enable_eplb",
|
||||
}
|
||||
|
||||
for key in get_all_fields(self):
|
||||
|
||||
@@ -205,6 +205,73 @@ def monkey_patch_tokenize_params_validation():
|
||||
TokenizeParams._text_len_check = _patched_text_len_check
|
||||
|
||||
|
||||
def monkey_patch_hermes_tool_parser_thread_safety():
|
||||
"""Patch Hermes2ProToolParser to cache tokenizer encode/decode results.
|
||||
|
||||
The original __init__ calls tokenizer.encode() and tokenizer.decode() on
|
||||
every instantiation. Under concurrent load, the shared HuggingFace tokenizer's
|
||||
Rust backend panics with ``RuntimeError: Already borrowed`` because multiple
|
||||
threads mutably borrow the same internal state simultaneously.
|
||||
|
||||
Fix: run the first __init__ (which calls encode/decode) under a lock, cache
|
||||
the results, and reuse them for all subsequent instantiations without ever
|
||||
touching the tokenizer again.
|
||||
"""
|
||||
import threading
|
||||
|
||||
import regex as re
|
||||
from vllm.tool_parsers.abstract_tool_parser import ToolParser
|
||||
from vllm.tool_parsers.hermes_tool_parser import Hermes2ProToolParser
|
||||
|
||||
_original_init = Hermes2ProToolParser.__init__
|
||||
_cache: dict[int, dict] = {}
|
||||
_lock = threading.Lock()
|
||||
|
||||
def _patched_init(self, tokenizer):
|
||||
from vllm.tokenizers.mistral import MistralTokenizer
|
||||
|
||||
# Resolve the actual tokenizer that __init__ will use for encode/decode
|
||||
actual_tokenizer = tokenizer.tokenizer if isinstance(tokenizer, MistralTokenizer) else tokenizer
|
||||
key = id(actual_tokenizer)
|
||||
|
||||
if key in _cache:
|
||||
# Fast path: skip encode/decode entirely, set up instance from cache
|
||||
ToolParser.__init__(self, tokenizer)
|
||||
if isinstance(tokenizer, MistralTokenizer):
|
||||
self.model_tokenizer = tokenizer.tokenizer
|
||||
self.current_tool_name_sent = False
|
||||
self.prev_tool_call_arr = []
|
||||
self.current_tool_id = -1
|
||||
self.streamed_args_for_tool = []
|
||||
self.tool_call_start_token = "<tool_call>"
|
||||
self.tool_call_end_token = "</tool_call>"
|
||||
self.tool_call_regex = re.compile(r"<tool_call>(.*?)</tool_call>|<tool_call>(.*)", re.DOTALL)
|
||||
self.scratch_pad_regex = re.compile(r"<scratch_pad>(.*?)</scratch_pad>", re.DOTALL)
|
||||
cached = _cache[key]
|
||||
self.tool_call_start_token_ids = cached["start_ids"]
|
||||
self.tool_call_end_token_ids = cached["end_ids"]
|
||||
self.tool_call_start_token_array = cached["start_array"]
|
||||
self.tool_call_end_token_array = cached["end_array"]
|
||||
self.buffered_delta_text = ""
|
||||
return
|
||||
|
||||
# Slow path: first instantiation for this tokenizer, run under lock
|
||||
with _lock:
|
||||
if key in _cache:
|
||||
# Another thread populated it while we waited
|
||||
_patched_init(self, tokenizer)
|
||||
return
|
||||
_original_init(self, tokenizer)
|
||||
_cache[key] = {
|
||||
"start_ids": self.tool_call_start_token_ids,
|
||||
"end_ids": self.tool_call_end_token_ids,
|
||||
"start_array": self.tool_call_start_token_array,
|
||||
"end_array": self.tool_call_end_token_array,
|
||||
}
|
||||
|
||||
Hermes2ProToolParser.__init__ = _patched_init
|
||||
|
||||
|
||||
def monkey_patch_minimax_m2_for_lora():
|
||||
"""Patch vLLM's MiniMaxM2 model for LoRA compatibility.
|
||||
|
||||
|
||||
@@ -22,7 +22,11 @@ from vllm.logger import init_logger
|
||||
from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
|
||||
from prime_rl.inference.config import InferenceConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
logger = get_logger()
|
||||
from prime_rl.inference.patches import (
|
||||
monkey_patch_hermes_tool_parser_thread_safety,
|
||||
monkey_patch_load_lora_adapter,
|
||||
monkey_patch_prometheus_stat_logger_for_lora_in_dp_mode,
|
||||
monkey_patch_tokenize_params_validation,
|
||||
@@ -38,6 +42,8 @@ monkey_patch_prometheus_stat_logger_for_lora_in_dp_mode()
|
||||
monkey_patch_load_lora_adapter()
|
||||
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
|
||||
monkey_patch_tokenize_params_validation()
|
||||
# NOTE: Monkeypatch Hermes tool parser to fix "Already borrowed" RuntimeError under concurrent load
|
||||
monkey_patch_hermes_tool_parser_thread_safety()
|
||||
|
||||
logger = init_logger("vllm.entrypoints.openai.api_server")
|
||||
|
||||
@@ -227,6 +233,9 @@ def server(config: InferenceConfig, vllm_args: list[str]):
|
||||
from vllm.entrypoints.cli.serve import run_headless, run_multi_api_server
|
||||
from vllm.entrypoints.openai.api_server import run_server
|
||||
|
||||
if config.model.tool_call_parser is not None:
|
||||
logger.info(f"Using tool_call_parser='{config.model.tool_call_parser}' for model '{config.model.name}'")
|
||||
|
||||
parser = FlexibleArgumentParser(description="vLLM OpenAI-Compatible RESTful API server.")
|
||||
parser = make_arg_parser(parser)
|
||||
args = parser.parse_args(args=vllm_args, namespace=config.to_vllm())
|
||||
|
||||
@@ -825,6 +825,13 @@ class OrchestratorConfig(BaseSettings):
|
||||
HeartbeatConfig | None, Field(description="The heartbeat config for monitoring training progress.")
|
||||
] = None
|
||||
|
||||
use_token_client: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to use the token-in-token-out (TITO) client for training across all environments. WARNING: Only use this if your environment has a linear history and the chat template has the extension property (i.e. no tokens are ever removed or inserted by the chat template)"
|
||||
),
|
||||
] = True
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_unique_filter_types(self):
|
||||
types = [f.type for f in self.filters]
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
import multiprocessing as mp
|
||||
import random
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
@@ -102,7 +103,13 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
install_env(env_id)
|
||||
|
||||
# Setup inference pool (handles both static and elastic modes)
|
||||
inference_pool = await setup_inference_pool(config.client, model_name=config.model.name)
|
||||
client_type = "openai_chat_completions_token" if config.use_token_client else "openai_chat_completions"
|
||||
if config.use_token_client:
|
||||
logger.warning(
|
||||
"Token-in-token-out (TITO) client is enabled. Only use this if your environment has a linear "
|
||||
"history and the chat template has the extension property."
|
||||
)
|
||||
inference_pool = await setup_inference_pool(config.client, model_name=config.model.name, client_type=client_type)
|
||||
|
||||
# Setup teacher inference pool if configured
|
||||
if config.teacher_model:
|
||||
@@ -164,9 +171,10 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
)
|
||||
|
||||
train_env_addresses = []
|
||||
env_processes: list[mp.Process] = []
|
||||
for env_id, env, env_name in zip(env_ids, config.env, train_env_names):
|
||||
if env.address is None:
|
||||
address = spawn_env_server(
|
||||
address, process = spawn_env_server(
|
||||
env_id=env_id,
|
||||
env_args=env.args,
|
||||
extra_env_kwargs=env.extra_env_kwargs,
|
||||
@@ -175,6 +183,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
log_file_level=config.log.vf_level,
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
env_processes.append(process)
|
||||
else:
|
||||
address = env.address
|
||||
logger.info(f"Connecting train environment {env_name} to server at {address}")
|
||||
@@ -201,7 +210,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
|
||||
for env_id, env, eval_env_name in zip(env_ids, config.eval.env, eval_env_names):
|
||||
if env.address is None:
|
||||
address = spawn_env_server(
|
||||
address, process = spawn_env_server(
|
||||
env_id=env_id,
|
||||
env_args=env.args,
|
||||
extra_env_kwargs=env.extra_env_kwargs,
|
||||
@@ -210,6 +219,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
log_file_level=config.log.vf_level,
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
env_processes.append(process)
|
||||
else:
|
||||
address = env.address
|
||||
logger.info(f"Connecting eval environment {eval_env_name} to server at {address}")
|
||||
@@ -487,12 +497,14 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
train_examples: list[TrainingSample] = []
|
||||
rollout_prefill_lens: list[int] = []
|
||||
rollout_decode_lens: list[int] = []
|
||||
rollout_samples_per_rollout: list[int] = []
|
||||
num_prefill_tokens = 0
|
||||
num_decode_tokens = 0
|
||||
for rollout, advantage, samples in zip(train_rollouts, advantages, results):
|
||||
rollout_prefill_tokens = 0
|
||||
rollout_decode_tokens = 0
|
||||
if samples is not None:
|
||||
rollout_samples_per_rollout.append(len(samples))
|
||||
for sample in samples:
|
||||
sample.advantage = advantage
|
||||
sample.reward = rollout["reward"]
|
||||
@@ -501,6 +513,8 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
rollout_decode_tokens += sample_decode_tokens
|
||||
rollout_prefill_tokens += sample_prefill_tokens
|
||||
train_examples.append(sample)
|
||||
else:
|
||||
rollout_samples_per_rollout.append(0)
|
||||
rollout_prefill_lens.append(rollout_prefill_tokens)
|
||||
rollout_decode_lens.append(rollout_decode_tokens)
|
||||
num_prefill_tokens += rollout_prefill_tokens
|
||||
@@ -568,6 +582,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
"seq_len": [get_seq_len(rollout) for rollout in train_rollouts],
|
||||
"prefill_len": rollout_prefill_lens,
|
||||
"decode_len": rollout_decode_lens,
|
||||
"samples_per_rollout": rollout_samples_per_rollout,
|
||||
"num_turns": [len(rollout["trajectory"]) for rollout in train_rollouts],
|
||||
"generation_ms": [rollout["timing"]["generation_ms"] for rollout in train_rollouts],
|
||||
"scoring_ms": [rollout["timing"]["scoring_ms"] for rollout in train_rollouts],
|
||||
@@ -630,6 +645,10 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
"is_truncated/mean": results_df.groupby("example_id").is_truncated.mean().mean(),
|
||||
"is_truncated/max": results_df.groupby("example_id").is_truncated.mean().max(),
|
||||
"is_truncated/min": results_df.groupby("example_id").is_truncated.mean().min(),
|
||||
# Seqs per rollout metrics
|
||||
"samples_per_rollout/mean": results_df.groupby("example_id").samples_per_rollout.mean().mean(),
|
||||
"samples_per_rollout/max": results_df.groupby("example_id").samples_per_rollout.mean().max(),
|
||||
"samples_per_rollout/min": results_df.groupby("example_id").samples_per_rollout.mean().min(),
|
||||
# Turn metrics
|
||||
"num_turns/mean": results_df.groupby("example_id").num_turns.mean().mean(),
|
||||
"num_turns/max": results_df.groupby("example_id").num_turns.mean().max(),
|
||||
@@ -775,6 +794,14 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
# Cancel event loop lag monitor task
|
||||
event_loop_lag_monitor_task.cancel()
|
||||
|
||||
# Shutdown env processes
|
||||
for process in env_processes:
|
||||
process.terminate()
|
||||
process.join(timeout=5)
|
||||
if process.is_alive():
|
||||
process.kill()
|
||||
process.join(timeout=5)
|
||||
|
||||
logger.success("Orchestrator finished.")
|
||||
|
||||
# Optionally, print benchmark table
|
||||
|
||||
@@ -27,8 +27,7 @@ def spawn_env_server(
|
||||
log_file: str | None = None,
|
||||
log_file_level: str | None = None,
|
||||
json_logging: bool = False,
|
||||
daemon: bool = True,
|
||||
) -> str:
|
||||
) -> tuple[str, mp.Process]:
|
||||
"""
|
||||
Starts a ZMQEnvServer process in a subprocess.
|
||||
|
||||
@@ -38,7 +37,7 @@ def spawn_env_server(
|
||||
# Use spawn to avoid inheriting file descriptors (e.g. sockets) from
|
||||
# the parent process, which has caused hangs when multiple env server
|
||||
# subprocesses share the same fds.
|
||||
mp.get_context("spawn").Process(
|
||||
process = mp.get_context("spawn").Process(
|
||||
target=ZMQEnvServer.run_server,
|
||||
args=(
|
||||
env_id,
|
||||
@@ -49,10 +48,11 @@ def spawn_env_server(
|
||||
log_file_level,
|
||||
),
|
||||
kwargs=dict(address=address, json_logging=json_logging),
|
||||
daemon=daemon,
|
||||
).start()
|
||||
daemon=False, # cannot run daemon because env server uses subprocesses
|
||||
)
|
||||
process.start()
|
||||
|
||||
return address
|
||||
return address, process
|
||||
|
||||
|
||||
def setup_env_client(
|
||||
|
||||
@@ -261,6 +261,9 @@ class BaseRLConfig(BaseSettings):
|
||||
self.orchestrator.model.name = self.model.name
|
||||
if self.inference is not None:
|
||||
self.inference.model.name = self.model.name
|
||||
self.inference.model.tool_call_parser = None
|
||||
self.inference.model.enable_auto_tool_choice = False
|
||||
self.inference.model.resolve_tool_call_parser()
|
||||
|
||||
validate_shared_model_name(self.trainer, self.orchestrator, self.inference)
|
||||
|
||||
|
||||
@@ -91,9 +91,6 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
|
||||
uv run inference \
|
||||
@ $CONFIG_DIR/inference.toml \
|
||||
--enable-auto-tool-choice \
|
||||
--enable-log-requests \
|
||||
--no-disable-log-requests \
|
||||
2>&1 | tee $OUTPUT_DIR/slurm/latest_infer_node_rank_${INFER_NODE_RANK}.log $OUTPUT_DIR/slurm/job_${INFER_NODE_RANK}_infer_node_rank_${INFER_NODE_RANK}.log
|
||||
else
|
||||
TRAIN_NODE_RANK=$((SLURM_PROCID - NUM_INFER_NODES))
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import tomli_w
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from prime_rl.trainer.sft.config import SFTTrainerConfig
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pydantic_config import parse_argv
|
||||
|
||||
TEMPLATE_DIR = Path(__file__).parent
|
||||
TEMPLATE_NAME = "sft_slurm.sh.j2"
|
||||
|
||||
|
||||
class SFTSLURMConfig(SFTTrainerConfig):
|
||||
job_name: str
|
||||
num_nodes: int = Field(default=1, description="Number of training nodes.")
|
||||
gpus_per_node: int = Field(default=8, description="Number of GPUs per node.")
|
||||
nodes_per_fsdp_group: int | None = Field(
|
||||
default=None,
|
||||
description="Number of nodes per FSDP island. Auto-sets model.dp_replicate = num_nodes / nodes_per_fsdp_group.",
|
||||
)
|
||||
|
||||
project_dir: Path = Field(
|
||||
default_factory=lambda: Path.cwd(),
|
||||
description="Path to the project root. Used to source .env, activate .venv, and run uv sync.",
|
||||
)
|
||||
hf_hub_offline: bool = Field(
|
||||
default=False, description="Set HF_HUB_OFFLINE=1 on training nodes to prevent downloading models at runtime."
|
||||
)
|
||||
|
||||
slurm_template: Path | None = Field(
|
||||
default=None, description="The path to the SLURM template file. If none, will use the default template."
|
||||
)
|
||||
dry_run: bool = Field(default=False, description="Only generate the SLURM script and configs without submitting.")
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_dp_replicate(self):
|
||||
if self.nodes_per_fsdp_group is not None:
|
||||
if self.num_nodes % self.nodes_per_fsdp_group != 0:
|
||||
raise ValueError(
|
||||
f"num_nodes ({self.num_nodes}) must be divisible by nodes_per_fsdp_group ({self.nodes_per_fsdp_group})"
|
||||
)
|
||||
self.model.dp_replicate = self.num_nodes // self.nodes_per_fsdp_group
|
||||
return self
|
||||
|
||||
|
||||
def write_trainer_config(config: SFTSLURMConfig, output_dir: Path) -> None:
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
slurm_only_fields = set(SFTSLURMConfig.model_fields) - set(SFTTrainerConfig.model_fields)
|
||||
trainer_data = config.model_dump(exclude_none=True, mode="json", exclude=slurm_only_fields)
|
||||
with open(output_dir / "trainer.toml", "wb") as f:
|
||||
tomli_w.dump(trainer_data, f)
|
||||
|
||||
|
||||
def render_slurm_script(config: SFTSLURMConfig, config_dir: Path) -> str:
|
||||
if config.slurm_template is not None:
|
||||
template_dir = config.slurm_template.parent
|
||||
template_name = config.slurm_template.name
|
||||
else:
|
||||
template_dir = TEMPLATE_DIR
|
||||
template_name = TEMPLATE_NAME
|
||||
env = Environment(loader=FileSystemLoader(template_dir), keep_trailing_newline=True)
|
||||
template = env.get_template(template_name)
|
||||
return template.render(
|
||||
job_name=config.job_name,
|
||||
output_dir=config.output_dir,
|
||||
config_dir=config_dir,
|
||||
num_nodes=config.num_nodes,
|
||||
project_dir=config.project_dir,
|
||||
gpus_per_node=config.gpus_per_node,
|
||||
hf_hub_offline=config.hf_hub_offline,
|
||||
)
|
||||
|
||||
|
||||
def sft_slurm(config: SFTSLURMConfig):
|
||||
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
|
||||
|
||||
config_dir = config.output_dir / "configs"
|
||||
write_trainer_config(config, config_dir)
|
||||
|
||||
logger.info(f"Wrote trainer config to {config_dir}")
|
||||
|
||||
script = render_slurm_script(config, config_dir)
|
||||
script_path = config.output_dir / "sft.sh"
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
log_message = f"Logs:\n Trainer: tail -f {config.output_dir}/slurm/latest_train_node_rank_0.log"
|
||||
|
||||
if config.dry_run:
|
||||
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
|
||||
return
|
||||
|
||||
logger.info(f"Submitting: sbatch {script_path}")
|
||||
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
logger.error(f"sbatch failed: {result.stderr.strip()}")
|
||||
sys.exit(1)
|
||||
|
||||
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
|
||||
|
||||
|
||||
def main():
|
||||
sft_slurm(parse_argv(SFTSLURMConfig))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,79 @@
|
||||
#!/bin/bash
|
||||
|
||||
#SBATCH --job-name={{ job_name }}
|
||||
#SBATCH --nodes={{ num_nodes }}
|
||||
#SBATCH --ntasks-per-node=1
|
||||
#SBATCH --gres=gpu:{{ gpus_per_node }}
|
||||
#SBATCH --partition=cluster
|
||||
#SBATCH --exclusive # Get the ENTIRE node exclusively
|
||||
#SBATCH --output=/shared/logs/job_%j.log
|
||||
#SBATCH --error=/shared/logs/job_%j.log
|
||||
|
||||
# Configs
|
||||
export NUM_NODES={{ num_nodes }}
|
||||
export GPUS_PER_NODE={{ gpus_per_node }}
|
||||
|
||||
# Paths
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
export CONFIG_DIR={{ config_dir }}
|
||||
export OUTPUT_DIR={{ output_dir }}
|
||||
mkdir -p $OUTPUT_DIR/slurm
|
||||
|
||||
# General
|
||||
export CUDA_DEVICE_ORDER=PCI_BUS_ID
|
||||
export PYTHONUNBUFFERED=1
|
||||
export OMP_NUM_THREADS=1
|
||||
|
||||
# Networking
|
||||
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
|
||||
echo "HOSTNAMES=${HOSTNAMES[@]}"
|
||||
|
||||
export MASTER_ADDR="${HOSTNAMES[0]}"
|
||||
export MASTER_PORT=29500
|
||||
echo "MASTER_ADDR=${MASTER_ADDR}"
|
||||
echo "MASTER_PORT=${MASTER_PORT}"
|
||||
|
||||
# Install environment
|
||||
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
|
||||
source $PROJECT_DIR/.venv/bin/activate
|
||||
|
||||
# Install environment as local package
|
||||
cd $PROJECT_DIR && uv sync --all-extras
|
||||
|
||||
|
||||
# Run SFT
|
||||
srun bash -c '
|
||||
# Setup environment
|
||||
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
|
||||
source $PROJECT_DIR/.venv/bin/activate
|
||||
|
||||
# Higher ulimit
|
||||
ulimit -n 65536
|
||||
export GIT_LFS_SKIP_SMUDGE=1
|
||||
|
||||
# Infiniband setup
|
||||
IB_HCA=$(ibv_devinfo | sed -n -e "/hca_id/p" -e "/link_layer:/p" | grep -B1 InfiniBand | grep hca_id | sed -e "s/^hca_id://g" | tr -d "[[:blank:]]" |paste -sd,)
|
||||
export NCCL_IB_HCA=$IB_HCA
|
||||
|
||||
TRAIN_NODE_RANK=$SLURM_PROCID
|
||||
|
||||
export HF_HUB_OFFLINE={{ 1 if hf_hub_offline else 0 }}
|
||||
|
||||
# This is required for compilation to work correctly
|
||||
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True"
|
||||
|
||||
echo $HOSTNAMES | tee $OUTPUT_DIR/slurm/latest_train_node_rank_${TRAIN_NODE_RANK}.log
|
||||
uv run torchrun \
|
||||
--nnodes=$NUM_NODES \
|
||||
--nproc-per-node=$GPUS_PER_NODE \
|
||||
--node-rank=$TRAIN_NODE_RANK \
|
||||
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
|
||||
--rdzv-id=job_$SLURM_JOB_ID \
|
||||
--log-dir=$OUTPUT_DIR/torchrun \
|
||||
--tee=3 \
|
||||
--redirects=3 \
|
||||
--local-ranks-filter=$(seq -s, 0 $((GPUS_PER_NODE - 1))) \
|
||||
-m prime_rl.trainer.sft.train \
|
||||
@ $CONFIG_DIR/trainer.toml \
|
||||
2>&1 | tee -a $OUTPUT_DIR/slurm/latest_train_node_rank_${TRAIN_NODE_RANK}.log $OUTPUT_DIR/slurm/job_${SLURM_JOB_ID}_train_node_rank_${TRAIN_NODE_RANK}.log
|
||||
'
|
||||
@@ -13,11 +13,6 @@ AttnImplementation: TypeAlias = Literal["sdpa", "flash_attention_2", "flash_atte
|
||||
# to attempt installing a kernel from hub.
|
||||
_ATTN_ALIASES = {"flash_attention_4": "fa4"}
|
||||
|
||||
MOE_MODEL_MAPS = {
|
||||
"Qwen/Qwen3-30B-A3B": "Jackmin108/Qwen3-30B-A3B-Fast",
|
||||
"moonshotai/Moonlight-16B-A3B-Instruct": "Jackmin108/Moonlight-16B-A3B-Instruct-Fast",
|
||||
}
|
||||
|
||||
|
||||
class ActivationCheckpointConfig(BaseConfig):
|
||||
"""Configures activation checkpointing."""
|
||||
@@ -255,6 +250,13 @@ class ModelConfig(BaseConfig):
|
||||
),
|
||||
] = True
|
||||
|
||||
freeze_moe_router: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to freeze the MoE router parameters during training.",
|
||||
),
|
||||
] = False
|
||||
|
||||
lora: Annotated[
|
||||
LoRAConfig | None,
|
||||
Field(
|
||||
@@ -291,13 +293,6 @@ class ModelConfig(BaseConfig):
|
||||
data["attn"] = _ATTN_ALIASES[data["attn"]]
|
||||
return data
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _map_model_name_for_moe(self):
|
||||
"""Map model name if it exists in MOE_MODEL_MAPS."""
|
||||
if self.name in MOE_MODEL_MAPS:
|
||||
self.name = MOE_MODEL_MAPS[self.name]
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def trust_remote_code_only_with_hf(self):
|
||||
"""Trust remote code only if the model is from HF."""
|
||||
|
||||
@@ -85,6 +85,34 @@ def freeze_vision_encoder(model: nn.Module) -> None:
|
||||
logger.info(f"Froze {num_frozen} parameters in vision encoder")
|
||||
|
||||
|
||||
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 layer in language_model.layers:
|
||||
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
|
||||
if mlp is None:
|
||||
continue
|
||||
|
||||
# Custom implementation: MoE class with router attribute
|
||||
if isinstance(mlp, MoE):
|
||||
for param in mlp.router.parameters():
|
||||
param.requires_grad = False
|
||||
num_frozen += 1
|
||||
# HuggingFace implementation: gate attribute (nn.Linear)
|
||||
elif hasattr(mlp, "gate") and isinstance(mlp.gate, nn.Linear):
|
||||
for param in mlp.gate.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")
|
||||
|
||||
|
||||
def is_tt_moe_model(model: nn.Module) -> bool:
|
||||
return hasattr(model.config, "num_experts") or hasattr(model.config, "n_routed_experts")
|
||||
|
||||
@@ -641,6 +669,9 @@ def setup_model(
|
||||
if config.lora is not None:
|
||||
apply_lora_to_model(model, config.lora)
|
||||
|
||||
if config.freeze_moe_router:
|
||||
freeze_moe_router(model)
|
||||
|
||||
if parallel_dims.ep_enabled:
|
||||
apply_ep(model, parallel_dims)
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ from transformers.models.llama.configuration_llama import LlamaConfig
|
||||
from prime_rl.trainer.models.afmoe import AfmoeConfig, AfmoeForCausalLM
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.glm4_moe import Glm4MoeConfig, Glm4MoeForCausalLM
|
||||
from prime_rl.trainer.models.glm_moe_dsa import GlmMoeDsaConfig, GlmMoeDsaForCausalLM
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput, cast_float_and_contiguous
|
||||
from prime_rl.trainer.models.llama import LlamaForCausalLM
|
||||
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2Config, MiniMaxM2ForCausalLM
|
||||
@@ -19,6 +20,7 @@ from prime_rl.trainer.models.qwen3_moe import Qwen3MoeConfig, Qwen3MoeForCausalL
|
||||
# Make custom config discoverable by AutoConfig
|
||||
AutoConfig.register("afmoe", AfmoeConfig, exist_ok=True)
|
||||
AutoConfig.register("glm4_moe", Glm4MoeConfig, exist_ok=True)
|
||||
AutoConfig.register("glm_moe_dsa", GlmMoeDsaConfig, exist_ok=True)
|
||||
AutoConfig.register("minimax_m2", MiniMaxM2Config, exist_ok=True)
|
||||
AutoConfig.register("qwen3_moe", Qwen3MoeConfig, exist_ok=True)
|
||||
|
||||
@@ -26,6 +28,7 @@ _CUSTOM_CAUSAL_LM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, OrderedDict()
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(LlamaConfig, LlamaForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(AfmoeConfig, AfmoeForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(Glm4MoeConfig, Glm4MoeForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(GlmMoeDsaConfig, GlmMoeDsaForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(MiniMaxM2Config, MiniMaxM2ForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(Qwen3MoeConfig, Qwen3MoeForCausalLM, exist_ok=True)
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
from prime_rl.trainer.models.glm_moe_dsa.configuration_glm_moe_dsa import GlmMoeDsaConfig
|
||||
from prime_rl.trainer.models.glm_moe_dsa.modeling_glm_moe_dsa import (
|
||||
GlmMoeDsaForCausalLM,
|
||||
GlmMoeDsaModel,
|
||||
GlmMoeDsaPreTrainedModel,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"GlmMoeDsaConfig",
|
||||
"GlmMoeDsaForCausalLM",
|
||||
"GlmMoeDsaModel",
|
||||
"GlmMoeDsaPreTrainedModel",
|
||||
]
|
||||
@@ -0,0 +1,209 @@
|
||||
import warnings
|
||||
|
||||
from transformers.configuration_utils import PretrainedConfig
|
||||
|
||||
|
||||
class GlmMoeDsaConfig(PretrainedConfig):
|
||||
r"""
|
||||
Configuration class for the GLM-5 (GlmMoeDsa) model.
|
||||
|
||||
GLM-5 uses DeepSeek V3.2-style Multi-head Latent Attention (MLA) with LoRA-compressed
|
||||
KV projections, combined with Mixture-of-Experts feed-forward layers.
|
||||
|
||||
Args:
|
||||
vocab_size (`int`, defaults to 154880):
|
||||
Vocabulary size.
|
||||
hidden_size (`int`, defaults to 6144):
|
||||
Dimension of the hidden representations.
|
||||
intermediate_size (`int`, defaults to 12288):
|
||||
Dimension of the dense MLP representations.
|
||||
moe_intermediate_size (`int`, defaults to 2048):
|
||||
Dimension of the MoE expert representations.
|
||||
num_hidden_layers (`int`, defaults to 78):
|
||||
Number of hidden layers in the Transformer decoder.
|
||||
num_attention_heads (`int`, defaults to 64):
|
||||
Number of attention heads.
|
||||
num_key_value_heads (`int`, defaults to 64):
|
||||
Number of key-value heads (after kv_b_proj up-projection).
|
||||
n_shared_experts (`int`, defaults to 1):
|
||||
Number of shared experts.
|
||||
n_routed_experts (`int`, defaults to 256):
|
||||
Number of routed experts.
|
||||
routed_scaling_factor (`float`, defaults to 2.5):
|
||||
Scaling factor for routed experts.
|
||||
kv_lora_rank (`int`, defaults to 512):
|
||||
Rank of the LoRA compression for key-value projections.
|
||||
q_lora_rank (`int`, defaults to 2048):
|
||||
Rank of the LoRA compression for query projections.
|
||||
qk_rope_head_dim (`int`, defaults to 64):
|
||||
Dimension of query/key heads that use rotary position embeddings.
|
||||
v_head_dim (`int`, defaults to 256):
|
||||
Dimension of value heads.
|
||||
qk_nope_head_dim (`int`, defaults to 192):
|
||||
Dimension of query/key heads that don't use rotary position embeddings.
|
||||
n_group (`int`, defaults to 1):
|
||||
Number of groups for routed experts.
|
||||
topk_group (`int`, defaults to 1):
|
||||
Number of selected groups per token.
|
||||
num_experts_per_tok (`int`, defaults to 8):
|
||||
Number of active experts per token.
|
||||
first_k_dense_replace (`int`, defaults to 3):
|
||||
Number of initial layers that use dense MLP instead of MoE.
|
||||
norm_topk_prob (`bool`, defaults to `True`):
|
||||
Whether to normalize the top-k routing probabilities.
|
||||
hidden_act (`str`, defaults to `"silu"`):
|
||||
Activation function in the feed-forward layers.
|
||||
max_position_embeddings (`int`, defaults to 202752):
|
||||
Maximum sequence length.
|
||||
initializer_range (`float`, defaults to 0.02):
|
||||
Standard deviation for weight initialization.
|
||||
rms_norm_eps (`float`, defaults to 1e-5):
|
||||
Epsilon for RMS normalization.
|
||||
rope_interleave (`bool`, defaults to `True`):
|
||||
Whether to use interleaved (non-neox) RoPE style.
|
||||
attention_bias (`bool`, defaults to `False`):
|
||||
Whether to use bias in attention projections.
|
||||
attention_dropout (`float`, defaults to 0.0):
|
||||
Dropout for attention probabilities.
|
||||
index_n_heads (`int`, defaults to 32):
|
||||
Number of heads used by the sparse indexer.
|
||||
index_head_dim (`int`, defaults to 128):
|
||||
Head dimension used by the sparse indexer.
|
||||
indexer_rope_interleave (`bool`, defaults to `True`):
|
||||
Whether to use interleaved RoPE style in the sparse indexer.
|
||||
index_topk (`int`, defaults to 2048):
|
||||
Number of top tokens selected by the sparse indexer.
|
||||
scoring_func (`str`, defaults to `"sigmoid"`):
|
||||
Scoring function for MoE router. Must match the vLLM inference
|
||||
server's expectation (vLLM defaults to ``"softmax"`` when this
|
||||
field is absent from the config).
|
||||
topk_method (`str`, defaults to `"noaux_tc"`):
|
||||
MoE routing top-k method used by GLM-5 checkpoints.
|
||||
use_grouped_mm (`bool`, defaults to `True`):
|
||||
Whether to use grouped matrix multiplication for MoE.
|
||||
"""
|
||||
|
||||
model_type = "glm_moe_dsa"
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
attribute_map = {"num_local_experts": "n_routed_experts"}
|
||||
|
||||
base_model_tp_plan = {
|
||||
"layers.*.self_attn.o_proj": "rowwise",
|
||||
"layers.*.mlp.experts.*.gate_proj": "colwise",
|
||||
"layers.*.mlp.experts.*.up_proj": "colwise",
|
||||
"layers.*.mlp.experts.*.down_proj": "rowwise",
|
||||
"layers.*.mlp.gate_proj": "colwise",
|
||||
"layers.*.mlp.up_proj": "colwise",
|
||||
"layers.*.mlp.down_proj": "rowwise",
|
||||
}
|
||||
base_model_pp_plan = {
|
||||
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
||||
"layers": (["hidden_states"], ["hidden_states"]),
|
||||
"norm": (["hidden_states"], ["hidden_states"]),
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vocab_size=154880,
|
||||
hidden_size=6144,
|
||||
intermediate_size=12288,
|
||||
moe_intermediate_size=2048,
|
||||
num_hidden_layers=78,
|
||||
num_attention_heads=64,
|
||||
num_key_value_heads=64,
|
||||
n_shared_experts=1,
|
||||
n_routed_experts=256,
|
||||
routed_scaling_factor=2.5,
|
||||
kv_lora_rank=512,
|
||||
q_lora_rank=2048,
|
||||
qk_rope_head_dim=64,
|
||||
v_head_dim=256,
|
||||
qk_nope_head_dim=192,
|
||||
n_group=1,
|
||||
topk_group=1,
|
||||
num_experts_per_tok=8,
|
||||
first_k_dense_replace=3,
|
||||
norm_topk_prob=True,
|
||||
hidden_act="silu",
|
||||
max_position_embeddings=202752,
|
||||
initializer_range=0.02,
|
||||
rms_norm_eps=1e-5,
|
||||
use_cache=True,
|
||||
tie_word_embeddings=False,
|
||||
rope_interleave=True,
|
||||
rope_parameters=None,
|
||||
rope_theta=10000.0,
|
||||
mlp_layer_types=None,
|
||||
attention_bias=False,
|
||||
attention_dropout=0.0,
|
||||
index_n_heads=32,
|
||||
index_head_dim=128,
|
||||
indexer_rope_interleave=True,
|
||||
pad_token_id=154820,
|
||||
index_topk=2048,
|
||||
scoring_func="sigmoid",
|
||||
topk_method="noaux_tc",
|
||||
use_grouped_mm=True,
|
||||
**kwargs,
|
||||
):
|
||||
self.vocab_size = vocab_size
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
self.hidden_size = hidden_size
|
||||
self.intermediate_size = intermediate_size
|
||||
self.moe_intermediate_size = moe_intermediate_size
|
||||
self.num_hidden_layers = num_hidden_layers
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.num_key_value_heads = num_key_value_heads
|
||||
|
||||
# MLA dimensions
|
||||
self.kv_lora_rank = kv_lora_rank
|
||||
self.q_lora_rank = q_lora_rank
|
||||
self.qk_rope_head_dim = qk_rope_head_dim
|
||||
self.v_head_dim = v_head_dim
|
||||
self.qk_nope_head_dim = qk_nope_head_dim
|
||||
self.qk_head_dim = qk_nope_head_dim + qk_rope_head_dim
|
||||
self.head_dim = qk_rope_head_dim
|
||||
|
||||
# MoE
|
||||
self.n_shared_experts = n_shared_experts
|
||||
self.n_routed_experts = n_routed_experts
|
||||
self.routed_scaling_factor = routed_scaling_factor
|
||||
self.n_group = n_group
|
||||
self.topk_group = topk_group
|
||||
self.num_experts_per_tok = num_experts_per_tok
|
||||
self.first_k_dense_replace = first_k_dense_replace
|
||||
self.norm_topk_prob = norm_topk_prob
|
||||
|
||||
# MLP layer types: per-layer dense/sparse dispatch
|
||||
if mlp_layer_types is None:
|
||||
mlp_layer_types = ["dense"] * min(first_k_dense_replace, num_hidden_layers) + ["sparse"] * max(
|
||||
0, num_hidden_layers - first_k_dense_replace
|
||||
)
|
||||
self.mlp_layer_types = mlp_layer_types
|
||||
|
||||
self.hidden_act = hidden_act
|
||||
self.initializer_range = initializer_range
|
||||
self.rms_norm_eps = rms_norm_eps
|
||||
self.use_cache = use_cache
|
||||
self.rope_interleave = rope_interleave
|
||||
self.rope_parameters = rope_parameters
|
||||
self.rope_theta = rope_theta
|
||||
self.attention_bias = attention_bias
|
||||
self.attention_dropout = attention_dropout
|
||||
self.index_n_heads = index_n_heads
|
||||
self.index_head_dim = index_head_dim
|
||||
self.indexer_rope_interleave = indexer_rope_interleave
|
||||
self.index_topk = index_topk
|
||||
self.scoring_func = scoring_func
|
||||
self.topk_method = topk_method
|
||||
self.use_grouped_mm = use_grouped_mm
|
||||
self.pad_token_id = pad_token_id
|
||||
|
||||
if not self.use_grouped_mm:
|
||||
warnings.warn("not using grouped mm for moe is very slow, should only be used for debugging")
|
||||
|
||||
super().__init__(
|
||||
pad_token_id=pad_token_id,
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
**kwargs,
|
||||
)
|
||||
@@ -0,0 +1,144 @@
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
|
||||
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
|
||||
return max(int(i.split(".")[2]) for i in state_dict.keys() if "model.layers." in i) + 1
|
||||
|
||||
|
||||
def _is_moe_layer(state_dict: dict[str, Tensor], layer_idx: int) -> bool:
|
||||
"""Check if a layer is an MoE layer by looking for the router gate weight."""
|
||||
return f"model.layers.{layer_idx}.mlp.gate.weight" in state_dict
|
||||
|
||||
|
||||
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int):
|
||||
i = layer_idx
|
||||
|
||||
if not _is_moe_layer(state_dict, i):
|
||||
return
|
||||
|
||||
# Router: gate.weight -> router.gate.weight
|
||||
state_dict[f"model.layers.{i}.mlp.router.gate.weight"] = state_dict[f"model.layers.{i}.mlp.gate.weight"]
|
||||
del state_dict[f"model.layers.{i}.mlp.gate.weight"]
|
||||
|
||||
# Routed experts: fused or per-expert format -> stacked w1/w2/w3
|
||||
if f"model.layers.{i}.mlp.experts.gate_up_proj" in state_dict:
|
||||
gate_up_proj = state_dict[f"model.layers.{i}.mlp.experts.gate_up_proj"]
|
||||
down_proj = state_dict[f"model.layers.{i}.mlp.experts.down_proj"]
|
||||
|
||||
num_experts, fused_dim, dim = gate_up_proj.shape
|
||||
moe_dim = fused_dim // 2
|
||||
|
||||
w1 = gate_up_proj[:, :moe_dim, :]
|
||||
w3 = gate_up_proj[:, moe_dim:, :]
|
||||
w2 = down_proj
|
||||
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.gate_up_proj"]
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.down_proj"]
|
||||
else:
|
||||
num_experts = len([j for j in state_dict.keys() if f"model.layers.{i}.mlp.experts" in j]) // 3
|
||||
if num_experts == 0:
|
||||
return
|
||||
|
||||
dim, moe_dim = state_dict[f"model.layers.{i}.mlp.experts.0.down_proj.weight"].shape
|
||||
dtype = state_dict[f"model.layers.{i}.mlp.experts.0.down_proj.weight"].dtype
|
||||
w1 = torch.empty((num_experts, moe_dim, dim), dtype=dtype)
|
||||
w2 = torch.empty((num_experts, dim, moe_dim), dtype=dtype)
|
||||
w3 = torch.empty((num_experts, moe_dim, dim), dtype=dtype)
|
||||
for j in range(num_experts):
|
||||
w1[j].copy_(state_dict[f"model.layers.{i}.mlp.experts.{j}.gate_proj.weight"])
|
||||
w2[j].copy_(state_dict[f"model.layers.{i}.mlp.experts.{j}.down_proj.weight"])
|
||||
w3[j].copy_(state_dict[f"model.layers.{i}.mlp.experts.{j}.up_proj.weight"])
|
||||
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.{j}.gate_proj.weight"]
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.{j}.down_proj.weight"]
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.{j}.up_proj.weight"]
|
||||
|
||||
state_dict[f"model.layers.{i}.mlp.experts.w1"] = w1
|
||||
state_dict[f"model.layers.{i}.mlp.experts.w2"] = w2
|
||||
state_dict[f"model.layers.{i}.mlp.experts.w3"] = w3
|
||||
|
||||
# Shared experts
|
||||
state_dict[f"model.layers.{i}.mlp.shared_expert.w1"] = state_dict[
|
||||
f"model.layers.{i}.mlp.shared_experts.gate_proj.weight"
|
||||
]
|
||||
state_dict[f"model.layers.{i}.mlp.shared_expert.w2"] = state_dict[
|
||||
f"model.layers.{i}.mlp.shared_experts.down_proj.weight"
|
||||
]
|
||||
state_dict[f"model.layers.{i}.mlp.shared_expert.w3"] = state_dict[
|
||||
f"model.layers.{i}.mlp.shared_experts.up_proj.weight"
|
||||
]
|
||||
del state_dict[f"model.layers.{i}.mlp.shared_experts.gate_proj.weight"]
|
||||
del state_dict[f"model.layers.{i}.mlp.shared_experts.down_proj.weight"]
|
||||
del state_dict[f"model.layers.{i}.mlp.shared_experts.up_proj.weight"]
|
||||
|
||||
# Expert bias for load balancing
|
||||
state_dict[f"model.layers.{i}.mlp.expert_bias"] = state_dict[f"model.layers.{i}.mlp.gate.e_score_correction_bias"]
|
||||
del state_dict[f"model.layers.{i}.mlp.gate.e_score_correction_bias"]
|
||||
|
||||
|
||||
def convert_hf_to_tt_moe(state_dict: dict[str, Tensor]):
|
||||
num_layers = get_max_layer_num(state_dict)
|
||||
for i in range(num_layers):
|
||||
convert_hf_layer_to_tt(state_dict, i)
|
||||
|
||||
|
||||
def convert_tt_layer_to_hf(state_dict: dict[str, Tensor], layer_index: int):
|
||||
i = layer_index
|
||||
|
||||
# Expert bias
|
||||
if f"model.layers.{i}.mlp.expert_bias" in state_dict:
|
||||
state_dict[f"model.layers.{i}.mlp.gate.e_score_correction_bias"] = state_dict[
|
||||
f"model.layers.{i}.mlp.expert_bias"
|
||||
]
|
||||
del state_dict[f"model.layers.{i}.mlp.expert_bias"]
|
||||
if f"model.layers.{i}.mlp.tokens_per_expert" in state_dict:
|
||||
del state_dict[f"model.layers.{i}.mlp.tokens_per_expert"]
|
||||
|
||||
# Shared experts
|
||||
if f"model.layers.{i}.mlp.shared_expert.w1" in state_dict:
|
||||
state_dict[f"model.layers.{i}.mlp.shared_experts.gate_proj.weight"] = state_dict[
|
||||
f"model.layers.{i}.mlp.shared_expert.w1"
|
||||
]
|
||||
state_dict[f"model.layers.{i}.mlp.shared_experts.down_proj.weight"] = state_dict[
|
||||
f"model.layers.{i}.mlp.shared_expert.w2"
|
||||
]
|
||||
state_dict[f"model.layers.{i}.mlp.shared_experts.up_proj.weight"] = state_dict[
|
||||
f"model.layers.{i}.mlp.shared_expert.w3"
|
||||
]
|
||||
|
||||
if state_dict[f"model.layers.{i}.mlp.shared_experts.up_proj.weight"].shape[0] == 1:
|
||||
state_dict[f"model.layers.{i}.mlp.shared_experts.up_proj.weight"] = state_dict[
|
||||
f"model.layers.{i}.mlp.shared_experts.up_proj.weight"
|
||||
][0]
|
||||
state_dict[f"model.layers.{i}.mlp.shared_experts.down_proj.weight"] = state_dict[
|
||||
f"model.layers.{i}.mlp.shared_experts.down_proj.weight"
|
||||
][0]
|
||||
state_dict[f"model.layers.{i}.mlp.shared_experts.gate_proj.weight"] = state_dict[
|
||||
f"model.layers.{i}.mlp.shared_experts.gate_proj.weight"
|
||||
][0]
|
||||
del state_dict[f"model.layers.{i}.mlp.shared_expert.w1"]
|
||||
del state_dict[f"model.layers.{i}.mlp.shared_expert.w2"]
|
||||
del state_dict[f"model.layers.{i}.mlp.shared_expert.w3"]
|
||||
|
||||
# Router
|
||||
if f"model.layers.{i}.mlp.router.gate.weight" in state_dict:
|
||||
state_dict[f"model.layers.{i}.mlp.gate.weight"] = state_dict[f"model.layers.{i}.mlp.router.gate.weight"]
|
||||
del state_dict[f"model.layers.{i}.mlp.router.gate.weight"]
|
||||
|
||||
# Routed experts - convert to per-expert format (compatible with vLLM and transformers)
|
||||
w1 = state_dict.pop(f"model.layers.{i}.mlp.experts.w1") # (num_experts, moe_dim, dim)
|
||||
w2 = state_dict.pop(f"model.layers.{i}.mlp.experts.w2") # (num_experts, dim, moe_dim)
|
||||
w3 = state_dict.pop(f"model.layers.{i}.mlp.experts.w3") # (num_experts, moe_dim, dim)
|
||||
|
||||
num_experts = w1.shape[0]
|
||||
for j in range(num_experts):
|
||||
state_dict[f"model.layers.{i}.mlp.experts.{j}.gate_proj.weight"] = w1[j]
|
||||
state_dict[f"model.layers.{i}.mlp.experts.{j}.down_proj.weight"] = w2[j]
|
||||
state_dict[f"model.layers.{i}.mlp.experts.{j}.up_proj.weight"] = w3[j]
|
||||
|
||||
|
||||
def convert_tt_to_hf_moe(state_dict: dict[str, Tensor]):
|
||||
num_layers = get_max_layer_num(state_dict)
|
||||
for i in range(num_layers):
|
||||
convert_tt_layer_to_hf(state_dict, i)
|
||||
@@ -0,0 +1,439 @@
|
||||
import warnings
|
||||
from typing import Optional, Union
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import Tensor, nn
|
||||
from transformers.cache_utils import Cache
|
||||
from transformers.generation import GenerationMixin
|
||||
from transformers.modeling_layers import GradientCheckpointingLayer
|
||||
from transformers.modeling_outputs import BaseModelOutputWithPast
|
||||
from transformers.processing_utils import Unpack
|
||||
from transformers.utils import TransformersKwargs, auto_docstring
|
||||
from transformers.utils.deprecation import deprecate_kwarg
|
||||
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.glm_moe_dsa.configuration_glm_moe_dsa import GlmMoeDsaConfig
|
||||
from prime_rl.trainer.models.glm_moe_dsa.converting_glm_moe_dsa import (
|
||||
convert_hf_layer_to_tt,
|
||||
convert_hf_to_tt_moe,
|
||||
convert_tt_layer_to_hf,
|
||||
convert_tt_to_hf_moe,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.rms_norm import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import (
|
||||
RotaryEmbedding,
|
||||
RotaryEmbeddingConfig,
|
||||
apply_rotary_pos_emb_interleave,
|
||||
)
|
||||
|
||||
try:
|
||||
from prime_rl.trainer.models.kernels.sparse_mla_bwd import sparse_mla_bwd
|
||||
from prime_rl.trainer.models.kernels.sparse_mla_fwd import sparse_mla_fwd_interface
|
||||
except ImportError:
|
||||
sparse_mla_fwd_interface = None # type: ignore
|
||||
sparse_mla_bwd = None # type: ignore
|
||||
|
||||
from prime_rl.trainer.models.kernels.fp8_indexer import fp8_indexer
|
||||
|
||||
|
||||
class _SparseMLA(torch.autograd.Function):
|
||||
"""Autograd wrapper for tilelang sparse MLA forward/backward kernels."""
|
||||
|
||||
@staticmethod
|
||||
def forward(ctx, q, kv, indices, sm_scale):
|
||||
out, lse = sparse_mla_fwd_interface(q, kv, indices, sm_scale=sm_scale)
|
||||
ctx.save_for_backward(q, kv, out, indices, lse)
|
||||
ctx.sm_scale = sm_scale
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, do):
|
||||
q, kv, out, indices, lse = ctx.saved_tensors
|
||||
dq, dkv = sparse_mla_bwd(q, kv, out, do.contiguous(), indices, lse, sm_scale=ctx.sm_scale)
|
||||
return dq, dkv, None, None
|
||||
|
||||
|
||||
class LayerNorm(nn.Module):
|
||||
def __init__(self, dim: int, eps: float = 1e-6):
|
||||
super().__init__()
|
||||
self.dim = dim
|
||||
self.eps = eps
|
||||
self.weight = nn.Parameter(torch.ones(dim, dtype=torch.float32))
|
||||
self.bias = nn.Parameter(torch.zeros(dim, dtype=torch.float32))
|
||||
|
||||
def forward(self, x: torch.Tensor):
|
||||
return F.layer_norm(x.float(), (self.dim,), self.weight.float(), self.bias.float(), self.eps).type_as(x)
|
||||
|
||||
|
||||
class Indexer(nn.Module):
|
||||
def __init__(self, config: GlmMoeDsaConfig):
|
||||
super().__init__()
|
||||
if config.q_lora_rank is None:
|
||||
raise ValueError("Sparse indexer requires q_lora_rank to be set")
|
||||
|
||||
self.n_head = config.index_n_heads
|
||||
self.head_dim = config.index_head_dim
|
||||
self.rope_dim = config.qk_rope_head_dim
|
||||
self.wq_b = nn.Linear(config.q_lora_rank, self.n_head * self.head_dim, bias=False)
|
||||
self.wk = nn.Linear(config.hidden_size, self.head_dim, bias=config.attention_bias)
|
||||
self.k_norm = LayerNorm(dim=self.head_dim, eps=1e-6)
|
||||
self.weights_proj = nn.Linear(config.hidden_size, self.n_head, bias=False)
|
||||
self.weight_scale = (self.head_dim**-0.5) * (self.n_head**-0.5)
|
||||
|
||||
@torch.no_grad()
|
||||
def compute_sparse_indices(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
q_latent: torch.Tensor,
|
||||
ks: torch.Tensor,
|
||||
ke: torch.Tensor,
|
||||
index_topk: int,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
) -> torch.Tensor:
|
||||
total_tokens = hidden_states.shape[1]
|
||||
assert index_topk % 64 == 0, f"index_topk must be divisible by 64 (block_I), got {index_topk}"
|
||||
|
||||
q_idx = self.wq_b(q_latent[0]).view(total_tokens, self.n_head, self.head_dim)
|
||||
k_idx = self.k_norm(self.wk(hidden_states[0]))
|
||||
w = self.weights_proj(hidden_states[0])
|
||||
|
||||
q_pe = q_idx[..., : self.rope_dim]
|
||||
q_nope = q_idx[..., self.rope_dim :]
|
||||
k_pe = k_idx[..., : self.rope_dim]
|
||||
k_nope = k_idx[..., self.rope_dim :]
|
||||
|
||||
cos, sin = position_embeddings
|
||||
q_pe = q_pe.unsqueeze(0).transpose(1, 2)
|
||||
k_pe = k_pe.unsqueeze(0).unsqueeze(1)
|
||||
q_pe, k_pe = apply_rotary_pos_emb_interleave(q_pe, k_pe, cos, sin)
|
||||
q_pe = q_pe.transpose(1, 2).squeeze(0)
|
||||
k_pe = k_pe.squeeze(1).squeeze(0)
|
||||
|
||||
q_idx = torch.cat([q_pe, q_nope], dim=-1)
|
||||
k_idx = torch.cat([k_pe, k_nope], dim=-1)
|
||||
|
||||
indices = fp8_indexer(q_idx, k_idx, w, ks, ke, index_topk, self.weight_scale)
|
||||
return indices.view(1, total_tokens, 1, index_topk)
|
||||
|
||||
|
||||
class GlmMoeDsaAttention(nn.Module):
|
||||
def __init__(self, config: GlmMoeDsaConfig):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.num_heads = config.num_attention_heads
|
||||
self.kv_lora_rank = config.kv_lora_rank
|
||||
self.qk_rope_head_dim = config.qk_rope_head_dim
|
||||
self.qk_nope_head_dim = config.qk_nope_head_dim
|
||||
self.qk_head_dim = config.qk_head_dim
|
||||
self.v_head_dim = config.v_head_dim
|
||||
|
||||
self.q_a_proj = nn.Linear(config.hidden_size, config.q_lora_rank, bias=config.attention_bias)
|
||||
self.q_a_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.q_lora_rank, eps=config.rms_norm_eps))
|
||||
self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.qk_head_dim, bias=False)
|
||||
|
||||
self.kv_a_proj_with_mqa = nn.Linear(
|
||||
config.hidden_size,
|
||||
self.kv_lora_rank + self.qk_rope_head_dim,
|
||||
bias=config.attention_bias,
|
||||
)
|
||||
self.kv_a_layernorm = RMSNorm(RMSNormConfig(hidden_size=self.kv_lora_rank, eps=config.rms_norm_eps))
|
||||
self.kv_b_proj = nn.Linear(
|
||||
self.kv_lora_rank,
|
||||
self.num_heads * (self.qk_nope_head_dim + self.v_head_dim),
|
||||
bias=False,
|
||||
)
|
||||
|
||||
self.o_proj = nn.Linear(self.num_heads * self.v_head_dim, config.hidden_size, bias=config.attention_bias)
|
||||
self.indexer = Indexer(config)
|
||||
self.scaling = self.qk_head_dim ** (-0.5)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
ks: torch.Tensor | None = None,
|
||||
ke: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
batch_size, total_tokens, _ = hidden_states.shape
|
||||
|
||||
q_latent = self.q_a_layernorm(self.q_a_proj(hidden_states))
|
||||
q_full = self.q_b_proj(q_latent).view(batch_size, total_tokens, self.num_heads, self.qk_head_dim)
|
||||
q_nope, q_rope = q_full.split([self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
|
||||
|
||||
compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
|
||||
k_compressed, k_rope = compressed_kv.split([self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
|
||||
k_compressed_normed = self.kv_a_layernorm(k_compressed)
|
||||
|
||||
q_rope_r = q_rope.transpose(1, 2)
|
||||
k_rope_r = k_rope.unsqueeze(1)
|
||||
cos, sin = position_embeddings
|
||||
q_rope_r, k_rope_r = apply_rotary_pos_emb_interleave(q_rope_r, k_rope_r, cos, sin)
|
||||
q_rope = q_rope_r.transpose(1, 2)
|
||||
k_rope = k_rope_r.squeeze(1)
|
||||
|
||||
indices = self.indexer.compute_sparse_indices(
|
||||
hidden_states, q_latent, ks, ke, self.config.index_topk, position_embeddings
|
||||
)
|
||||
|
||||
# KV absorption
|
||||
kv_b_w = self.kv_b_proj.weight.view(self.num_heads, self.qk_nope_head_dim + self.v_head_dim, self.kv_lora_rank)
|
||||
w_k_nope = kv_b_w[:, : self.qk_nope_head_dim, :]
|
||||
w_v = kv_b_w[:, self.qk_nope_head_dim :, :]
|
||||
|
||||
q_absorbed = torch.einsum("bshd,hdk->bshk", q_nope, w_k_nope)
|
||||
|
||||
sparse_q = torch.cat([q_absorbed, q_rope], dim=-1)
|
||||
sparse_kv = torch.cat([k_compressed_normed, k_rope], dim=-1).unsqueeze(2)
|
||||
|
||||
# Sentinel zero-token so padded indices (= total_tokens) are in-bounds
|
||||
sentinel = torch.zeros(batch_size, 1, 1, sparse_kv.shape[-1], dtype=sparse_kv.dtype, device=sparse_kv.device)
|
||||
sparse_kv = torch.cat([sparse_kv, sentinel], dim=1)
|
||||
|
||||
out = _SparseMLA.apply(sparse_q, sparse_kv, indices, self.scaling)
|
||||
|
||||
# Un-absorb
|
||||
out = torch.einsum("bshk,hdk->bshd", out, w_v)
|
||||
|
||||
out = out.reshape(batch_size, total_tokens, -1)
|
||||
return self.o_proj(out), None
|
||||
|
||||
|
||||
class GlmMoeDsaDecoderLayer(GradientCheckpointingLayer):
|
||||
def __init__(self, config: GlmMoeDsaConfig, layer_idx: int):
|
||||
super().__init__()
|
||||
self.hidden_size = config.hidden_size
|
||||
self.self_attn = GlmMoeDsaAttention(config)
|
||||
|
||||
moe_args = MoEArgs(
|
||||
num_experts=config.n_routed_experts,
|
||||
num_shared_experts=config.n_shared_experts,
|
||||
score_func="sigmoid",
|
||||
route_norm=config.norm_topk_prob,
|
||||
route_scale=config.routed_scaling_factor,
|
||||
score_before_experts=False,
|
||||
top_k=config.num_experts_per_tok,
|
||||
load_balance_coeff=1e-3,
|
||||
use_grouped_mm=config.use_grouped_mm,
|
||||
)
|
||||
mlp_config = MLPConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
intermediate_size=config.intermediate_size,
|
||||
gate_act=config.hidden_act,
|
||||
bias=False,
|
||||
)
|
||||
|
||||
if layer_idx >= config.first_k_dense_replace:
|
||||
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
|
||||
else:
|
||||
self.mlp = MLP(mlp_config)
|
||||
|
||||
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
|
||||
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
|
||||
ks: Optional[torch.Tensor] = None,
|
||||
ke: Optional[torch.Tensor] = None,
|
||||
) -> torch.Tensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.input_layernorm(hidden_states)
|
||||
hidden_states, _ = self.self_attn(
|
||||
hidden_states=hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
ks=ks,
|
||||
ke=ke,
|
||||
)
|
||||
hidden_states = residual + hidden_states
|
||||
|
||||
residual = hidden_states
|
||||
hidden_states = self.post_attention_layernorm(hidden_states)
|
||||
hidden_states = self.mlp(hidden_states)
|
||||
hidden_states = residual + hidden_states
|
||||
return hidden_states
|
||||
|
||||
|
||||
@auto_docstring
|
||||
class GlmMoeDsaPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
config: GlmMoeDsaConfig
|
||||
base_model_prefix = "model"
|
||||
supports_gradient_checkpointing = True
|
||||
_no_split_modules = ["GlmMoeDsaDecoderLayer"]
|
||||
_skip_keys_device_placement = ["past_key_values"]
|
||||
_supports_flash_attn = True
|
||||
_supports_sdpa = True
|
||||
_supports_flex_attn = True
|
||||
_can_compile_fullgraph = False
|
||||
_supports_attention_backend = True
|
||||
_can_record_outputs = {
|
||||
"hidden_states": GlmMoeDsaDecoderLayer,
|
||||
}
|
||||
|
||||
def _init_weights(self, module):
|
||||
super()._init_weights(module)
|
||||
|
||||
@classmethod
|
||||
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return any("mlp.experts.1.up_proj" in name or "mlp.experts.gate_up_proj" in name for name in state_dict.keys())
|
||||
|
||||
@classmethod
|
||||
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return any("mlp.experts.w1" in module_name for module_name in state_dict.keys())
|
||||
|
||||
@classmethod
|
||||
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
convert_tt_to_hf_moe(state_dict)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_to_prime(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
convert_hf_to_tt_moe(state_dict)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_hf(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
convert_tt_layer_to_hf(state_dict, layer_idx)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_prime(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
convert_hf_layer_to_tt(state_dict, layer_idx)
|
||||
return state_dict
|
||||
|
||||
|
||||
@auto_docstring
|
||||
class GlmMoeDsaModel(GlmMoeDsaPreTrainedModel):
|
||||
def __init__(self, config: GlmMoeDsaConfig):
|
||||
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(
|
||||
[GlmMoeDsaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
||||
)
|
||||
self.norm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
|
||||
rope_parameters = getattr(config, "rope_parameters", None) or {}
|
||||
rope_type = rope_parameters.get("rope_type", "default") if isinstance(rope_parameters, dict) else "default"
|
||||
rotary_config = RotaryEmbeddingConfig(
|
||||
max_position_embeddings=config.max_position_embeddings,
|
||||
rope_type=rope_type,
|
||||
model_config=config,
|
||||
)
|
||||
self.rotary_emb = RotaryEmbedding(rotary_config)
|
||||
self.gradient_checkpointing = False
|
||||
|
||||
self.post_init()
|
||||
|
||||
@auto_docstring
|
||||
def forward(
|
||||
self,
|
||||
input_ids: Optional[torch.LongTensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
inputs_embeds: Optional[torch.FloatTensor] = None,
|
||||
) -> BaseModelOutputWithPast:
|
||||
if (input_ids is None) ^ (inputs_embeds is not None):
|
||||
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
||||
|
||||
if inputs_embeds is None:
|
||||
inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
|
||||
|
||||
flat_position_ids = position_ids.view(-1)
|
||||
S = flat_position_ids.shape[0]
|
||||
ks = torch.arange(S, dtype=torch.int32, device=flat_position_ids.device) - flat_position_ids.to(torch.int32)
|
||||
ke = torch.arange(1, S + 1, dtype=torch.int32, device=flat_position_ids.device)
|
||||
|
||||
hidden_states = inputs_embeds
|
||||
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
||||
|
||||
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
ks=ks,
|
||||
ke=ke,
|
||||
)
|
||||
|
||||
hidden_states = self.norm(hidden_states)
|
||||
return BaseModelOutputWithPast(last_hidden_state=hidden_states)
|
||||
|
||||
|
||||
@auto_docstring
|
||||
class GlmMoeDsaForCausalLM(GlmMoeDsaPreTrainedModel, GenerationMixin):
|
||||
_tied_weights_keys = ["lm_head.weight"]
|
||||
_tp_plan = {"lm_head": "colwise_rep"}
|
||||
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
||||
|
||||
def __init__(self, config):
|
||||
super().__init__(config)
|
||||
self.model = GlmMoeDsaModel(config)
|
||||
self.vocab_size = config.vocab_size
|
||||
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
||||
|
||||
warnings.warn("GlmMoeDsaForCausalLM is experimental, higher trainer<->inference KL mismatch may be observed.")
|
||||
warnings.warn("`model.attn` is ignored, GlmMoeDsa uses only sparse attention.")
|
||||
|
||||
self.post_init()
|
||||
|
||||
@auto_docstring
|
||||
def forward(
|
||||
self,
|
||||
input_ids: Optional[torch.LongTensor] = 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,
|
||||
temperature: Optional[torch.Tensor] = None,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> PrimeLmOutput:
|
||||
r"""
|
||||
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
||||
Labels used by PrimeRL's wrapped LM head to optionally compute per-token logprobs/entropy.
|
||||
temperature (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
||||
Per-token temperatures for logprobs/entropy computation when `labels` are provided.
|
||||
"""
|
||||
assert use_cache is None, "use_cache is not supported for custom glm_moe_dsa for now"
|
||||
assert past_key_values is None, "past_key_values is not supported for custom glm_moe_dsa for now"
|
||||
|
||||
if position_ids is None:
|
||||
if inputs_embeds is not None:
|
||||
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
||||
else:
|
||||
position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).unsqueeze(0)
|
||||
|
||||
outputs: BaseModelOutputWithPast = self.model(
|
||||
input_ids=input_ids,
|
||||
position_ids=position_ids,
|
||||
inputs_embeds=inputs_embeds,
|
||||
)
|
||||
|
||||
hidden_states = outputs.last_hidden_state
|
||||
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
||||
return self.lm_head(
|
||||
hidden_states[:, slice_indices, :],
|
||||
labels[:, slice_indices] if labels is not None else None,
|
||||
temperature=temperature,
|
||||
)
|
||||
|
||||
def init_buffers_post_meta(self):
|
||||
buffer_names = [name for name, _ in self.named_buffers()]
|
||||
if "model.rotary_emb.inv_freq" in buffer_names:
|
||||
rotary_emb = self.model.rotary_emb
|
||||
inv_freq, rotary_emb.attention_scaling = rotary_emb.rope_init_fn(
|
||||
rotary_emb.config, rotary_emb.inv_freq.device
|
||||
)
|
||||
rotary_emb.inv_freq.copy_(inv_freq)
|
||||
|
||||
|
||||
__all__ = ["GlmMoeDsaConfig", "GlmMoeDsaPreTrainedModel", "GlmMoeDsaModel", "GlmMoeDsaForCausalLM"]
|
||||
@@ -0,0 +1,236 @@
|
||||
"""Triton FP8 indexer kernel for DSA sparse token selection.
|
||||
|
||||
Scoring formula: I_{t,s} = Σ_j w_{t,j} · ReLU(q_{t,j} · k_s)
|
||||
|
||||
FP8 quantization vendored from vLLM (Apache 2.0).
|
||||
"""
|
||||
|
||||
import torch
|
||||
import triton
|
||||
import triton.language as tl
|
||||
|
||||
FP8_MAX = 448.0
|
||||
FP8_MIN = -448.0
|
||||
FP8_EPS = 1e-10
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _per_token_group_quant_fp8(
|
||||
y_ptr,
|
||||
y_q_ptr,
|
||||
y_s_ptr,
|
||||
group_size,
|
||||
y_num_columns,
|
||||
y_row_stride,
|
||||
eps,
|
||||
fp8_min,
|
||||
fp8_max,
|
||||
use_ue8m0: tl.constexpr,
|
||||
BLOCK: tl.constexpr,
|
||||
):
|
||||
groups_per_row = y_num_columns // group_size
|
||||
|
||||
g_id = tl.program_id(0)
|
||||
row = g_id // groups_per_row
|
||||
row_g_id = g_id % groups_per_row
|
||||
|
||||
y_ptr_offset = (row.to(tl.int64) * y_row_stride) + (row_g_id.to(tl.int64) * group_size)
|
||||
y_ptr += y_ptr_offset
|
||||
|
||||
y_q_ptr_offset = g_id.to(tl.int64) * group_size
|
||||
y_q_ptr += y_q_ptr_offset
|
||||
y_s_ptr += g_id
|
||||
|
||||
cols = tl.arange(0, BLOCK)
|
||||
mask = cols < group_size
|
||||
|
||||
y = tl.load(y_ptr + cols, mask=mask, other=0.0).to(tl.float32)
|
||||
|
||||
_absmax = tl.maximum(tl.max(tl.abs(y)), eps)
|
||||
scale_raw = _absmax / fp8_max
|
||||
y_s = tl.math.exp2(tl.ceil(tl.log2(scale_raw))) if use_ue8m0 else scale_raw
|
||||
y_q = tl.clamp(y / y_s, fp8_min, fp8_max).to(y_q_ptr.dtype.element_ty)
|
||||
|
||||
tl.store(y_q_ptr + cols, y_q, mask=mask)
|
||||
tl.store(y_s_ptr, y_s)
|
||||
|
||||
|
||||
def per_token_group_quant_fp8(
|
||||
x: torch.Tensor, group_size: int, use_ue8m0: bool = True
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
assert x.shape[-1] % group_size == 0
|
||||
assert x.stride(-1) == 1
|
||||
|
||||
x_q = torch.empty(x.shape, device=x.device, dtype=torch.float8_e4m3fn)
|
||||
shape = x.shape[:-1] + (x.shape[-1] // group_size,)
|
||||
x_s = torch.empty(shape, device=x.device, dtype=torch.float32)
|
||||
|
||||
M = x.numel() // group_size
|
||||
N = group_size
|
||||
BLOCK = triton.next_power_of_2(N)
|
||||
num_warps = min(max(BLOCK // 256, 1), 8)
|
||||
|
||||
_per_token_group_quant_fp8[(M,)](
|
||||
x,
|
||||
x_q,
|
||||
x_s,
|
||||
group_size,
|
||||
x.shape[-1],
|
||||
x.stride(-2),
|
||||
FP8_EPS,
|
||||
FP8_MIN,
|
||||
FP8_MAX,
|
||||
use_ue8m0=use_ue8m0,
|
||||
BLOCK=BLOCK,
|
||||
num_warps=num_warps,
|
||||
num_stages=1,
|
||||
)
|
||||
return x_q, x_s
|
||||
|
||||
|
||||
@triton.autotune(
|
||||
configs=[
|
||||
triton.Config({"BLOCK_M": 64, "BLOCK_N": 64}, num_warps=4, num_stages=2),
|
||||
triton.Config({"BLOCK_M": 64, "BLOCK_N": 128}, num_warps=4, num_stages=2),
|
||||
triton.Config({"BLOCK_M": 128, "BLOCK_N": 64}, num_warps=8, num_stages=2),
|
||||
triton.Config({"BLOCK_M": 128, "BLOCK_N": 128}, num_warps=8, num_stages=2),
|
||||
triton.Config({"BLOCK_M": 64, "BLOCK_N": 64}, num_warps=8, num_stages=3),
|
||||
triton.Config({"BLOCK_M": 64, "BLOCK_N": 128}, num_warps=8, num_stages=3),
|
||||
],
|
||||
key=["S"],
|
||||
)
|
||||
@triton.jit
|
||||
def _triton_fp8_indexer_kernel(
|
||||
Q_fp8,
|
||||
K_fp8,
|
||||
K_scales,
|
||||
W,
|
||||
Out,
|
||||
KS,
|
||||
KE,
|
||||
S,
|
||||
stride_qh,
|
||||
stride_qs,
|
||||
stride_ks,
|
||||
stride_ws,
|
||||
H: tl.constexpr,
|
||||
D: tl.constexpr,
|
||||
BLOCK_M: tl.constexpr,
|
||||
BLOCK_N: tl.constexpr,
|
||||
):
|
||||
pid_m = tl.program_id(0)
|
||||
pid_n = tl.program_id(1)
|
||||
|
||||
offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
|
||||
offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
|
||||
offs_d = tl.arange(0, D)
|
||||
|
||||
mask_m = offs_m < S
|
||||
mask_n = offs_n < S
|
||||
|
||||
ks_vals = tl.load(KS + offs_m, mask=mask_m, other=S)
|
||||
ke_vals = tl.load(KE + offs_m, mask=mask_m, other=0)
|
||||
|
||||
offs_m_64 = offs_m.to(tl.int64)
|
||||
offs_n_64 = offs_n.to(tl.int64)
|
||||
out_ptrs = Out + offs_m_64[:, None] * S + offs_n_64[None, :]
|
||||
out_mask = mask_m[:, None] & mask_n[None, :]
|
||||
|
||||
ks_min = tl.min(ks_vals)
|
||||
ke_max = tl.max(ke_vals)
|
||||
n_lo = pid_n * BLOCK_N
|
||||
|
||||
if n_lo >= ke_max or n_lo + BLOCK_N <= ks_min:
|
||||
tl.store(out_ptrs, tl.full([BLOCK_M, BLOCK_N], float("-inf"), tl.float32), mask=out_mask)
|
||||
return
|
||||
|
||||
# Clamp indices for FP8 loads (can't use mask+other with fp8 dtype)
|
||||
offs_n_safe = tl.minimum(offs_n, S - 1)
|
||||
offs_m_safe = tl.minimum(offs_m, S - 1)
|
||||
|
||||
k_block = tl.load(K_fp8 + offs_n_safe[:, None] * stride_ks + offs_d[None, :])
|
||||
k_sc = tl.load(K_scales + offs_n_safe, mask=mask_n, other=0.0).to(tl.float32)
|
||||
|
||||
acc = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)
|
||||
|
||||
for h in range(H):
|
||||
q_h = tl.load(Q_fp8 + h * stride_qh + offs_m_safe[:, None] * stride_qs + offs_d[None, :])
|
||||
w_h = tl.load(W + offs_m * stride_ws + h, mask=mask_m, other=0.0).to(tl.float32)
|
||||
|
||||
scores = tl.dot(q_h, tl.trans(k_block)).to(tl.float32)
|
||||
scores = tl.maximum(scores, 0.0) * k_sc[None, :]
|
||||
acc += scores * w_h[:, None]
|
||||
|
||||
valid = (offs_n[None, :] >= ks_vals[:, None]) & (offs_n[None, :] < ke_vals[:, None])
|
||||
acc = tl.where(valid, acc, float("-inf"))
|
||||
|
||||
tl.store(out_ptrs, acc, mask=out_mask)
|
||||
|
||||
|
||||
def fp8_indexer(q, k, w, ks, ke, topk, weight_scale=1.0):
|
||||
"""Triton FP8 indexer: UE8M0 quantization + fused scoring kernel + topk.
|
||||
|
||||
Args:
|
||||
q: [S, H, D] bf16 query vectors per head
|
||||
k: [S, D] bf16 key vectors (shared across heads)
|
||||
w: [S, H] bf16 per-head weights
|
||||
ks: [S] int32 sequence start per token
|
||||
ke: [S] int32 causal end per token (= position + 1)
|
||||
topk: number of top indices to return
|
||||
weight_scale: constant scaling factor for weights
|
||||
|
||||
Returns:
|
||||
[S, topk] int32 selected token indices per query
|
||||
"""
|
||||
# NOTE: We don't use weight scale in this kernel as it produces higher KL mismatch for some reason
|
||||
# This is not a problem result-wise, as it is a constant multiplier
|
||||
_weight_scale = weight_scale
|
||||
S, H, D = q.shape
|
||||
device = q.device
|
||||
|
||||
q_flat = q.reshape(S * H, D).contiguous()
|
||||
q_fp8, q_scales = per_token_group_quant_fp8(q_flat, group_size=D, use_ue8m0=True)
|
||||
k_fp8, k_scales = per_token_group_quant_fp8(k.contiguous(), group_size=D, use_ue8m0=True)
|
||||
|
||||
q_fp8 = q_fp8.view(S, H, D).permute(1, 0, 2).contiguous()
|
||||
|
||||
# Fold q_scale into weights
|
||||
q_scales = q_scales.view(S, H)
|
||||
w = w * q_scales
|
||||
|
||||
logits = torch.empty(S, S, dtype=torch.float32, device=device)
|
||||
|
||||
grid = lambda meta: (
|
||||
triton.cdiv(S, meta["BLOCK_M"]),
|
||||
triton.cdiv(S, meta["BLOCK_N"]),
|
||||
)
|
||||
_triton_fp8_indexer_kernel[grid](
|
||||
q_fp8,
|
||||
k_fp8,
|
||||
k_scales,
|
||||
w,
|
||||
logits,
|
||||
ks,
|
||||
ke,
|
||||
S,
|
||||
q_fp8.stride(0),
|
||||
q_fp8.stride(1),
|
||||
k_fp8.stride(0),
|
||||
w.stride(0),
|
||||
H=H,
|
||||
D=D,
|
||||
)
|
||||
|
||||
actual_topk = min(topk, S)
|
||||
_, indices = torch.topk(logits, actual_topk, dim=-1)
|
||||
if actual_topk < topk:
|
||||
padding = torch.full((S, topk - actual_topk), S, dtype=indices.dtype, device=device)
|
||||
indices = torch.cat([indices, padding], dim=-1)
|
||||
|
||||
# Replace cross-sequence indices with sentinel S (maps to zero-valued KV)
|
||||
ks_exp = ks.unsqueeze(1).expand_as(indices)
|
||||
ke_exp = ke.unsqueeze(1).expand_as(indices)
|
||||
out_of_range = (indices < ks_exp) | (indices >= ke_exp)
|
||||
indices = indices.masked_fill(out_of_range, S)
|
||||
|
||||
return indices.to(torch.int32)
|
||||
@@ -0,0 +1,286 @@
|
||||
# Vendored from tile-ai/tilelang (Apache 2.0), modified for dynamic shapes.
|
||||
|
||||
import tilelang
|
||||
import torch
|
||||
from tilelang import language as T
|
||||
|
||||
|
||||
@tilelang.jit(out_idx=[-1])
|
||||
def preprocess(
|
||||
H,
|
||||
D,
|
||||
block_ND=32,
|
||||
num_stages=5,
|
||||
dtype=T.bfloat16,
|
||||
accum_dtype=T.float32,
|
||||
):
|
||||
assert dtype == T.bfloat16
|
||||
assert accum_dtype == T.float32
|
||||
B = T.dynamic("B")
|
||||
S = T.dynamic("S")
|
||||
shape = [B, S, H, D]
|
||||
|
||||
@T.prim_func
|
||||
def preprocess_kernel(
|
||||
O: T.Tensor(shape, dtype),
|
||||
dO: T.Tensor(shape, dtype),
|
||||
Delta: T.Tensor([B, S, H], accum_dtype),
|
||||
):
|
||||
with T.Kernel(H, T.ceildiv(S, block_ND), B) as (bx, by, bz):
|
||||
o = T.alloc_fragment([block_ND, block_ND], accum_dtype)
|
||||
do = T.alloc_fragment([block_ND, block_ND], accum_dtype)
|
||||
delta = T.alloc_fragment([block_ND], accum_dtype)
|
||||
acc = T.alloc_fragment([block_ND, block_ND], accum_dtype)
|
||||
T.clear(acc)
|
||||
for k in T.Pipelined(T.ceildiv(D, block_ND), num_stages=num_stages):
|
||||
T.copy(O[bz, by * block_ND : (by + 1) * block_ND, bx, k * block_ND : (k + 1) * block_ND], o)
|
||||
T.copy(dO[bz, by * block_ND : (by + 1) * block_ND, bx, k * block_ND : (k + 1) * block_ND], do)
|
||||
for i, j in T.Parallel(block_ND, block_ND):
|
||||
acc[i, j] += o[i, j] * do[i, j]
|
||||
T.reduce_sum(acc, delta, 1)
|
||||
T.copy(delta, Delta[bz, by * block_ND : (by + 1) * block_ND, bx])
|
||||
|
||||
return preprocess_kernel
|
||||
|
||||
|
||||
@tilelang.jit(out_idx=[-1])
|
||||
def postprocess(
|
||||
D,
|
||||
D_tail,
|
||||
kv_group=1,
|
||||
block_N=64,
|
||||
threads=128,
|
||||
dtype=T.bfloat16,
|
||||
accum_dtype=T.float32,
|
||||
):
|
||||
assert dtype == T.bfloat16
|
||||
assert accum_dtype == T.float32
|
||||
B = T.dynamic("B")
|
||||
S_kv = T.dynamic("S_kv")
|
||||
dkv_shape = [B, S_kv, kv_group, D + D_tail]
|
||||
|
||||
@T.prim_func
|
||||
def postprocess_kernel(
|
||||
dKV: T.Tensor(dkv_shape, accum_dtype),
|
||||
dKV_out: T.Tensor(dkv_shape, dtype),
|
||||
):
|
||||
with T.Kernel(T.ceildiv(S_kv, block_N), kv_group, B, threads=threads) as (bx, by, bz):
|
||||
T.copy(
|
||||
dKV[bz, bx * block_N : (bx + 1) * block_N, by, :],
|
||||
dKV_out[bz, bx * block_N : (bx + 1) * block_N, by, :],
|
||||
)
|
||||
|
||||
return postprocess_kernel
|
||||
|
||||
|
||||
@tilelang.jit(
|
||||
out_idx=[-2],
|
||||
pass_configs={
|
||||
tilelang.PassConfigKey.TL_DISABLE_TMA_LOWER: True,
|
||||
tilelang.PassConfigKey.TL_DISABLE_WARP_SPECIALIZED: True,
|
||||
tilelang.PassConfigKey.TL_ENABLE_AGGRESSIVE_SHARED_MEMORY_MERGE: True,
|
||||
},
|
||||
)
|
||||
def bwd(
|
||||
H,
|
||||
D,
|
||||
D_tail,
|
||||
topk,
|
||||
kv_group=1,
|
||||
sm_scale=None,
|
||||
is_causal=True,
|
||||
block_size=32,
|
||||
num_stages=0,
|
||||
threads=256,
|
||||
indices_dtype=T.int32,
|
||||
dtype=T.bfloat16,
|
||||
accum_dtype=T.float32,
|
||||
):
|
||||
assert is_causal is True, "non-casual is not supported now"
|
||||
assert topk % block_size == 0, "otherwise will load some index=0 thus causing wrong kv to be loaded"
|
||||
assert dtype == T.bfloat16
|
||||
assert accum_dtype == T.float32
|
||||
assert indices_dtype == T.int32
|
||||
|
||||
if sm_scale is None:
|
||||
sm_scale = (D + D_tail) ** (-0.5)
|
||||
sm_scale_mul_reciprocal_log2 = sm_scale * 1.44269504 # log2(e)
|
||||
|
||||
B = T.dynamic("B")
|
||||
S = T.dynamic("S")
|
||||
S_kv = T.dynamic("S_kv")
|
||||
|
||||
H_kv = H // kv_group
|
||||
q_shape = [B, S, H, D + D_tail]
|
||||
k_shape = [B, S_kv, kv_group, D + D_tail]
|
||||
o_shape = [B, S, H, D]
|
||||
indices_shape = [B, S, kv_group, topk]
|
||||
delta_shape = [B, S, H]
|
||||
lse_shape = [B, S, H]
|
||||
|
||||
H = H_kv
|
||||
padded_H = max(tilelang.math.next_power_of_2(H_kv), 16)
|
||||
block_H = min(64, padded_H)
|
||||
assert padded_H % block_H == 0
|
||||
NH = padded_H // block_H
|
||||
BS = block_size
|
||||
NS = tilelang.cdiv(topk, block_size)
|
||||
|
||||
split_store = 2
|
||||
|
||||
@T.prim_func
|
||||
def sparse_mla_bwd_kernel(
|
||||
Q: T.Tensor(q_shape, dtype),
|
||||
KV: T.Tensor(k_shape, dtype),
|
||||
dO: T.Tensor(o_shape, dtype),
|
||||
Indices: T.Tensor(indices_shape, indices_dtype),
|
||||
Lse: T.Tensor(lse_shape, accum_dtype),
|
||||
Delta: T.Tensor(delta_shape, accum_dtype),
|
||||
dQ: T.Tensor(q_shape, dtype),
|
||||
dKV: T.Tensor(k_shape, accum_dtype),
|
||||
):
|
||||
with T.Kernel(S, B, kv_group * NH, threads=threads) as (s_i, by, bz):
|
||||
Q_shared = T.alloc_shared([block_H, D], dtype)
|
||||
Q_tail_shared = T.alloc_shared([block_H, D_tail], dtype)
|
||||
KV_shared = T.alloc_shared([BS, D], dtype)
|
||||
KV_tail_shared = T.alloc_shared([BS, D_tail], dtype)
|
||||
dO_shared = T.alloc_shared([block_H, D], dtype)
|
||||
mask = T.alloc_fragment([BS], "bool")
|
||||
|
||||
P_shared_cast = T.alloc_shared([block_H, BS], dtype)
|
||||
dP_shared_cast = T.alloc_shared([block_H, BS], dtype)
|
||||
dQ_shared = T.alloc_shared([block_H, D], dtype)
|
||||
dQ_tail_shared = T.alloc_shared([block_H, D_tail], dtype)
|
||||
|
||||
acc_p = T.alloc_fragment([block_H, BS], accum_dtype)
|
||||
acc_dp = T.alloc_fragment([block_H, BS], accum_dtype)
|
||||
acc_dq = T.alloc_fragment([block_H, D], accum_dtype)
|
||||
acc_dq_tail = T.alloc_fragment([block_H, D_tail], accum_dtype)
|
||||
acc_dkv = T.alloc_fragment([BS, D], accum_dtype)
|
||||
acc_dkv_tail = T.alloc_fragment([BS, D_tail], accum_dtype)
|
||||
acc_dkv_shared = T.alloc_shared([BS // split_store, D], accum_dtype)
|
||||
acc_dkv_tail_shared = T.alloc_shared([BS // split_store, D_tail], accum_dtype)
|
||||
|
||||
max_kv_i = s_i
|
||||
|
||||
T.copy(Q[by, s_i, bz * block_H : (bz + 1) * block_H, :D], Q_shared)
|
||||
T.copy(Q[by, s_i, bz * block_H : (bz + 1) * block_H, D:], Q_tail_shared)
|
||||
T.copy(dO[by, s_i, bz * block_H : (bz + 1) * block_H, :D], dO_shared)
|
||||
|
||||
T.clear(acc_dq)
|
||||
T.clear(acc_dq_tail)
|
||||
|
||||
for i_i in T.Pipelined(NS, num_stages=num_stages):
|
||||
for bi_i in T.Parallel(BS):
|
||||
mask[bi_i] = Indices[by, s_i, bz // NH, i_i * BS + bi_i] <= max_kv_i
|
||||
|
||||
for h_i, bi_i in T.Parallel(block_H, BS):
|
||||
acc_p[h_i, bi_i] = T.if_then_else(mask[bi_i], 0, -T.infinity(acc_p.dtype))
|
||||
|
||||
for bi_i, d_i in T.Parallel(BS, D):
|
||||
KV_shared[bi_i, d_i] = KV[by, Indices[by, s_i, bz // NH, i_i * BS + bi_i], bz // NH, d_i]
|
||||
|
||||
T.gemm(Q_shared, KV_shared, acc_p, transpose_B=True, policy=T.GemmWarpPolicy.FullCol)
|
||||
|
||||
for bi_i, d_i in T.Parallel(BS, D_tail):
|
||||
KV_tail_shared[bi_i, d_i] = KV[by, Indices[by, s_i, bz // NH, i_i * BS + bi_i], bz // NH, D + d_i]
|
||||
T.gemm(Q_tail_shared, KV_tail_shared, acc_p, transpose_B=True, policy=T.GemmWarpPolicy.FullCol)
|
||||
|
||||
for h_i, bi_i in T.Parallel(block_H, BS):
|
||||
acc_p[h_i, bi_i] = T.exp2(
|
||||
acc_p[h_i, bi_i] * sm_scale_mul_reciprocal_log2 - Lse[by, s_i, bz * block_H + h_i]
|
||||
)
|
||||
|
||||
T.copy(acc_p, P_shared_cast)
|
||||
|
||||
T.gemm(
|
||||
dO_shared, KV_shared, acc_dp, transpose_B=True, policy=T.GemmWarpPolicy.FullCol, clear_accum=True
|
||||
)
|
||||
|
||||
for h_i, bi_i in T.Parallel(block_H, BS):
|
||||
acc_dp[h_i, bi_i] = (
|
||||
acc_p[h_i, bi_i] * (acc_dp[h_i, bi_i] - Delta[by, s_i, bz * block_H + h_i]) * sm_scale
|
||||
)
|
||||
|
||||
T.copy(acc_dp, dP_shared_cast)
|
||||
T.gemm(dP_shared_cast, KV_shared, acc_dq, policy=T.GemmWarpPolicy.FullCol)
|
||||
T.gemm(dP_shared_cast, KV_tail_shared, acc_dq_tail, policy=T.GemmWarpPolicy.FullCol)
|
||||
|
||||
T.gemm(
|
||||
dP_shared_cast,
|
||||
Q_shared,
|
||||
acc_dkv,
|
||||
transpose_A=True,
|
||||
policy=T.GemmWarpPolicy.FullCol,
|
||||
clear_accum=True,
|
||||
)
|
||||
T.gemm(P_shared_cast, dO_shared, acc_dkv, transpose_A=True, policy=T.GemmWarpPolicy.FullCol)
|
||||
|
||||
T.clear(acc_dkv_tail)
|
||||
T.gemm(dP_shared_cast, Q_tail_shared, acc_dkv_tail, transpose_A=True, policy=T.GemmWarpPolicy.FullCol)
|
||||
|
||||
for s in range(split_store):
|
||||
for bi_i, d_i in T.Parallel(BS, D):
|
||||
if bi_i < BS // split_store:
|
||||
acc_dkv_shared[bi_i, d_i] = acc_dkv[bi_i + s * (BS // split_store), d_i]
|
||||
|
||||
for bi_i, d_i in T.Parallel(BS, D_tail):
|
||||
if bi_i < BS // split_store:
|
||||
acc_dkv_tail_shared[bi_i, d_i] = acc_dkv_tail[bi_i + s * (BS // split_store), d_i]
|
||||
|
||||
for bi_i, d_i in T.Parallel(BS // split_store, D // 4):
|
||||
T.atomic_addx4(
|
||||
dKV[
|
||||
by,
|
||||
Indices[by, s_i, bz // NH, i_i * BS + bi_i + s * (BS // split_store)],
|
||||
bz // NH,
|
||||
d_i * 4,
|
||||
],
|
||||
acc_dkv_shared[bi_i, d_i * 4],
|
||||
)
|
||||
|
||||
for bi_i, d_i in T.Parallel(BS // split_store, D_tail // 4):
|
||||
T.atomic_addx4(
|
||||
dKV[
|
||||
by,
|
||||
Indices[by, s_i, bz // NH, i_i * BS + bi_i + s * (BS // split_store)],
|
||||
bz // NH,
|
||||
D + d_i * 4,
|
||||
],
|
||||
acc_dkv_tail_shared[bi_i, d_i * 4],
|
||||
)
|
||||
|
||||
T.copy(acc_dq, dQ_shared)
|
||||
T.copy(acc_dq_tail, dQ_tail_shared)
|
||||
|
||||
T.copy(dQ_shared, dQ[by, s_i, bz * block_H : (bz + 1) * block_H, :D])
|
||||
T.copy(dQ_tail_shared, dQ[by, s_i, bz * block_H : (bz + 1) * block_H, D:])
|
||||
|
||||
return sparse_mla_bwd_kernel
|
||||
|
||||
|
||||
def sparse_mla_bwd(q, kv, o, do, indices, lse, sm_scale=None):
|
||||
assert q.is_contiguous()
|
||||
assert kv.is_contiguous()
|
||||
assert indices.is_contiguous()
|
||||
assert lse.is_contiguous()
|
||||
B, S, H, dim_plus_tail_dim = q.shape
|
||||
_, S_kv, kv_group, _ = kv.shape
|
||||
assert kv.shape[-1] == dim_plus_tail_dim
|
||||
assert kv.shape[0] == B
|
||||
D = 512
|
||||
D_tail = dim_plus_tail_dim - D
|
||||
topk = indices.shape[-1]
|
||||
assert indices.shape == (B, S, kv_group, topk)
|
||||
assert lse.shape == (B, S, H)
|
||||
|
||||
preprocess_kernel = preprocess(H, D)
|
||||
bwd_kernel = bwd(H, D, D_tail, topk, kv_group, sm_scale, True)
|
||||
postprocess_kernel = postprocess(D, D_tail, kv_group)
|
||||
|
||||
delta = preprocess_kernel(o, do)
|
||||
dkv = torch.zeros_like(kv, dtype=torch.float32)
|
||||
dq = bwd_kernel(q, kv, do, indices, lse, delta, dkv)
|
||||
dkv = postprocess_kernel(dkv)
|
||||
|
||||
return dq, dkv
|
||||
@@ -0,0 +1,195 @@
|
||||
# Vendored from tile-ai/tilelang (Apache 2.0), modified for dynamic shapes.
|
||||
|
||||
import tilelang
|
||||
from tilelang import language as T
|
||||
|
||||
|
||||
@tilelang.jit(
|
||||
out_idx=[-2, -1],
|
||||
pass_configs={
|
||||
tilelang.PassConfigKey.TL_DISABLE_TMA_LOWER: True,
|
||||
tilelang.PassConfigKey.TL_DISABLE_WARP_SPECIALIZED: True,
|
||||
},
|
||||
)
|
||||
def sparse_mla_fwd(
|
||||
heads,
|
||||
dim,
|
||||
tail_dim,
|
||||
topk,
|
||||
kv_group=1,
|
||||
sm_scale=None,
|
||||
is_causal=True,
|
||||
CP0=True,
|
||||
block_I=64,
|
||||
num_stages=2,
|
||||
threads=256,
|
||||
):
|
||||
assert dim == tilelang.math.next_power_of_2(dim), f"haven't check padding correctness yet, dim={dim}"
|
||||
assert tail_dim == tilelang.math.next_power_of_2(tail_dim), f"haven't check padding correctness yet, dim={tail_dim}"
|
||||
assert is_causal is True, "non-casual is not supported"
|
||||
assert topk % block_I == 0, "otherwise will load some index=0 thus causing wrong kv to be loaded"
|
||||
if sm_scale is None:
|
||||
sm_scale = (1.0 / (dim + tail_dim)) ** 0.5 * 1.44269504 # log2(e)
|
||||
else:
|
||||
sm_scale = sm_scale * 1.44269504 # log2(e)
|
||||
|
||||
batch = T.dynamic("batch")
|
||||
seq_len = T.dynamic("seq_len")
|
||||
seq_len_kv = T.dynamic("seq_len_kv")
|
||||
|
||||
head_kv = heads // kv_group
|
||||
q_shape = [batch, seq_len, heads, dim + tail_dim]
|
||||
kv_shape = [batch, seq_len_kv, kv_group, dim + tail_dim]
|
||||
o_shape = [batch, seq_len, heads, dim]
|
||||
indices_shape = [batch, seq_len, kv_group, topk]
|
||||
lse_shape = [batch, seq_len, heads]
|
||||
indices_dtype = T.int32
|
||||
dtype = T.bfloat16
|
||||
accum_dtype = T.float32
|
||||
|
||||
H = head_kv
|
||||
padded_H = max(tilelang.math.next_power_of_2(head_kv), 16)
|
||||
if padded_H != H:
|
||||
assert kv_group == 1, (
|
||||
"here we solve the H padding automatically, other wise you should handle Q copy and Output copy"
|
||||
" with your mask (when kv_group == 1, use g_i * padded_H:(g_i+1) * padded_H would be handled"
|
||||
" automatically)"
|
||||
)
|
||||
BI = block_I
|
||||
NI = tilelang.cdiv(topk, block_I)
|
||||
D = dim
|
||||
D_tail = tail_dim
|
||||
|
||||
if head_kv > 64:
|
||||
assert head_kv % 64 == 0, "head_kv should be a multiple of 64"
|
||||
REPLICATE_H = head_kv // 64
|
||||
else:
|
||||
REPLICATE_H = 1
|
||||
|
||||
H_per_block = padded_H if REPLICATE_H == 1 else 64
|
||||
|
||||
@T.prim_func
|
||||
def main(
|
||||
Q: T.Tensor(q_shape, dtype), # type: ignore
|
||||
KV: T.Tensor(kv_shape, dtype), # type: ignore
|
||||
Indices: T.Tensor(indices_shape, indices_dtype), # type: ignore
|
||||
Output: T.Tensor(o_shape, dtype), # type: ignore
|
||||
Lse: T.Tensor(lse_shape, accum_dtype), # type: ignore
|
||||
):
|
||||
with T.Kernel(seq_len * REPLICATE_H, batch, kv_group, threads=threads) as (
|
||||
bx,
|
||||
by,
|
||||
bz,
|
||||
):
|
||||
Q_shared = T.alloc_shared([H_per_block, D], dtype)
|
||||
Q_tail_shared = T.alloc_shared([H_per_block, D_tail], dtype)
|
||||
KV_shared = T.alloc_shared([BI, D], dtype)
|
||||
K_tail_shared = T.alloc_shared([BI, D_tail], dtype)
|
||||
O_shared = T.alloc_shared([H_per_block, D], dtype) # noqa: F841
|
||||
Lse_shared = T.alloc_shared([H_per_block], accum_dtype) # noqa: F841
|
||||
mask = T.alloc_fragment([BI], "bool")
|
||||
|
||||
acc_o = T.alloc_fragment([H_per_block, D], accum_dtype)
|
||||
acc_s = T.alloc_fragment([H_per_block, BI], accum_dtype)
|
||||
S_shared = T.alloc_shared([H_per_block, BI], dtype)
|
||||
sumexp = T.alloc_fragment([H_per_block], accum_dtype)
|
||||
sumexp_i = T.alloc_fragment([H_per_block], accum_dtype)
|
||||
alpha = T.alloc_fragment([H_per_block], accum_dtype)
|
||||
m_i = T.alloc_fragment([H_per_block], accum_dtype)
|
||||
m_i_prev = T.alloc_fragment([H_per_block], accum_dtype)
|
||||
|
||||
T.fill(acc_o, 0)
|
||||
T.fill(sumexp, 0)
|
||||
T.fill(m_i, -(2**30))
|
||||
|
||||
b_i, g_i = by, bz
|
||||
s_i = bx if REPLICATE_H == 1 else (bx // REPLICATE_H)
|
||||
q_i = s_i
|
||||
max_kv_i = q_i
|
||||
|
||||
H0 = g_i * padded_H + (0 if REPLICATE_H == 1 else (bx % REPLICATE_H) * 64)
|
||||
H1 = H0 + H_per_block
|
||||
|
||||
T.copy(Q[b_i, s_i, H0:H1, :D], Q_shared)
|
||||
T.copy(Q[b_i, s_i, H0:H1, D:], Q_tail_shared)
|
||||
|
||||
for i_i in T.Pipelined(NI, num_stages=num_stages):
|
||||
for bi_i in T.Parallel(BI):
|
||||
mask[bi_i] = Indices[b_i, s_i, g_i, i_i * BI + bi_i] <= max_kv_i
|
||||
|
||||
for bi_i, d_i in T.Parallel(BI, D):
|
||||
KV_shared[bi_i, d_i] = KV[b_i, Indices[b_i, s_i, g_i, i_i * BI + bi_i], g_i, d_i]
|
||||
for bi_i, d_i in T.Parallel(BI, D_tail):
|
||||
K_tail_shared[bi_i, d_i] = KV[b_i, Indices[b_i, s_i, g_i, i_i * BI + bi_i], g_i, D + d_i]
|
||||
|
||||
for h_i, bi_i in T.Parallel(H_per_block, BI):
|
||||
acc_s[h_i, bi_i] = T.if_then_else(mask[bi_i], 0, -T.infinity(acc_s.dtype))
|
||||
T.gemm(
|
||||
Q_shared,
|
||||
KV_shared,
|
||||
acc_s,
|
||||
transpose_B=True,
|
||||
policy=T.GemmWarpPolicy.FullRow,
|
||||
)
|
||||
T.gemm(
|
||||
Q_tail_shared,
|
||||
K_tail_shared,
|
||||
acc_s,
|
||||
transpose_B=True,
|
||||
policy=T.GemmWarpPolicy.FullRow,
|
||||
)
|
||||
T.copy(m_i, m_i_prev)
|
||||
T.reduce_max(acc_s, m_i, dim=1, clear=False)
|
||||
for h_i in T.Parallel(H_per_block):
|
||||
m_i[h_i] = T.max(m_i[h_i], m_i_prev[h_i])
|
||||
for h_i in T.Parallel(H_per_block):
|
||||
alpha[h_i] = T.exp2((m_i_prev[h_i] - m_i[h_i]) * sm_scale)
|
||||
for h_i, bi_i in T.Parallel(H_per_block, BI):
|
||||
acc_s[h_i, bi_i] = T.exp2(acc_s[h_i, bi_i] * sm_scale - m_i[h_i] * sm_scale)
|
||||
T.reduce_sum(acc_s, sumexp_i, dim=1)
|
||||
for h_i in T.Parallel(H_per_block):
|
||||
sumexp[h_i] = sumexp[h_i] * alpha[h_i] + sumexp_i[h_i]
|
||||
for h_i, d_i in T.Parallel(H_per_block, D):
|
||||
acc_o[h_i, d_i] = acc_o[h_i, d_i] * alpha[h_i]
|
||||
|
||||
T.copy(acc_s, S_shared)
|
||||
T.gemm(S_shared, KV_shared, acc_o, policy=T.GemmWarpPolicy.FullRow)
|
||||
|
||||
for h_i, d_i in T.Parallel(H_per_block, D):
|
||||
acc_o[h_i, d_i] /= sumexp[h_i]
|
||||
for h_i in T.Parallel(H_per_block):
|
||||
sumexp[h_i] = T.log2(sumexp[h_i]) + m_i[h_i] * sm_scale
|
||||
|
||||
T.copy(acc_o, Output[b_i, s_i, H0:H1, :])
|
||||
T.copy(sumexp, Lse[b_i, s_i, H0:H1])
|
||||
|
||||
return main
|
||||
|
||||
|
||||
def sparse_mla_fwd_interface(q, kv, indices, sm_scale=None, d_v=512, block_I=64, num_stages=2, threads=256):
|
||||
assert q.is_contiguous() and kv.is_contiguous() and indices.is_contiguous()
|
||||
batch, seq_len, heads, dim_plus_tail_dim = q.shape
|
||||
_, seq_len_kv, kv_group, _ = kv.shape
|
||||
|
||||
assert dim_plus_tail_dim == 576, "you should assign dim otherwise"
|
||||
dim = d_v
|
||||
assert kv.shape[-1] == dim_plus_tail_dim
|
||||
assert kv.shape[0] == batch
|
||||
tail_dim = dim_plus_tail_dim - dim
|
||||
_, _, _, topk = indices.shape
|
||||
assert indices.shape == (batch, seq_len, kv_group, topk)
|
||||
|
||||
kernel = sparse_mla_fwd(
|
||||
heads,
|
||||
dim,
|
||||
tail_dim,
|
||||
topk,
|
||||
kv_group,
|
||||
sm_scale,
|
||||
True,
|
||||
block_I=block_I,
|
||||
num_stages=num_stages,
|
||||
threads=threads,
|
||||
)
|
||||
out, lse = kernel(q, kv, indices)
|
||||
return out, lse
|
||||
@@ -115,3 +115,34 @@ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
||||
q_embed = torch.cat([q_embed, q_pass], dim=-1)
|
||||
k_embed = torch.cat([k_embed, k_pass], dim=-1)
|
||||
return q_embed, k_embed
|
||||
|
||||
|
||||
def apply_rotary_pos_emb_interleave(q, k, cos, sin, unsqueeze_dim=1):
|
||||
"""Interleaved RoPE: converts from [r0, i0, r1, i1, ...] layout before applying rotation.
|
||||
|
||||
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.
|
||||
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)
|
||||
|
||||
b, h, s, d = q.shape
|
||||
q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
|
||||
b, h, s, d = k.shape
|
||||
k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
|
||||
|
||||
q_embed = (q * cos) + (rotate_half(q) * sin)
|
||||
k_embed = (k * cos) + (rotate_half(k) * sin)
|
||||
return q_embed, k_embed
|
||||
|
||||
@@ -96,31 +96,33 @@ class StaticInferencePool:
|
||||
pass
|
||||
|
||||
|
||||
async def setup_inference_pool(client_config: ClientConfig, model_name: str) -> InferencePool:
|
||||
async def setup_inference_pool(
|
||||
client_config: ClientConfig, model_name: str, client_type: str = "openai_chat_completions"
|
||||
) -> InferencePool:
|
||||
"""Create an inference pool from config (static or elastic)."""
|
||||
logger = get_logger()
|
||||
|
||||
if client_config.is_elastic:
|
||||
from prime_rl.utils.elastic import ElasticInferencePool
|
||||
|
||||
return await ElasticInferencePool.from_config(client_config, model_name=model_name)
|
||||
return await ElasticInferencePool.from_config(client_config, model_name=model_name, client_type=client_type)
|
||||
|
||||
logger.info(
|
||||
f"Initializing static inference pool (base_url={', '.join(client_config.base_url)}, "
|
||||
f"api_key_var={client_config.api_key_var}, headers={client_config.headers})"
|
||||
)
|
||||
return StaticInferencePool(
|
||||
clients=setup_clients(client_config),
|
||||
clients=setup_clients(client_config, client_type=client_type),
|
||||
admin_clients=setup_admin_clients(client_config),
|
||||
skip_model_check=client_config.skip_model_check,
|
||||
)
|
||||
|
||||
|
||||
def setup_clients(client_config: ClientConfig) -> list[vf.ClientConfig]:
|
||||
def setup_clients(client_config: ClientConfig, client_type: str = "openai_chat_completions") -> list[vf.ClientConfig]:
|
||||
def setup_client(client_idx: int, base_url: str) -> vf.ClientConfig:
|
||||
return vf.ClientConfig(
|
||||
client_idx=client_idx,
|
||||
client_type="openai_chat_completions_token",
|
||||
client_type=client_type,
|
||||
api_base_url=base_url,
|
||||
api_key_var=client_config.api_key_var,
|
||||
timeout=client_config.timeout,
|
||||
|
||||
@@ -107,6 +107,7 @@ class ElasticInferencePool:
|
||||
model_name: str,
|
||||
port: int = 8000,
|
||||
sync_interval: float = 5.0,
|
||||
client_type: str = "openai_chat_completions",
|
||||
):
|
||||
self.logger = get_logger()
|
||||
self.hostname = hostname
|
||||
@@ -115,6 +116,7 @@ class ElasticInferencePool:
|
||||
self.base_model_name = model_name # Keep original for health checks
|
||||
self.port = port
|
||||
self.sync_interval = sync_interval
|
||||
self.client_type = client_type
|
||||
|
||||
self._servers: dict[str, ServerState] = {}
|
||||
self._admin_clients: dict[str, AsyncClient] = {}
|
||||
@@ -129,7 +131,9 @@ class ElasticInferencePool:
|
||||
self._started = False
|
||||
|
||||
@classmethod
|
||||
async def from_config(cls, config: ClientConfig, model_name: str) -> ElasticInferencePool:
|
||||
async def from_config(
|
||||
cls, config: ClientConfig, model_name: str, client_type: str = "openai_chat_completions"
|
||||
) -> ElasticInferencePool:
|
||||
if config.elastic is None:
|
||||
raise ValueError("Elastic inference pool requires elastic config")
|
||||
pool = cls(
|
||||
@@ -138,6 +142,7 @@ class ElasticInferencePool:
|
||||
model_name=model_name,
|
||||
port=config.elastic.port,
|
||||
sync_interval=config.elastic.sync_interval,
|
||||
client_type=client_type,
|
||||
)
|
||||
await pool.start()
|
||||
return pool
|
||||
@@ -168,7 +173,8 @@ class ElasticInferencePool:
|
||||
base_url=urls,
|
||||
api_key_var=self.client_config.api_key_var,
|
||||
headers=self.client_config.headers,
|
||||
)
|
||||
),
|
||||
client_type=self.client_type,
|
||||
)
|
||||
if urls
|
||||
else []
|
||||
|
||||
@@ -8,6 +8,7 @@ from prime_rl.inference.config import InferenceConfig
|
||||
from prime_rl.orchestrator.config import OrchestratorConfig
|
||||
from prime_rl.rl import RLConfig
|
||||
from prime_rl.slurm.rl import RLSLURMConfig
|
||||
from prime_rl.slurm.sft import SFTSLURMConfig
|
||||
from prime_rl.trainer.rl.config import RLTrainerConfig
|
||||
from prime_rl.trainer.sft.config import SFTTrainerConfig
|
||||
from prime_rl.utils.pydantic_config import parse_argv
|
||||
@@ -20,6 +21,7 @@ CONFIG_CLASSES = [
|
||||
OrchestratorConfig,
|
||||
InferenceConfig,
|
||||
RLSLURMConfig,
|
||||
SFTSLURMConfig,
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import pytest
|
||||
|
||||
from prime_rl.inference.config import ModelConfig
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"model_name,expected_parser",
|
||||
[
|
||||
# GLM-4.5
|
||||
("zai-org/GLM-4.5", "glm45"),
|
||||
("zai-org/GLM-4.5-Air", "glm45"),
|
||||
("zai-org/GLM-4.5V", "glm45"),
|
||||
# GLM-4.7
|
||||
("zai-org/GLM-4.7", "glm47"),
|
||||
("zai-org/GLM-4.7-Flash", "glm47"),
|
||||
# MiniMax
|
||||
("MiniMaxAI/MiniMax-M2", "minimax_m2"),
|
||||
("MiniMaxAI/MiniMax-M2.1", "minimax_m2"),
|
||||
("MiniMaxAI/MiniMax-M2.5", "minimax_m2"),
|
||||
# INTELLECT
|
||||
("PrimeIntellect/INTELLECT-3", "hermes"),
|
||||
("PrimeIntellect/INTELLECT-3-FP8", "hermes"),
|
||||
("PrimeIntellect/INTELLECT-3.1", "hermes"),
|
||||
# Qwen3
|
||||
("Qwen/Qwen3-0.6B", "hermes"),
|
||||
("Qwen/Qwen3-32B", "hermes"),
|
||||
("Qwen/Qwen3-235B-A22B", "hermes"),
|
||||
("Qwen/Qwen3-4B-Instruct-2507", "hermes"),
|
||||
("Qwen/Qwen3-Coder-480B-A35B-Instruct", "hermes"),
|
||||
("Qwen/Qwen3-Next-80B-A3B-Instruct", "hermes"),
|
||||
("Qwen/Qwen3.5-397B-A17B", "hermes"),
|
||||
],
|
||||
)
|
||||
def test_auto_detect_tool_call_parser(model_name: str, expected_parser: str):
|
||||
config = ModelConfig(name=model_name)
|
||||
assert config.tool_call_parser == expected_parser
|
||||
|
||||
|
||||
def test_explicit_parser_overrides_auto_detect():
|
||||
config = ModelConfig(name="Qwen/Qwen3-4B-Instruct-2507", tool_call_parser="qwen3_xml")
|
||||
assert config.tool_call_parser == "qwen3_xml"
|
||||
@@ -3,7 +3,8 @@ revision = 3
|
||||
requires-python = "==3.12.*"
|
||||
resolution-markers = [
|
||||
"sys_platform == 'linux'",
|
||||
"sys_platform != 'linux'",
|
||||
"sys_platform == 'darwin'",
|
||||
"sys_platform != 'darwin' and sys_platform != 'linux'",
|
||||
]
|
||||
|
||||
[options]
|
||||
@@ -242,7 +243,7 @@ name = "build"
|
||||
version = "1.3.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "colorama", marker = "os_name == 'nt' and sys_platform != 'linux'" },
|
||||
{ name = "colorama", marker = "os_name == 'nt' and sys_platform != 'darwin' and sys_platform != 'linux'" },
|
||||
{ name = "packaging" },
|
||||
{ name = "pyproject-hooks" },
|
||||
]
|
||||
@@ -453,7 +454,8 @@ name = "cuda-bindings"
|
||||
version = "13.1.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
resolution-markers = [
|
||||
"sys_platform != 'linux'",
|
||||
"sys_platform == 'darwin'",
|
||||
"sys_platform != 'darwin' and sys_platform != 'linux'",
|
||||
]
|
||||
dependencies = [
|
||||
{ name = "cuda-pathfinder", marker = "sys_platform != 'linux'" },
|
||||
@@ -489,7 +491,8 @@ name = "cuda-python"
|
||||
version = "13.1.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
resolution-markers = [
|
||||
"sys_platform != 'linux'",
|
||||
"sys_platform == 'darwin'",
|
||||
"sys_platform != 'darwin' and sys_platform != 'linux'",
|
||||
]
|
||||
dependencies = [
|
||||
{ name = "cuda-bindings", version = "13.1.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
|
||||
@@ -504,8 +507,8 @@ name = "cupy-cuda12x"
|
||||
version = "13.6.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "fastrlock" },
|
||||
{ name = "numpy" },
|
||||
{ name = "fastrlock", marker = "sys_platform != 'darwin'" },
|
||||
{ name = "numpy", marker = "sys_platform != 'darwin'" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/12/c5/7e7fc4816d0de0154e5d9053242c3a08a0ca8b43ee656a6f7b3b95055a7b/cupy_cuda12x-13.6.0-cp312-cp312-manylinux2014_aarch64.whl", hash = "sha256:a6970ceefe40f9acbede41d7fe17416bd277b1bd2093adcde457b23b578c5a59", size = 127334633, upload-time = "2025-08-18T08:24:43.065Z" },
|
||||
@@ -1588,6 +1591,22 @@ image = [
|
||||
{ name = "opencv-python-headless" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ml-dtypes"
|
||||
version = "0.5.4"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "numpy" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/0e/4a/c27b42ed9b1c7d13d9ba8b6905dece787d6259152f2309338aed29b2447b/ml_dtypes-0.5.4.tar.gz", hash = "sha256:8ab06a50fb9bf9666dd0fe5dfb4676fa2b0ac0f31ecff72a6c3af8e22c063453", size = 692314, upload-time = "2025-11-17T22:32:31.031Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/a8/b8/3c70881695e056f8a32f8b941126cf78775d9a4d7feba8abcb52cb7b04f2/ml_dtypes-0.5.4-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:a174837a64f5b16cab6f368171a1a03a27936b31699d167684073ff1c4237dac", size = 676927, upload-time = "2025-11-17T22:31:48.182Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/54/0f/428ef6881782e5ebb7eca459689448c0394fa0a80bea3aa9262cba5445ea/ml_dtypes-0.5.4-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a7f7c643e8b1320fd958bf098aa7ecf70623a42ec5154e3be3be673f4c34d900", size = 5028464, upload-time = "2025-11-17T22:31:50.135Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/3a/cb/28ce52eb94390dda42599c98ea0204d74799e4d8047a0eb559b6fd648056/ml_dtypes-0.5.4-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9ad459e99793fa6e13bd5b7e6792c8f9190b4e5a1b45c63aba14a4d0a7f1d5ff", size = 5009002, upload-time = "2025-11-17T22:31:52.001Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f5/f0/0cfadd537c5470378b1b32bd859cf2824972174b51b873c9d95cfd7475a5/ml_dtypes-0.5.4-cp312-cp312-win_amd64.whl", hash = "sha256:c1a953995cccb9e25a4ae19e34316671e4e2edaebe4cf538229b1fc7109087b7", size = 212222, upload-time = "2025-11-17T22:31:53.742Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/16/2e/9acc86985bfad8f2c2d30291b27cd2bb4c74cea08695bd540906ed744249/ml_dtypes-0.5.4-cp312-cp312-win_arm64.whl", hash = "sha256:9bad06436568442575beb2d03389aa7456c690a5b05892c471215bfd8cf39460", size = 160793, upload-time = "2025-11-17T22:31:55.358Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mlx"
|
||||
version = "0.29.0"
|
||||
@@ -1606,12 +1625,12 @@ name = "mlx-lm"
|
||||
version = "0.27.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "jinja2", marker = "sys_platform != 'linux'" },
|
||||
{ name = "mlx", marker = "sys_platform != 'linux'" },
|
||||
{ name = "numpy", marker = "sys_platform != 'linux'" },
|
||||
{ name = "protobuf", marker = "sys_platform != 'linux'" },
|
||||
{ name = "pyyaml", marker = "sys_platform != 'linux'" },
|
||||
{ name = "transformers", marker = "sys_platform != 'linux'" },
|
||||
{ name = "jinja2", marker = "sys_platform == 'darwin'" },
|
||||
{ name = "mlx", marker = "sys_platform == 'darwin'" },
|
||||
{ name = "numpy", marker = "sys_platform == 'darwin'" },
|
||||
{ name = "protobuf", marker = "sys_platform == 'darwin'" },
|
||||
{ name = "pyyaml", marker = "sys_platform == 'darwin'" },
|
||||
{ name = "transformers", marker = "sys_platform == 'darwin'" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/41/77/e8d3a82658a2070bc392a583dd08c8d24088433e920eac4905bf882255ad/mlx_lm-0.27.1.tar.gz", hash = "sha256:36640fb64c909cfd9baddf37b16e7d3b94a1a141033e6b7ea7a0ef5a965fb4ae", size = 185170, upload-time = "2025-09-04T16:06:57.949Z" }
|
||||
wheels = [
|
||||
@@ -2310,6 +2329,7 @@ dependencies = [
|
||||
{ name = "rich" },
|
||||
{ name = "ring-flash-attn" },
|
||||
{ name = "tenacity" },
|
||||
{ name = "tilelang" },
|
||||
{ name = "tomli" },
|
||||
{ name = "tomli-w" },
|
||||
{ name = "torch" },
|
||||
@@ -2366,6 +2386,7 @@ requires-dist = [
|
||||
{ name = "rich", specifier = ">=14.0.0" },
|
||||
{ name = "ring-flash-attn", specifier = ">=0.1.8" },
|
||||
{ name = "tenacity", specifier = ">=8.2.0" },
|
||||
{ name = "tilelang", specifier = ">=0.1.8" },
|
||||
{ name = "tomli", specifier = ">=2.2.1" },
|
||||
{ name = "tomli-w", specifier = ">=1.2.0" },
|
||||
{ name = "torch", specifier = ">=2.9.0", index = "https://download.pytorch.org/whl/test/cu128" },
|
||||
@@ -2373,7 +2394,7 @@ requires-dist = [
|
||||
{ name = "torchtitan", git = "https://github.com/pytorch/torchtitan?rev=a1fdd7e" },
|
||||
{ name = "transformers", git = "https://github.com/huggingface/transformers.git?rev=609e3d5" },
|
||||
{ name = "uvloop", specifier = ">=0.21.0" },
|
||||
{ name = "verifiers", git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=013d4da" },
|
||||
{ name = "verifiers", git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=3f555af" },
|
||||
{ name = "vllm", url = "https://github.com/vllm-project/vllm/releases/download/v0.16.0/vllm-0.16.0-cp38-abi3-manylinux_2_31_x86_64.whl" },
|
||||
{ name = "wandb", specifier = ">=0.24.2" },
|
||||
]
|
||||
@@ -3295,6 +3316,30 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/f5/6e/5b71578799b72e5bdcef206a214c3ce860d999d579a3b56e74a6c8989ee2/tiktoken-0.11.0-cp312-cp312-win_amd64.whl", hash = "sha256:45927a71ab6643dfd3ef57d515a5db3d199137adf551f66453be098502838b0f", size = 884282, upload-time = "2025-08-08T23:57:50.759Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tilelang"
|
||||
version = "0.1.8"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "apache-tvm-ffi" },
|
||||
{ name = "cloudpickle" },
|
||||
{ name = "ml-dtypes" },
|
||||
{ name = "numpy" },
|
||||
{ name = "psutil" },
|
||||
{ name = "setuptools", marker = "sys_platform == 'darwin'" },
|
||||
{ name = "torch" },
|
||||
{ name = "torch-c-dlpack-ext" },
|
||||
{ name = "tqdm" },
|
||||
{ name = "typing-extensions" },
|
||||
{ name = "z3-solver" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/e6/27/6e363f48f878389078e2899756b8fecc326388b585122fd7f8a86590dfab/tilelang-0.1.8.tar.gz", hash = "sha256:da967821698eb7a79a76d27fbe25e314a3273f2b12ba4833e981658139d0e6d9", size = 93247335, upload-time = "2026-02-16T14:03:28.706Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/de/17/10ab5c8ccc58783edcc5392ba653f4732702e44a72065224b3d7a4971852/tilelang-0.1.8-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:83654bff38448b6b26e143f150c928360619e91bf431289cf6cd74a4b31c7eba", size = 36016575, upload-time = "2026-02-16T14:02:54.054Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/5d/0b/96ba853aa9e4795020d183e0ca832e9e37d82d4f7f48896241323d1b5ece/tilelang-0.1.8-cp38-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5a4018e581f55c852d98a42d3b4acf2dbcfb8b7d8b9156ba7c6b0ab61600a10c", size = 43477401, upload-time = "2026-02-16T14:03:02.879Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e6/db/d130c8db9140bb21a2ef81a455614a4aeec3388088bf9af5df01ad0ba45d/tilelang-0.1.8-cp38-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:bcc2e28202cde516bdd59e1c25b7f6a139d1c52207d92576f4e711c6217e16ba", size = 40422585, upload-time = "2026-02-16T14:03:12.092Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokenizers"
|
||||
version = "0.22.2"
|
||||
@@ -3527,7 +3572,8 @@ name = "triton"
|
||||
version = "3.3.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
resolution-markers = [
|
||||
"sys_platform != 'linux'",
|
||||
"sys_platform == 'darwin'",
|
||||
"sys_platform != 'darwin' and sys_platform != 'linux'",
|
||||
]
|
||||
dependencies = [
|
||||
{ name = "setuptools", marker = "sys_platform != 'linux'" },
|
||||
@@ -3702,7 +3748,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "verifiers"
|
||||
version = "0.1.11.dev0"
|
||||
source = { git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=013d4da#013d4da8a906bef2e1cbb6b4bc4347214c1fd534" }
|
||||
source = { git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=3f555af#3f555af3674a22ffbfec0cafade25bec51bf517f" }
|
||||
dependencies = [
|
||||
{ name = "anthropic" },
|
||||
{ name = "datasets" },
|
||||
@@ -4096,6 +4142,20 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/b4/2d/2345fce04cfd4bee161bf1e7d9cdc702e3e16109021035dbb24db654a622/yarl-1.20.1-py3-none-any.whl", hash = "sha256:83b8eb083fe4683c6115795d9fc1cfaf2cbbefb19b3a1cb68f6527460f483a77", size = 46542, upload-time = "2025-06-10T00:46:07.521Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "z3-solver"
|
||||
version = "4.15.4.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/8a/8e/0c8f17309549d2e5cde9a3ccefa6365437f1e7bafe71878eaf9478e47b18/z3_solver-4.15.4.0.tar.gz", hash = "sha256:928c29b58c4eb62106da51c1914f6a4a55d0441f8f48a81b9da07950434a8946", size = 5018600, upload-time = "2025-10-29T18:12:03.062Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/63/33/a3d5d2eaeb0f7b3174d57d405437eabb2075d4d50bd9ea0957696c435c7b/z3_solver-4.15.4.0-py3-none-macosx_13_0_arm64.whl", hash = "sha256:407e825cc9211f95ef46bdc8d151bf630e7ab2d62a21d24cd74c09cc5b73f3aa", size = 37052538, upload-time = "2025-10-29T18:11:46.233Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/47/84/fd7ffac1551cd9f8d44fe41358f738be670fc4c24dfd514fab503f2cf3e7/z3_solver-4.15.4.0-py3-none-macosx_13_0_x86_64.whl", hash = "sha256:00bd10c5a6a5f6112d3a9a810d0799227e52f76caa860dafa5e00966bb47eb13", size = 39807925, upload-time = "2025-10-29T18:11:49.81Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/21/c9/bb51a96af0091324c81b803f16c49f719f9f6ea0b0bb52200f5c97ec4892/z3_solver-4.15.4.0-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7e103a6f203f505b8b8b8e5c931cc407c95b61556512d4921c1ddc0b3f41b08e", size = 29268352, upload-time = "2025-10-29T18:11:53.032Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/bf/2e/0b49f7e4e53817cfb09a0f6585012b782dfe0b666e8abefcb4fac0570606/z3_solver-4.15.4.0-py3-none-manylinux_2_34_aarch64.whl", hash = "sha256:62c7e9cbdd711932301f29919ad9158de9b2f58b4d281dd259bbcd0a2f408ba1", size = 27226534, upload-time = "2025-10-29T18:11:55.59Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/26/91/33de49538444d4aafbe47415c450c2f9abab1733e1226f276b496672f46c/z3_solver-4.15.4.0-py3-none-win32.whl", hash = "sha256:be3bc916545c96ffbf89e00d07104ff14f78336e55db069177a1bfbcc01b269d", size = 13191672, upload-time = "2025-10-29T18:11:58.424Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/03/d6/a0b135e4419df475177ae78fc93c422430b0fd8875649486f9a5989772e6/z3_solver-4.15.4.0-py3-none-win_amd64.whl", hash = "sha256:00e35b02632ed085ea8199fb230f6015e6fc40554a6680c097bd5f060e827431", size = 16259597, upload-time = "2025-10-29T18:12:01.14Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zipp"
|
||||
version = "3.23.0"
|
||||
|
||||
Reference in New Issue
Block a user