Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7c40b334e6 | ||
|
|
aaeb711501 | ||
|
|
6c8faec459 | ||
|
|
95a53f39e7 | ||
|
|
0756df77c1 | ||
|
|
66b1f4b6b7 | ||
|
|
bb5e48292d | ||
|
|
187b7a438c | ||
|
|
1b725b84b8 |
+2
-1
@@ -56,6 +56,7 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
|
||||
- **`EvalSaveDiskConfig`**, **`EvalSaveConfig`**, **`RetryConfig`**, **`OnlineEvalConfig`**: Removed (2026-02-06)
|
||||
- **`TemperatureScheduleConfig`**: Renamed to `TemperatureSchedulerConfig` (2026-02-06)
|
||||
- **`optim.mu`**: Added Muon momentum (`mu`) config field (default: 0.95). Previously hardcoded to Muon class default. Also fixed `optim.betas1`/`optim.betas2` not being passed through to the Muon optimizer (2026-02-09)
|
||||
- **`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
|
||||
- **`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.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)
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
inference_gpu_ids = [0]
|
||||
trainer_gpu_ids = [1]
|
||||
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt]
|
||||
|
||||
[model]
|
||||
name = "samsja/mini-glm-moe"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 128
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.7
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 2048
|
||||
@@ -27,7 +27,7 @@ spec:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
containers:
|
||||
- name: prime-rl
|
||||
- name: prime-rl-orchestrator
|
||||
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
|
||||
imagePullPolicy: {{ .Values.image.pullPolicy }}
|
||||
{{- if .Values.orchestrator.autoStart }}
|
||||
@@ -133,7 +133,7 @@ spec:
|
||||
runtimeClassName: {{ .Values.inference.runtimeClassName }}
|
||||
{{- end }}
|
||||
containers:
|
||||
- name: prime-rl
|
||||
- name: prime-rl-inference
|
||||
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
|
||||
imagePullPolicy: {{ .Values.image.pullPolicy }}
|
||||
{{- if .Values.inference.autoStart }}
|
||||
@@ -262,7 +262,7 @@ spec:
|
||||
runtimeClassName: {{ .Values.trainer.runtimeClassName }}
|
||||
{{- end }}
|
||||
containers:
|
||||
- name: prime-rl
|
||||
- name: prime-rl-trainer
|
||||
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
|
||||
imagePullPolicy: {{ .Values.image.pullPolicy }}
|
||||
{{- if .Values.trainer.autoStart }}
|
||||
|
||||
+2
-2
@@ -45,7 +45,7 @@ sft = "prime_rl.trainer.sft.train:main"
|
||||
|
||||
[project.optional-dependencies]
|
||||
flash-attn = [
|
||||
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.16/flash_attn-2.6.3%2Bcu128torch2.10-cp312-cp312-linux_x86_64.whl",
|
||||
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.16/flash_attn-2.8.3%2Bcu128torch2.10-cp312-cp312-linux_x86_64.whl",
|
||||
]
|
||||
flash-attn-3 = [
|
||||
"flash_attn_3 @ https://github.com/samsja/flash-attn-builds/releases/download/v0.1/flash_attn_3-3.0.0b1-cp39-abi3-linux_x86_64.whl",
|
||||
@@ -77,7 +77,7 @@ override-dependencies = [
|
||||
|
||||
[tool.uv.sources]
|
||||
torch = { index = "pytorch-cu128" }
|
||||
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "786d300" }
|
||||
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "ad77074" }
|
||||
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" }
|
||||
|
||||
+61
-9
@@ -15,12 +15,14 @@ import argparse
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
from transformers import AutoConfig, AutoTokenizer
|
||||
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
|
||||
from transformers import Glm4MoeForCausalLM as HFGlm4MoeForCausalLM
|
||||
|
||||
from prime_rl.trainer.models.glm4_moe import Glm4MoeConfig
|
||||
from prime_rl.trainer.models.glm4_moe import Glm4MoeForCausalLM as PrimeRLGlm4MoeForCausalLM
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2Config
|
||||
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2ForCausalLM as PrimeRLMiniMaxM2ForCausalLM
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.utils import default_dtype
|
||||
|
||||
@@ -57,21 +59,70 @@ ARCH_PRESETS = {
|
||||
"prime_model_class": PrimeRLGlm4MoeForCausalLM,
|
||||
"tokenizer_source": "THUDM/GLM-4-9B-0414",
|
||||
},
|
||||
"minimax_m2": {
|
||||
"config_class": MiniMaxM2Config,
|
||||
"config_kwargs": dict(
|
||||
vocab_size=200064,
|
||||
hidden_size=512,
|
||||
intermediate_size=256,
|
||||
num_hidden_layers=12,
|
||||
num_attention_heads=8,
|
||||
num_key_value_heads=4,
|
||||
head_dim=64,
|
||||
hidden_act="silu",
|
||||
max_position_embeddings=4096,
|
||||
rms_norm_eps=1e-6,
|
||||
rope_theta=5000000,
|
||||
rotary_dim=32,
|
||||
num_local_experts=8,
|
||||
num_experts_per_tok=4,
|
||||
scoring_func="sigmoid",
|
||||
use_routing_bias=True,
|
||||
use_qk_norm=True,
|
||||
qk_norm_type="per_layer",
|
||||
use_grouped_mm=False,
|
||||
auto_map={"AutoModelForCausalLM": "MiniMaxAI/MiniMax-M2.1--modeling_minimax_m2.MiniMaxM2ForCausalLM"},
|
||||
),
|
||||
"hf_model_class": None, # uses AutoModelForCausalLM with trust_remote_code
|
||||
"prime_model_class": PrimeRLMiniMaxM2ForCausalLM,
|
||||
"tokenizer_source": "MiniMaxAI/MiniMax-M2.1",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _create_hf_model(preset, config):
|
||||
"""Create an HF model from a preset and config."""
|
||||
hf_cls = preset["hf_model_class"]
|
||||
if hf_cls is not None:
|
||||
return hf_cls(config)
|
||||
return AutoModelForCausalLM.from_config(config, trust_remote_code=True)
|
||||
|
||||
|
||||
def _load_hf_model(preset, model_dir, config):
|
||||
"""Load an HF model from a preset and directory."""
|
||||
hf_cls = preset["hf_model_class"]
|
||||
if hf_cls is not None:
|
||||
return hf_cls.from_pretrained(str(model_dir), config=config)
|
||||
return AutoModelForCausalLM.from_pretrained(str(model_dir), config=config, trust_remote_code=True)
|
||||
|
||||
|
||||
def _create_hf_model_from_config(preset, config):
|
||||
"""Create an empty HF model from config (for roundtrip verification)."""
|
||||
hf_cls = preset["hf_model_class"]
|
||||
if hf_cls is not None:
|
||||
return hf_cls._from_config(config)
|
||||
return AutoModelForCausalLM.from_config(config, trust_remote_code=True)
|
||||
|
||||
|
||||
def create(arch: str, output_dir: Path) -> None:
|
||||
preset = ARCH_PRESETS[arch]
|
||||
config = preset["config_class"](**preset["config_kwargs"])
|
||||
|
||||
print(f"Creating mini {arch} model...")
|
||||
print(
|
||||
f" hidden_size={config.hidden_size}, layers={config.num_hidden_layers}, "
|
||||
f"experts={config.n_routed_experts}, moe_intermediate_size={config.moe_intermediate_size}"
|
||||
)
|
||||
print(f" hidden_size={config.hidden_size}, layers={config.num_hidden_layers}")
|
||||
|
||||
with torch.device("cpu"):
|
||||
model = preset["hf_model_class"](config)
|
||||
model = _create_hf_model(preset, config)
|
||||
|
||||
param_count = sum(p.numel() for p in model.parameters())
|
||||
print(f" Parameters: {param_count / 1e6:.1f}M")
|
||||
@@ -89,11 +140,12 @@ def verify(arch: str, model_dir: Path) -> None:
|
||||
preset = ARCH_PRESETS[arch]
|
||||
print(f"Verifying HF <-> PrimeRL roundtrip for {model_dir}...")
|
||||
|
||||
config = AutoConfig.from_pretrained(str(model_dir))
|
||||
trust_remote_code = preset["hf_model_class"] is None
|
||||
config = AutoConfig.from_pretrained(str(model_dir), trust_remote_code=trust_remote_code)
|
||||
config._attn_implementation = "sdpa"
|
||||
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
hf_model = preset["hf_model_class"].from_pretrained(str(model_dir), config=config)
|
||||
hf_model = _load_hf_model(preset, model_dir, config)
|
||||
prime_model = preset["prime_model_class"]._from_config(config)
|
||||
|
||||
with torch.no_grad():
|
||||
@@ -118,7 +170,7 @@ def verify(arch: str, model_dir: Path) -> None:
|
||||
with torch.no_grad():
|
||||
roundtrip_state_dict = prime_model.convert_to_hf(prime_model.state_dict())
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
hf_roundtrip = preset["hf_model_class"]._from_config(config)
|
||||
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)
|
||||
|
||||
@@ -376,6 +376,13 @@ class EvalConfig(BaseConfig):
|
||||
),
|
||||
] = True
|
||||
|
||||
cancel_inflight_rollouts_on_eval: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to cancel in-flight training rollouts before starting online evals. This is useful to avoid congestion (e.g. do not have training + eval rollouts happening at the same time) but leads to slower training steps as rollouts get cancelled and the pipeline has to fill up after each eval",
|
||||
),
|
||||
] = False
|
||||
|
||||
|
||||
class CheckpointConfig(BaseConfig):
|
||||
"""Configures checkpointing the orchestrator."""
|
||||
|
||||
@@ -41,7 +41,6 @@ from prime_rl.orchestrator.utils import (
|
||||
from prime_rl.orchestrator.vf_utils import (
|
||||
generate,
|
||||
get_completion_len,
|
||||
get_prompt_len,
|
||||
get_seq_len,
|
||||
setup_env_client,
|
||||
spawn_env_server,
|
||||
@@ -382,10 +381,15 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
last_eval_step = ckpt_step
|
||||
logger.info(f"Running evals for checkpoint step {ckpt_step}")
|
||||
|
||||
# Pause weight updates during eval and cancel inflight rollouts
|
||||
# this avoid doing eval across different checkpoints and avoid congestion
|
||||
# Pause weight updates and re-scheduling of training rollouts during eval
|
||||
# to avoid evaluating across different checkpoints and avoid congestion
|
||||
scheduler.checkpoint_ready.clear()
|
||||
scheduler.cancel_all_inflight_rollouts()
|
||||
|
||||
# For heavy eval workloads, it might be necessary additionally cancel in-flight training rollouts
|
||||
if config.eval.cancel_inflight_rollouts_on_eval:
|
||||
logger.info("Cancelling in-flight training rollouts before starting evals to avoid congestion.")
|
||||
scheduler.cancel_inflight_rollouts()
|
||||
|
||||
results = await asyncio.gather(
|
||||
*[
|
||||
evaluate_env(
|
||||
@@ -473,12 +477,26 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
|
||||
# Collect results and assign advantages
|
||||
train_examples: list[TrainingSample] = []
|
||||
rollout_prefill_lens: list[int] = []
|
||||
rollout_decode_lens: 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:
|
||||
for sample in samples:
|
||||
sample.advantage = advantage
|
||||
sample.reward = rollout["reward"]
|
||||
train_examples.extend(samples)
|
||||
sample_decode_tokens = sum(sample.completion_mask)
|
||||
sample_prefill_tokens = len(sample.prompt_ids) + len(sample.completion_mask) - sample_decode_tokens
|
||||
rollout_decode_tokens += sample_decode_tokens
|
||||
rollout_prefill_tokens += sample_prefill_tokens
|
||||
train_examples.append(sample)
|
||||
rollout_prefill_lens.append(rollout_prefill_tokens)
|
||||
rollout_decode_lens.append(rollout_decode_tokens)
|
||||
num_prefill_tokens += rollout_prefill_tokens
|
||||
num_decode_tokens += rollout_decode_tokens
|
||||
|
||||
parallel_preprocess_time = time.perf_counter() - parallel_preprocess_start
|
||||
logger.debug(
|
||||
@@ -539,9 +557,9 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
"reward": [rollout["reward"] for rollout in train_rollouts],
|
||||
"is_truncated": [rollout["is_truncated"] for rollout in train_rollouts],
|
||||
"error": [rollout["error"] for rollout in train_rollouts],
|
||||
"completion_len": [get_completion_len(rollout) for rollout in train_rollouts],
|
||||
"prompt_len": [get_prompt_len(rollout) for rollout in train_rollouts],
|
||||
"seq_len": [get_seq_len(rollout) for rollout in train_rollouts],
|
||||
"prefill_len": rollout_prefill_lens,
|
||||
"decode_len": rollout_decode_lens,
|
||||
"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],
|
||||
@@ -598,6 +616,8 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
to_log = {
|
||||
# Progress metrics
|
||||
"progress/tokens": num_tokens,
|
||||
"progress/prefill_tokens": num_prefill_tokens,
|
||||
"progress/decode_tokens": num_decode_tokens,
|
||||
"progress/samples": config.batch_size,
|
||||
"progress/problems": config.batch_size // config.rollouts_per_example,
|
||||
"progress/total_tokens": progress.total_tokens,
|
||||
@@ -608,12 +628,12 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
"seq_len/mean": results_df.groupby("example_id").seq_len.mean().mean(),
|
||||
"seq_len/max": results_df.groupby("example_id").seq_len.mean().max(),
|
||||
"seq_len/min": results_df.groupby("example_id").seq_len.mean().min(),
|
||||
"prompt_len/mean": results_df.groupby("example_id").prompt_len.mean().mean(),
|
||||
"prompt_len/max": results_df.groupby("example_id").prompt_len.mean().max(),
|
||||
"prompt_len/min": results_df.groupby("example_id").prompt_len.mean().min(),
|
||||
"completion_len/mean": results_df.groupby("example_id").completion_len.mean().mean(),
|
||||
"completion_len/max": results_df.groupby("example_id").completion_len.mean().max(),
|
||||
"completion_len/min": results_df.groupby("example_id").completion_len.mean().min(),
|
||||
"prefill_len/mean": results_df.groupby("example_id").prefill_len.mean().mean(),
|
||||
"prefill_len/max": results_df.groupby("example_id").prefill_len.mean().max(),
|
||||
"prefill_len/min": results_df.groupby("example_id").prefill_len.mean().min(),
|
||||
"decode_len/mean": results_df.groupby("example_id").decode_len.mean().mean(),
|
||||
"decode_len/max": results_df.groupby("example_id").decode_len.mean().max(),
|
||||
"decode_len/min": results_df.groupby("example_id").decode_len.mean().min(),
|
||||
"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(),
|
||||
@@ -732,6 +752,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
sampling_args=eval_sampling_args,
|
||||
num_examples=eval_env_config.num_examples or config.eval.num_examples,
|
||||
rollouts_per_example=eval_env_config.rollouts_per_example or config.eval.rollouts_per_example,
|
||||
max_retries=eval_env_config.max_retries,
|
||||
ckpt_step=ckpt_step,
|
||||
step=progress.step,
|
||||
)
|
||||
@@ -755,7 +776,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
rollout_executor.shutdown(wait=False)
|
||||
|
||||
# Stop scheduler
|
||||
scheduler.cancel_all_inflight_rollouts()
|
||||
scheduler.cancel_inflight_rollouts()
|
||||
update_policy_task.cancel()
|
||||
|
||||
# Stop inference pool
|
||||
|
||||
@@ -95,11 +95,8 @@ class Scheduler:
|
||||
"""Update sampling args for future rollout requests."""
|
||||
self.sampling_args = sampling_args
|
||||
|
||||
def cancel_all_inflight_rollouts(self):
|
||||
"""Cancel all in-flight rollout requests.
|
||||
|
||||
Used when weights are updated to discard stale rollouts generated with old weights.
|
||||
"""
|
||||
def cancel_inflight_rollouts(self):
|
||||
"""Cancel all in-flight rollout requests."""
|
||||
count = len(self.inflight_group_rollouts)
|
||||
for future in list(self.inflight_group_rollouts.keys()):
|
||||
if not future.done():
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import multiprocessing as mp
|
||||
from collections.abc import Awaitable, Callable
|
||||
from itertools import cycle
|
||||
from multiprocessing import Process
|
||||
from typing import Any
|
||||
|
||||
import verifiers as vf
|
||||
@@ -33,7 +33,10 @@ def spawn_env_server(
|
||||
Mirrors vf.Environment.start_server().
|
||||
"""
|
||||
address = address or f"tcp://127.0.0.1:{get_free_port()}"
|
||||
Process(
|
||||
# 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(
|
||||
target=ZMQEnvServer.run_server,
|
||||
args=(
|
||||
env_id,
|
||||
|
||||
@@ -13,17 +13,20 @@ from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.glm4_moe import Glm4MoeConfig, Glm4MoeForCausalLM
|
||||
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
|
||||
from prime_rl.trainer.models.qwen3_moe import Qwen3MoeConfig, Qwen3MoeForCausalLM
|
||||
|
||||
# Make custom config discoverable by AutoConfig
|
||||
AutoConfig.register("afmoe", AfmoeConfig, exist_ok=True)
|
||||
AutoConfig.register("glm4_moe", Glm4MoeConfig, exist_ok=True)
|
||||
AutoConfig.register("minimax_m2", MiniMaxM2Config, exist_ok=True)
|
||||
AutoConfig.register("qwen3_moe", Qwen3MoeConfig, exist_ok=True)
|
||||
|
||||
_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(MiniMaxM2Config, MiniMaxM2ForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(Qwen3MoeConfig, Qwen3MoeForCausalLM, exist_ok=True)
|
||||
|
||||
|
||||
|
||||
@@ -132,19 +132,16 @@ def convert_tt_layer_to_hf(state_dict: dict[str, Tensor], layer_index: int):
|
||||
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 new fused format (transformers 5.0+)
|
||||
w1 = state_dict[f"model.layers.{i}.mlp.experts.w1"] # (num_experts, moe_dim, dim)
|
||||
w2 = state_dict[f"model.layers.{i}.mlp.experts.w2"] # (num_experts, dim, moe_dim)
|
||||
w3 = state_dict[f"model.layers.{i}.mlp.experts.w3"] # (num_experts, moe_dim, dim)
|
||||
# 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)
|
||||
|
||||
# Fuse w1 (gate) and w3 (up) into gate_up_proj
|
||||
gate_up_proj = torch.cat([w1, w3], dim=1) # (num_experts, 2*moe_dim, dim)
|
||||
state_dict[f"model.layers.{i}.mlp.experts.gate_up_proj"] = gate_up_proj
|
||||
state_dict[f"model.layers.{i}.mlp.experts.down_proj"] = w2
|
||||
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.w1"]
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.w2"]
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.w3"]
|
||||
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]):
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import functools
|
||||
from dataclasses import dataclass
|
||||
from typing import Literal
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
@@ -36,6 +37,7 @@ class AttentionConfig:
|
||||
attention_bias: bool
|
||||
use_qk_norm: bool
|
||||
rms_norm_eps: float
|
||||
qk_norm_type: Literal["per_head", "per_layer"] = "per_head"
|
||||
|
||||
|
||||
# TODO: Does torch compile support config._attn_implementation forking?
|
||||
@@ -70,9 +72,18 @@ class FlashAttention(nn.Module):
|
||||
)
|
||||
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
|
||||
self.use_qk_norm = config.use_qk_norm
|
||||
self.qk_norm_type = config.qk_norm_type
|
||||
if self.use_qk_norm:
|
||||
self.q_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
|
||||
self.k_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
|
||||
if self.qk_norm_type == "per_layer":
|
||||
self.q_norm = RMSNorm(
|
||||
RMSNormConfig(hidden_size=config.num_attention_heads * self.head_dim, eps=config.rms_norm_eps)
|
||||
)
|
||||
self.k_norm = RMSNorm(
|
||||
RMSNormConfig(hidden_size=config.num_key_value_heads * self.head_dim, eps=config.rms_norm_eps)
|
||||
)
|
||||
else:
|
||||
self.q_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
|
||||
self.k_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
|
||||
|
||||
self._flash_attn_version = flash_attn_version
|
||||
self.func = self._funcs[flash_attn_version]
|
||||
@@ -90,11 +101,19 @@ class FlashAttention(nn.Module):
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
hidden_shape = (*input_shape, -1, self.head_dim)
|
||||
|
||||
query_states = self.q_proj(hidden_states).view(hidden_shape)
|
||||
key_states = self.k_proj(hidden_states).view(hidden_shape)
|
||||
value_states = self.v_proj(hidden_states).view(hidden_shape)
|
||||
query_states = self.q_proj(hidden_states)
|
||||
key_states = self.k_proj(hidden_states)
|
||||
value_states = self.v_proj(hidden_states)
|
||||
|
||||
if self.use_qk_norm: # main diff from Llama
|
||||
if self.use_qk_norm and self.qk_norm_type == "per_layer":
|
||||
query_states = self.q_norm(query_states)
|
||||
key_states = self.k_norm(key_states)
|
||||
|
||||
query_states = query_states.view(hidden_shape)
|
||||
key_states = key_states.view(hidden_shape)
|
||||
value_states = value_states.view(hidden_shape)
|
||||
|
||||
if self.use_qk_norm and self.qk_norm_type == "per_head":
|
||||
query_states = self.q_norm(query_states)
|
||||
key_states = self.k_norm(key_states)
|
||||
|
||||
@@ -156,9 +175,18 @@ class SDPAAttention(nn.Module):
|
||||
)
|
||||
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
|
||||
self.use_qk_norm = config.use_qk_norm
|
||||
self.qk_norm_type = config.qk_norm_type
|
||||
if self.use_qk_norm:
|
||||
self.q_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
|
||||
self.k_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
|
||||
if self.qk_norm_type == "per_layer":
|
||||
self.q_norm = RMSNorm(
|
||||
RMSNormConfig(hidden_size=config.num_attention_heads * self.head_dim, eps=config.rms_norm_eps)
|
||||
)
|
||||
self.k_norm = RMSNorm(
|
||||
RMSNormConfig(hidden_size=config.num_key_value_heads * self.head_dim, eps=config.rms_norm_eps)
|
||||
)
|
||||
else:
|
||||
self.q_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
|
||||
self.k_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
|
||||
|
||||
def forward(
|
||||
self,
|
||||
@@ -170,11 +198,19 @@ class SDPAAttention(nn.Module):
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
hidden_shape = (*input_shape, -1, self.head_dim)
|
||||
|
||||
query_states: torch.Tensor = self.q_proj(hidden_states).view(hidden_shape)
|
||||
key_states: torch.Tensor = self.k_proj(hidden_states).view(hidden_shape)
|
||||
value_states: torch.Tensor = self.v_proj(hidden_states).view(hidden_shape)
|
||||
query_states: torch.Tensor = self.q_proj(hidden_states)
|
||||
key_states: torch.Tensor = self.k_proj(hidden_states)
|
||||
value_states: torch.Tensor = self.v_proj(hidden_states)
|
||||
|
||||
if self.use_qk_norm: # main diff from Llama
|
||||
if self.use_qk_norm and self.qk_norm_type == "per_layer":
|
||||
query_states = self.q_norm(query_states)
|
||||
key_states = self.k_norm(key_states)
|
||||
|
||||
query_states = query_states.view(hidden_shape)
|
||||
key_states = key_states.view(hidden_shape)
|
||||
value_states = value_states.view(hidden_shape)
|
||||
|
||||
if self.use_qk_norm and self.qk_norm_type == "per_head":
|
||||
query_states = self.q_norm(query_states)
|
||||
key_states = self.k_norm(key_states)
|
||||
|
||||
@@ -229,11 +265,19 @@ def substitute_prime_rl_flash_attn(
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
hidden_shape = (*input_shape, -1, self.head_dim)
|
||||
|
||||
query_states = self.q_proj(hidden_states).view(hidden_shape)
|
||||
key_states = self.k_proj(hidden_states).view(hidden_shape)
|
||||
value_states = self.v_proj(hidden_states).view(hidden_shape)
|
||||
query_states = self.q_proj(hidden_states)
|
||||
key_states = self.k_proj(hidden_states)
|
||||
value_states = self.v_proj(hidden_states)
|
||||
|
||||
if self.use_qk_norm: # main diff from Llama
|
||||
if self.use_qk_norm and self.qk_norm_type == "per_layer":
|
||||
query_states = self.q_norm(query_states)
|
||||
key_states = self.k_norm(key_states)
|
||||
|
||||
query_states = query_states.view(hidden_shape)
|
||||
key_states = key_states.view(hidden_shape)
|
||||
value_states = value_states.view(hidden_shape)
|
||||
|
||||
if self.use_qk_norm and self.qk_norm_type == "per_head":
|
||||
query_states = self.q_norm(query_states)
|
||||
key_states = self.k_norm(key_states)
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
from prime_rl.trainer.models.minimax_m2.configuration_minimax_m2 import MiniMaxM2Config
|
||||
from prime_rl.trainer.models.minimax_m2.modeling_minimax_m2 import (
|
||||
MiniMaxM2ForCausalLM,
|
||||
MiniMaxM2Model,
|
||||
MiniMaxM2PreTrainedModel,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"MiniMaxM2Config",
|
||||
"MiniMaxM2ForCausalLM",
|
||||
"MiniMaxM2Model",
|
||||
"MiniMaxM2PreTrainedModel",
|
||||
]
|
||||
@@ -0,0 +1,151 @@
|
||||
from transformers.configuration_utils import PretrainedConfig
|
||||
from transformers.modeling_rope_utils import rope_config_validation
|
||||
|
||||
|
||||
class MiniMaxM2Config(PretrainedConfig):
|
||||
r"""
|
||||
Configuration class for MiniMax M2.1 MoE model.
|
||||
|
||||
Args:
|
||||
vocab_size (`int`, *optional*, defaults to 200064):
|
||||
Vocabulary size of the model.
|
||||
hidden_size (`int`, *optional*, defaults to 6144):
|
||||
Dimension of the hidden representations.
|
||||
intermediate_size (`int`, *optional*, defaults to 24576):
|
||||
Dimension of the MoE expert FFN.
|
||||
num_hidden_layers (`int`, *optional*, defaults to 92):
|
||||
Number of hidden layers in the Transformer.
|
||||
num_attention_heads (`int`, *optional*, defaults to 48):
|
||||
Number of attention heads.
|
||||
num_key_value_heads (`int`, *optional*, defaults to 8):
|
||||
Number of key-value heads for GQA.
|
||||
head_dim (`int`, *optional*, defaults to 128):
|
||||
Dimension of each attention head.
|
||||
hidden_act (`str`, *optional*, defaults to `"silu"`):
|
||||
Activation function for the MLP.
|
||||
max_position_embeddings (`int`, *optional*, defaults to 131072):
|
||||
Maximum sequence length.
|
||||
rms_norm_eps (`float`, *optional*, defaults to 1e-6):
|
||||
Epsilon for RMS normalization.
|
||||
rope_theta (`float`, *optional*, defaults to 5000000):
|
||||
Base period for RoPE.
|
||||
rotary_dim (`int`, *optional*, defaults to 64):
|
||||
Dimension of the rotary embeddings. Converted to `partial_rotary_factor` for HF rope init.
|
||||
num_local_experts (`int`, *optional*, defaults to 256):
|
||||
Number of routed experts per layer.
|
||||
num_experts_per_tok (`int`, *optional*, defaults to 8):
|
||||
Number of experts selected per token.
|
||||
scoring_func (`str`, *optional*, defaults to `"sigmoid"`):
|
||||
Scoring function for the router.
|
||||
use_routing_bias (`bool`, *optional*, defaults to `True`):
|
||||
Whether to use e_score_correction_bias for load balancing.
|
||||
use_qk_norm (`bool`, *optional*, defaults to `True`):
|
||||
Whether to use QK normalization.
|
||||
qk_norm_type (`str`, *optional*, defaults to `"per_layer"`):
|
||||
Type of QK normalization. "per_layer" means each head has its own scale.
|
||||
attention_bias (`bool`, *optional*, defaults to `False`):
|
||||
Whether to use bias in attention projections.
|
||||
use_grouped_mm (`bool`, *optional*, defaults to `True`):
|
||||
Whether to use grouped matmul for experts.
|
||||
"""
|
||||
|
||||
model_type = "minimax_m2"
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
|
||||
base_model_tp_plan = {
|
||||
"layers.*.self_attn.q_proj": "colwise",
|
||||
"layers.*.self_attn.k_proj": "colwise",
|
||||
"layers.*.self_attn.v_proj": "colwise",
|
||||
"layers.*.self_attn.o_proj": "rowwise",
|
||||
}
|
||||
base_model_pp_plan = {
|
||||
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
||||
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
|
||||
"norm": (["hidden_states"], ["hidden_states"]),
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vocab_size=200064,
|
||||
hidden_size=6144,
|
||||
intermediate_size=24576,
|
||||
num_hidden_layers=92,
|
||||
num_attention_heads=48,
|
||||
num_key_value_heads=8,
|
||||
head_dim=128,
|
||||
hidden_act="silu",
|
||||
max_position_embeddings=131072,
|
||||
initializer_range=0.02,
|
||||
rms_norm_eps=1e-6,
|
||||
use_cache=True,
|
||||
tie_word_embeddings=False,
|
||||
rope_theta=5000000,
|
||||
rope_scaling=None,
|
||||
rotary_dim=64,
|
||||
pad_token_id=None,
|
||||
bos_token_id=1,
|
||||
eos_token_id=2,
|
||||
num_local_experts=256,
|
||||
num_experts_per_tok=8,
|
||||
scoring_func="sigmoid",
|
||||
use_routing_bias=True,
|
||||
use_qk_norm=True,
|
||||
qk_norm_type="per_layer",
|
||||
attention_bias=False,
|
||||
sliding_window=None,
|
||||
attention_dropout=0.0,
|
||||
output_router_logits=False,
|
||||
router_aux_loss_coef=0.001,
|
||||
router_jitter_noise=0.0,
|
||||
use_grouped_mm=True,
|
||||
**kwargs,
|
||||
):
|
||||
self.vocab_size = vocab_size
|
||||
self.hidden_size = hidden_size
|
||||
self.intermediate_size = intermediate_size
|
||||
self.num_hidden_layers = num_hidden_layers
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.num_key_value_heads = num_key_value_heads
|
||||
self.head_dim = head_dim
|
||||
self.hidden_act = hidden_act
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
self.initializer_range = initializer_range
|
||||
self.rms_norm_eps = rms_norm_eps
|
||||
self.use_cache = use_cache
|
||||
self.rope_theta = rope_theta
|
||||
self.rope_scaling = rope_scaling
|
||||
self.attention_bias = attention_bias
|
||||
self.sliding_window = sliding_window
|
||||
self.attention_dropout = attention_dropout
|
||||
|
||||
# Compute partial_rotary_factor from rotary_dim for HF rope init compatibility
|
||||
self.rotary_dim = rotary_dim
|
||||
self.partial_rotary_factor = rotary_dim / head_dim
|
||||
|
||||
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
||||
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
||||
rope_config_validation(self)
|
||||
|
||||
# MoE arguments
|
||||
self.num_local_experts = num_local_experts
|
||||
self.num_experts_per_tok = num_experts_per_tok
|
||||
self.scoring_func = scoring_func
|
||||
self.use_routing_bias = use_routing_bias
|
||||
self.output_router_logits = output_router_logits
|
||||
self.router_aux_loss_coef = router_aux_loss_coef
|
||||
self.router_jitter_noise = router_jitter_noise
|
||||
|
||||
# Attention
|
||||
self.use_qk_norm = use_qk_norm
|
||||
self.qk_norm_type = qk_norm_type
|
||||
|
||||
# Training
|
||||
self.use_grouped_mm = use_grouped_mm
|
||||
|
||||
super().__init__(
|
||||
pad_token_id=pad_token_id,
|
||||
bos_token_id=bos_token_id,
|
||||
eos_token_id=eos_token_id,
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
**kwargs,
|
||||
)
|
||||
@@ -0,0 +1,101 @@
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
|
||||
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
|
||||
"""Get the maximum number of layers in the model."""
|
||||
return max(int(i.split(".")[2]) for i in state_dict.keys() if "model.layers." in i) + 1
|
||||
|
||||
|
||||
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int):
|
||||
"""Convert a layer from HF to PrimeRL format in-place.
|
||||
|
||||
HF MiniMax M2.1 uses `block_sparse_moe` as the MoE block name, with
|
||||
expert weights stored as `experts.{j}.w1.weight` (nn.Linear format).
|
||||
"""
|
||||
i = layer_idx
|
||||
prefix = f"model.layers.{i}"
|
||||
|
||||
# Check if this layer has MoE experts
|
||||
num_experts = len([k for k in state_dict.keys() if f"{prefix}.block_sparse_moe.experts" in k]) // 3
|
||||
if num_experts == 0:
|
||||
return
|
||||
|
||||
# Router: block_sparse_moe.gate.weight -> mlp.router.gate.weight
|
||||
state_dict[f"{prefix}.mlp.router.gate.weight"] = state_dict[f"{prefix}.block_sparse_moe.gate.weight"]
|
||||
del state_dict[f"{prefix}.block_sparse_moe.gate.weight"]
|
||||
|
||||
# e_score_correction_bias: direct tensor under block_sparse_moe -> mlp.expert_bias
|
||||
bias_key = f"{prefix}.block_sparse_moe.e_score_correction_bias"
|
||||
if bias_key in state_dict:
|
||||
state_dict[f"{prefix}.mlp.expert_bias"] = state_dict[bias_key]
|
||||
del state_dict[bias_key]
|
||||
|
||||
# Expert weights: stack individual experts into grouped tensors
|
||||
# HF uses w1.weight, w2.weight, w3.weight (nn.Linear with .weight suffix)
|
||||
dim, moe_dim = state_dict[f"{prefix}.block_sparse_moe.experts.0.w2.weight"].shape
|
||||
dtype = state_dict[f"{prefix}.block_sparse_moe.experts.0.w2.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"{prefix}.block_sparse_moe.experts.{j}.w1.weight"])
|
||||
w2[j].copy_(state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w2.weight"])
|
||||
w3[j].copy_(state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w3.weight"])
|
||||
|
||||
del state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w1.weight"]
|
||||
del state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w2.weight"]
|
||||
del state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w3.weight"]
|
||||
|
||||
state_dict[f"{prefix}.mlp.experts.w1"] = w1
|
||||
state_dict[f"{prefix}.mlp.experts.w2"] = w2
|
||||
state_dict[f"{prefix}.mlp.experts.w3"] = w3
|
||||
|
||||
|
||||
def convert_tt_layer_to_hf(state_dict: dict[str, Tensor], layer_idx: int):
|
||||
"""Convert a layer from PrimeRL to HF format in-place."""
|
||||
i = layer_idx
|
||||
prefix = f"model.layers.{i}"
|
||||
|
||||
if f"{prefix}.mlp.router.gate.weight" not in state_dict:
|
||||
return
|
||||
|
||||
# Router: mlp.router.gate.weight -> block_sparse_moe.gate.weight
|
||||
state_dict[f"{prefix}.block_sparse_moe.gate.weight"] = state_dict[f"{prefix}.mlp.router.gate.weight"]
|
||||
del state_dict[f"{prefix}.mlp.router.gate.weight"]
|
||||
|
||||
# expert_bias -> block_sparse_moe.e_score_correction_bias
|
||||
if f"{prefix}.mlp.expert_bias" in state_dict:
|
||||
state_dict[f"{prefix}.block_sparse_moe.e_score_correction_bias"] = state_dict[f"{prefix}.mlp.expert_bias"]
|
||||
del state_dict[f"{prefix}.mlp.expert_bias"]
|
||||
|
||||
# tokens_per_expert is a runtime buffer, remove if present
|
||||
if f"{prefix}.mlp.tokens_per_expert" in state_dict:
|
||||
del state_dict[f"{prefix}.mlp.tokens_per_expert"]
|
||||
|
||||
# Expert weights: unstack grouped tensors into individual experts
|
||||
num_experts, moe_dim, dim = state_dict[f"{prefix}.mlp.experts.w1"].shape
|
||||
for j in range(num_experts):
|
||||
state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w1.weight"] = state_dict[f"{prefix}.mlp.experts.w1"][j]
|
||||
state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w2.weight"] = state_dict[f"{prefix}.mlp.experts.w2"][j]
|
||||
state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w3.weight"] = state_dict[f"{prefix}.mlp.experts.w3"][j]
|
||||
|
||||
del state_dict[f"{prefix}.mlp.experts.w1"]
|
||||
del state_dict[f"{prefix}.mlp.experts.w2"]
|
||||
del state_dict[f"{prefix}.mlp.experts.w3"]
|
||||
|
||||
|
||||
def convert_hf_to_tt_moe(state_dict: dict[str, Tensor]):
|
||||
"""Convert MoE weights from HF to PrimeRL format in-place."""
|
||||
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_to_hf_moe(state_dict: dict[str, Tensor]):
|
||||
"""Convert MoE weights from PrimeRL to HF format in-place."""
|
||||
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,276 @@
|
||||
from typing import Optional, Union
|
||||
|
||||
import torch
|
||||
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, can_return_tuple, logging
|
||||
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
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
|
||||
from prime_rl.trainer.models.minimax_m2.configuration_minimax_m2 import MiniMaxM2Config
|
||||
from prime_rl.trainer.models.minimax_m2.converting_minimax_m2 import (
|
||||
convert_hf_layer_to_tt,
|
||||
convert_hf_to_tt_moe,
|
||||
convert_tt_layer_to_hf,
|
||||
convert_tt_to_hf_moe,
|
||||
)
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
|
||||
class MiniMaxM2DecoderLayer(GradientCheckpointingLayer):
|
||||
def __init__(self, config: MiniMaxM2Config, layer_idx: int):
|
||||
super().__init__()
|
||||
self.hidden_size = config.hidden_size
|
||||
|
||||
attn_config = AttentionConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
head_dim=config.head_dim,
|
||||
num_attention_heads=config.num_attention_heads,
|
||||
num_key_value_heads=config.num_key_value_heads,
|
||||
is_causal=True,
|
||||
attention_bias=config.attention_bias,
|
||||
use_qk_norm=config.use_qk_norm,
|
||||
rms_norm_eps=config.rms_norm_eps,
|
||||
qk_norm_type=config.qk_norm_type,
|
||||
)
|
||||
self.self_attn = ATTN_IMPL2CLASS[config._attn_implementation](attn_config)
|
||||
|
||||
moe_args = MoEArgs(
|
||||
num_experts=config.num_local_experts,
|
||||
num_shared_experts=0,
|
||||
score_func=config.scoring_func,
|
||||
route_norm=True,
|
||||
route_scale=1.0,
|
||||
score_before_experts=False,
|
||||
top_k=config.num_experts_per_tok,
|
||||
use_grouped_mm=config.use_grouped_mm,
|
||||
load_balance_coeff=1e-3 if config.use_routing_bias else None,
|
||||
)
|
||||
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.intermediate_size)
|
||||
|
||||
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> torch.FloatTensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.input_layernorm(hidden_states)
|
||||
hidden_states, _ = self.self_attn(
|
||||
hidden_states=hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
)
|
||||
hidden_states = residual + hidden_states
|
||||
|
||||
residual = hidden_states
|
||||
hidden_states = self.post_attention_layernorm(hidden_states)
|
||||
hidden_states = self.mlp(hidden_states)
|
||||
hidden_states = residual + hidden_states
|
||||
return hidden_states
|
||||
|
||||
|
||||
@auto_docstring
|
||||
class MiniMaxM2PreTrainedModel(PreTrainedModelPrimeRL):
|
||||
config: MiniMaxM2Config
|
||||
base_model_prefix = "model"
|
||||
supports_gradient_checkpointing = True
|
||||
_no_split_modules = ["MiniMaxM2DecoderLayer"]
|
||||
_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": MiniMaxM2DecoderLayer,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return any("block_sparse_moe.experts.1.w1" 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 name for 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 MiniMaxM2Model(MiniMaxM2PreTrainedModel):
|
||||
def __init__(self, config: MiniMaxM2Config):
|
||||
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(
|
||||
[MiniMaxM2DecoderLayer(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))
|
||||
|
||||
if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
|
||||
rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
||||
else:
|
||||
rope_type = "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 = self.embed_tokens(input_ids)
|
||||
|
||||
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
|
||||
flat_position_ids = position_ids.view(-1)
|
||||
seqlens = torch.cat(
|
||||
[
|
||||
flat_position_ids[0:1],
|
||||
flat_position_ids[:-1][(flat_position_ids == 0)[1:]] + 1,
|
||||
flat_position_ids[-1:] + 1,
|
||||
]
|
||||
)
|
||||
max_seqlen = seqlens.max().item()
|
||||
cu_seqlens = seqlens.cumsum(dim=0, dtype=torch.int32)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
else:
|
||||
max_seqlen = None
|
||||
cu_seqlens = None
|
||||
|
||||
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,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
)
|
||||
|
||||
hidden_states = self.norm(hidden_states)
|
||||
return BaseModelOutputWithPast(last_hidden_state=hidden_states)
|
||||
|
||||
|
||||
@auto_docstring
|
||||
class MiniMaxM2ForCausalLM(MiniMaxM2PreTrainedModel, 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 = MiniMaxM2Model(config)
|
||||
self.vocab_size = config.vocab_size
|
||||
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
||||
|
||||
self.post_init()
|
||||
|
||||
@can_return_tuple
|
||||
@auto_docstring
|
||||
def forward(
|
||||
self,
|
||||
input_ids: Optional[torch.LongTensor] = None,
|
||||
attention_mask: Optional[torch.Tensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
past_key_values: Optional[Cache] = None,
|
||||
inputs_embeds: Optional[torch.FloatTensor] = None,
|
||||
labels: Optional[torch.LongTensor] = None,
|
||||
use_cache: Optional[bool] = None,
|
||||
cache_position: Optional[torch.LongTensor] = None,
|
||||
logits_to_keep: Union[int, torch.Tensor] = 0,
|
||||
temperature: Union[torch.Tensor, None] = None,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> PrimeLmOutput:
|
||||
r"""
|
||||
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
||||
Labels for computing the masked language modeling loss.
|
||||
temperature (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
||||
Per-token temperatures for logprobs/entropy computation.
|
||||
"""
|
||||
assert use_cache is None, "use_cache is not supported for custom minimax_m2 for now"
|
||||
assert past_key_values is None, "past_key_values is not supported for custom minimax_m2 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__ = [
|
||||
"MiniMaxM2ForCausalLM",
|
||||
"MiniMaxM2Model",
|
||||
"MiniMaxM2PreTrainedModel",
|
||||
]
|
||||
@@ -74,19 +74,16 @@ def convert_tt_layer_to_hf(state_dict: dict[str, Tensor], layer_index: int):
|
||||
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 new fused format (transformers 5.0+)
|
||||
w1 = state_dict[f"model.layers.{i}.mlp.experts.w1"] # (num_experts, moe_dim, dim)
|
||||
w2 = state_dict[f"model.layers.{i}.mlp.experts.w2"] # (num_experts, dim, moe_dim)
|
||||
w3 = state_dict[f"model.layers.{i}.mlp.experts.w3"] # (num_experts, moe_dim, dim)
|
||||
# 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)
|
||||
|
||||
# Fuse w1 (gate) and w3 (up) into gate_up_proj
|
||||
gate_up_proj = torch.cat([w1, w3], dim=1) # (num_experts, 2*moe_dim, dim)
|
||||
state_dict[f"model.layers.{i}.mlp.experts.gate_up_proj"] = gate_up_proj
|
||||
state_dict[f"model.layers.{i}.mlp.experts.down_proj"] = w2
|
||||
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.w1"]
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.w2"]
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.w3"]
|
||||
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_hf_to_tt_moe(state_dict: dict[str, Tensor]):
|
||||
|
||||
@@ -14,7 +14,7 @@ NO_BOLD = "\033[22m"
|
||||
RESET = "\033[0m"
|
||||
|
||||
|
||||
def _build_log_entry(record) -> dict:
|
||||
def build_log_entry(record) -> dict:
|
||||
"""Build a flat JSON log entry from a loguru record."""
|
||||
extra = record["extra"]
|
||||
|
||||
@@ -54,14 +54,14 @@ def _build_log_entry(record) -> dict:
|
||||
return log_entry
|
||||
|
||||
|
||||
def _json_sink(message) -> None:
|
||||
def json_sink(message) -> None:
|
||||
"""Sink that outputs flat JSON to stdout for log aggregation (Loki, Grafana, etc.)."""
|
||||
log_entry = _build_log_entry(message.record)
|
||||
log_entry = build_log_entry(message.record)
|
||||
sys.stdout.write(json_module.dumps(log_entry) + "\n")
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
class _JsonFileSink:
|
||||
class JsonFileSink:
|
||||
"""File sink that keeps the handle open and writes flat JSON lines."""
|
||||
|
||||
def __init__(self, log_file: Path):
|
||||
@@ -74,7 +74,7 @@ class _JsonFileSink:
|
||||
self._file.close()
|
||||
|
||||
def write(self, message) -> None:
|
||||
log_entry = _build_log_entry(message.record)
|
||||
log_entry = build_log_entry(message.record)
|
||||
self._file.write(json_module.dumps(log_entry) + "\n")
|
||||
self._file.flush()
|
||||
|
||||
@@ -102,17 +102,19 @@ class InterceptHandler(logging.Handler):
|
||||
|
||||
|
||||
def setup_logger(
|
||||
log_level: str,
|
||||
log_level: str = "info",
|
||||
log_file: Path | None = None,
|
||||
append: bool = False,
|
||||
tag: str | None = None,
|
||||
json_logging: bool = False,
|
||||
):
|
||||
global _LOGGER, _JSON_LOGGING
|
||||
if _LOGGER is not None:
|
||||
raise RuntimeError("Logger already set. Please call `setup_logger` only once.")
|
||||
_JSON_LOGGING = json_logging
|
||||
|
||||
# Clean up old logger instance to prevent resource leaks
|
||||
if _LOGGER is not None:
|
||||
_LOGGER.remove()
|
||||
|
||||
# Format message with optional tag prefix
|
||||
tag_prefix = f"[{tag}] " if tag else ""
|
||||
message = "".join(
|
||||
@@ -154,7 +156,7 @@ def setup_logger(
|
||||
|
||||
# Install console handler (enqueue=True only for JSON mode to avoid blocking in async contexts)
|
||||
if json_logging:
|
||||
logger.add(_json_sink, level=log_level.upper(), enqueue=True)
|
||||
logger.add(json_sink, level=log_level.upper(), enqueue=True)
|
||||
else:
|
||||
logger.add(sys.stdout, format=format, level=log_level.upper(), colorize=True)
|
||||
|
||||
@@ -163,7 +165,7 @@ def setup_logger(
|
||||
if not append and log_file.exists():
|
||||
log_file.unlink()
|
||||
if json_logging:
|
||||
file_sink = _JsonFileSink(log_file)
|
||||
file_sink = JsonFileSink(log_file)
|
||||
logger.add(file_sink.write, level=log_level.upper(), enqueue=True)
|
||||
else:
|
||||
logger.add(log_file, format=format, level=log_level.upper(), colorize=True)
|
||||
@@ -178,23 +180,17 @@ def setup_logger(
|
||||
|
||||
|
||||
def get_logger():
|
||||
"""
|
||||
Get the global logger. This function is shared across submodules such as
|
||||
training and inference to access the global logger instance. Raises if the
|
||||
logger has not been set.
|
||||
|
||||
Returns:
|
||||
The global logger.
|
||||
"""
|
||||
global _LOGGER
|
||||
if _LOGGER is None:
|
||||
raise RuntimeError("Logger not set. Please call `set_logger` first.")
|
||||
_LOGGER = setup_logger()
|
||||
return _LOGGER
|
||||
|
||||
|
||||
def reset_logger():
|
||||
"""Reset the global logger. Useful mainly in test to clear loggers between tests."""
|
||||
"""Reset the logger. Useful mainly in tests."""
|
||||
global _LOGGER, _JSON_LOGGING
|
||||
if _LOGGER is not None:
|
||||
_LOGGER.remove()
|
||||
_LOGGER = None
|
||||
_JSON_LOGGING = False
|
||||
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import ProcessResult
|
||||
from tests.utils import check_no_error
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
TIMEOUT = 900 # 15 minutes
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
return f"test-rl-moe-{branch_name}"
|
||||
|
||||
|
||||
# --- MoE with HF impl (default) ---
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def moe_hf_output_dir(output_dir: Path) -> Path:
|
||||
d = output_dir / "rl_moe_hf"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def moe_hf_process(
|
||||
run_process: Callable[..., ProcessResult],
|
||||
moe_hf_output_dir: Path,
|
||||
wandb_project: str,
|
||||
wandb_name: str,
|
||||
) -> ProcessResult:
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/rl_moe/start.toml",
|
||||
"--trainer.model.impl",
|
||||
"hf",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
f"{wandb_name}-hf",
|
||||
"--output-dir",
|
||||
moe_hf_output_dir.as_posix(),
|
||||
]
|
||||
return run_process(cmd, timeout=TIMEOUT)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error_hf(moe_hf_process: ProcessResult, moe_hf_output_dir: Path):
|
||||
check_no_error(moe_hf_process, moe_hf_output_dir)
|
||||
|
||||
|
||||
def test_moe_hf_runs(moe_hf_process: ProcessResult, test_no_error_hf):
|
||||
"""MoE RL with HF model impl completes without error."""
|
||||
|
||||
|
||||
# --- MoE with custom impl ---
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def moe_custom_output_dir(output_dir: Path) -> Path:
|
||||
d = output_dir / "rl_moe_custom"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def moe_custom_process(
|
||||
run_process: Callable[..., ProcessResult],
|
||||
moe_custom_output_dir: Path,
|
||||
wandb_project: str,
|
||||
wandb_name: str,
|
||||
) -> ProcessResult:
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/rl_moe/start.toml",
|
||||
"--trainer.model.impl",
|
||||
"custom",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
f"{wandb_name}-custom",
|
||||
"--output-dir",
|
||||
moe_custom_output_dir.as_posix(),
|
||||
]
|
||||
return run_process(cmd, timeout=TIMEOUT)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error_custom(moe_custom_process: ProcessResult, moe_custom_output_dir: Path):
|
||||
check_no_error(moe_custom_process, moe_custom_output_dir)
|
||||
|
||||
|
||||
def test_moe_custom_runs(moe_custom_process: ProcessResult, test_no_error_custom):
|
||||
"""MoE RL with custom model impl completes without error."""
|
||||
@@ -118,21 +118,6 @@ def test_glm4_moe() -> None:
|
||||
grad_diff = hf_model.model.embed_tokens.weight.grad - prime_model.model.embed_tokens.weight.grad
|
||||
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
|
||||
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
hf_from_prime_model = HFGlm4MoeForCausalLM._from_config(hf_model.config)
|
||||
converted_state_dict = prime_model.convert_to_hf(prime_model.state_dict())
|
||||
hf_from_prime_model.load_state_dict(converted_state_dict)
|
||||
|
||||
hf_from_prime_output = hf_from_prime_model(input_ids, position_ids)
|
||||
hf_from_prime_output.logits.sum().backward()
|
||||
|
||||
logits_diff = hf_from_prime_output.logits - hf_output.logits
|
||||
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
|
||||
f"Max logits diff: {logits_diff.abs().max()}"
|
||||
)
|
||||
grad_diff = hf_from_prime_model.model.embed_tokens.weight.grad - hf_model.model.embed_tokens.weight.grad
|
||||
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_glm4_moe_mlp_only()
|
||||
|
||||
@@ -117,21 +117,6 @@ def test_qwen3_moe():
|
||||
grad_diff = hf_model.model.embed_tokens.weight.grad - prime_model.model.embed_tokens.weight.grad
|
||||
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
|
||||
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
hf_from_prime_model = HFQwen3MoeForCausalLM._from_config(hf_model.config)
|
||||
converted_state_dict = prime_model.convert_to_hf(prime_model.state_dict())
|
||||
hf_from_prime_model.load_state_dict(converted_state_dict)
|
||||
|
||||
hf_from_prime_output = hf_from_prime_model(input_ids, position_ids)
|
||||
hf_from_prime_output.logits.sum().backward()
|
||||
|
||||
logits_diff = hf_from_prime_output.logits - hf_output.logits
|
||||
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
|
||||
f"Max logits diff: {logits_diff.abs().max()}"
|
||||
)
|
||||
grad_diff = hf_from_prime_model.model.embed_tokens.weight.grad - hf_model.model.embed_tokens.weight.grad
|
||||
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_qwen3_moe_mlp_only()
|
||||
|
||||
@@ -755,14 +755,14 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "flash-attn"
|
||||
version = "2.6.3+cu128torch2.10"
|
||||
source = { url = "https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.16/flash_attn-2.6.3%2Bcu128torch2.10-cp312-cp312-linux_x86_64.whl" }
|
||||
version = "2.8.3+cu128torch2.10"
|
||||
source = { url = "https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.16/flash_attn-2.8.3%2Bcu128torch2.10-cp312-cp312-linux_x86_64.whl" }
|
||||
dependencies = [
|
||||
{ name = "einops" },
|
||||
{ name = "torch" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.16/flash_attn-2.6.3%2Bcu128torch2.10-cp312-cp312-linux_x86_64.whl", hash = "sha256:e883225b48075ea57790527ae3f653421a58c25d207375d00a1dfa9221b5bd43" },
|
||||
{ url = "https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.16/flash_attn-2.8.3%2Bcu128torch2.10-cp312-cp312-linux_x86_64.whl", hash = "sha256:5ef676dfd01d198eed36795d924eb6af4c87674896de6bd102390afa7f522bc0" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
@@ -2334,7 +2334,7 @@ requires-dist = [
|
||||
{ name = "beartype", specifier = ">=0.21.0" },
|
||||
{ name = "datasets", specifier = ">=4.0.0" },
|
||||
{ name = "dion", git = "https://github.com/samsja/dion.git?rev=d891eeb" },
|
||||
{ name = "flash-attn", marker = "extra == 'flash-attn'", url = "https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.16/flash_attn-2.6.3%2Bcu128torch2.10-cp312-cp312-linux_x86_64.whl" },
|
||||
{ name = "flash-attn", marker = "extra == 'flash-attn'", url = "https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.16/flash_attn-2.8.3%2Bcu128torch2.10-cp312-cp312-linux_x86_64.whl" },
|
||||
{ name = "flash-attn-3", marker = "extra == 'flash-attn-3'", url = "https://github.com/samsja/flash-attn-builds/releases/download/v0.1/flash_attn_3-3.0.0b1-cp39-abi3-linux_x86_64.whl" },
|
||||
{ name = "flash-attn-cute", marker = "extra == 'flash-attn-cute'", git = "https://github.com/Dao-AILab/flash-attention.git?subdirectory=flash_attn%2Fcute&rev=main" },
|
||||
{ name = "jaxtyping", specifier = ">=0.3.2" },
|
||||
@@ -2358,7 +2358,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=786d300" },
|
||||
{ name = "verifiers", git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=ad77074" },
|
||||
{ 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" },
|
||||
]
|
||||
@@ -3687,7 +3687,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "verifiers"
|
||||
version = "0.1.11.dev0"
|
||||
source = { git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=786d300#786d300bf5aab105279fc542dda838beafcb025e" }
|
||||
source = { git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=ad77074#ad77074e6e8585242425aabd598fc102584a0777" }
|
||||
dependencies = [
|
||||
{ name = "anthropic" },
|
||||
{ name = "datasets" },
|
||||
|
||||
Reference in New Issue
Block a user