* feat(weight-transfer): add NIXL ModelExpress synchronization * refactor(weight-transfer): simplify NIXL integration * refactor(weight-transfer): simplify NIXL worker planning * refactor(weight-transfer): align MX update lifecycle * feat(inference): pass through online quantization methods * feat(weight-transfer): add GLM trainer conversion graph * feat(weight-transfer): stream NIXL updates by layer * feat(weight-transfer): pipeline NIXL layer reloads * fix(weight-transfer): preserve single-buffer NIXL behavior * fix(weight-transfer): reserve observed inference peak * feat(weight-transfer): preserve model-declared FP32 tensors * cleanup(weight-transfer): simplify trainer wire schema * cleanup(weight-transfer): make trainer shard ranges explicit * cleanup(weight-transfer): resolve model conversions through registry * cleanup(weight-transfer): clarify lazy copy destinations * cleanup(weight-transfer): derive lazy metadata from source * cleanup(weight-transfer): rename weight load tracing * cleanup(weight-transfer): name recorded tensor operations * cleanup(weight-transfer): simplify transfer planning * cleanup(weight-transfer): consolidate load graph * cleanup(weight-transfer): name trainer tensor table * cleanup(weight-transfer): clarify tensor routing * cleanup(weight-transfer): simplify NIXL adapter * cleanup(weight-transfer): clarify ModelExpress sessions * cleanup(weight-transfer): clarify CUDA memory sizing * cleanup(weight-transfer): clarify staged trainer shards * cleanup(weight-transfer): simplify trainer broadcast guards * cleanup(weight-transfer): clarify trainer staging state * cleanup(weight-transfer): simplify trainer constants * cleanup(weight-transfer): use ModelExpress client name * cleanup(weight-transfer): clarify trainer shard discovery * cleanup(weight-transfer): structure trainer initialization * cleanup(weight-transfer): reuse trainer agent metadata * cleanup(weight-transfer): reuse trainer table fragments * cleanup(weight-transfer): simplify trainer staging setup * cleanup(weight-transfer): simplify inference transfer planning * cleanup(weight-transfer): split inference plan construction * cleanup(weight-transfer): clarify inference replay methods * cleanup(weight-transfer): localize receive arena sizing * cleanup(weight-transfer): clarify loader recording wrapper * cleanup(weight-transfer): clarify watcher synchronization * cleanup(weight-transfer): unify checkpoint wait timing * cleanup(weight-transfer): align in-memory broadcast lifecycle * fix(weight-transfer): skip NIXL startup filesystem wait * cleanup(weight-transfer): use declarative model conversions * style(weight-transfer): format NIXL implementation * fix(weight-transfer): stabilize ranks and final watcher step * fix(tests): use instance conversion API * cleanup(weight-transfer): scope package to NIXL * cleanup(weight-transfer): align names and package layout
191 lines
7.1 KiB
Python
191 lines
7.1 KiB
Python
import pytest
|
|
import torch
|
|
from transformers import Qwen3_5MoeForCausalLM as HFQwen3_5MoeForCausalLM
|
|
|
|
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
|
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeConfig
|
|
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeForCausalLM as PrimeRLQwen3_5MoeForCausalLM
|
|
from prime_rl.utils.cp import setup_model_cp
|
|
from prime_rl.utils.utils import default_dtype
|
|
|
|
pytestmark = [pytest.mark.gpu]
|
|
|
|
|
|
def get_model_pairs():
|
|
config = Qwen3_5MoeConfig(
|
|
vocab_size=256,
|
|
hidden_size=256,
|
|
num_hidden_layers=4,
|
|
num_attention_heads=4,
|
|
num_key_value_heads=2,
|
|
head_dim=64,
|
|
moe_intermediate_size=128,
|
|
shared_expert_intermediate_size=128,
|
|
num_experts=8,
|
|
num_experts_per_tok=2,
|
|
max_position_embeddings=512,
|
|
rms_norm_eps=1e-6,
|
|
linear_conv_kernel_dim=4,
|
|
linear_key_head_dim=32,
|
|
linear_value_head_dim=32,
|
|
linear_num_key_heads=4,
|
|
linear_num_value_heads=8,
|
|
use_grouped_mm=False,
|
|
)
|
|
config._attn_implementation = "flash_attention_2"
|
|
with torch.device("cuda"), default_dtype(torch.bfloat16):
|
|
hf_model = HFQwen3_5MoeForCausalLM._from_config(config)
|
|
prime_model = PrimeRLQwen3_5MoeForCausalLM._from_config(config)
|
|
with torch.no_grad():
|
|
state_dict = hf_model.state_dict()
|
|
prime_state_keys = prime_model.state_dict().keys()
|
|
prime_model.convert_to_prime(state_dict)
|
|
prime_model.load_state_dict(state_dict)
|
|
inject_prime_lm_head(prime_model, chunk_size=None)
|
|
assert set(prime_state_keys) - set(state_dict.keys()) == set()
|
|
return hf_model, prime_model
|
|
|
|
|
|
def test_qwen3_5_moe():
|
|
hf_model, prime_model = get_model_pairs()
|
|
|
|
with torch.device("cuda"), default_dtype(torch.bfloat16):
|
|
input_ids = torch.randint(0, hf_model.config.vocab_size, (1, 100))
|
|
position_ids = torch.arange(1, 101).unsqueeze(0)
|
|
|
|
hf_output = hf_model(input_ids, position_ids=position_ids)
|
|
prime_output = prime_model(
|
|
input_ids,
|
|
position_ids=position_ids,
|
|
seq_lens=torch.tensor([input_ids.shape[1]], device="cuda"),
|
|
)
|
|
hf_output.logits.sum().backward()
|
|
prime_output["logits"].sum().backward()
|
|
|
|
logits_diff = prime_output["logits"] - hf_output.logits
|
|
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=1e-0), (
|
|
f"Max logits diff: {logits_diff.abs().max()}"
|
|
)
|
|
grad_diff = hf_model.model.embed_tokens.weight.grad - prime_model.model.embed_tokens.weight.grad
|
|
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=1000), f"Max grad diff: {grad_diff.abs().max()}"
|
|
|
|
|
|
def test_qwen3_5_moe_roundtrip():
|
|
"""Verify HF → PrimeRL → HF weight conversion is lossless at the state_dict level."""
|
|
hf_model, prime_model = get_model_pairs()
|
|
|
|
# Get original HF state_dict and the PrimeRL-converted version
|
|
original_hf_sd = hf_model.state_dict()
|
|
prime_sd = prime_model.state_dict()
|
|
|
|
# Convert PrimeRL → per-expert HF format
|
|
converted_hf_sd = prime_model.convert_to_hf(dict(prime_sd))
|
|
|
|
# Also convert original HF (fused) to per-expert format for comparison
|
|
|
|
# First convert original HF → PrimeRL, then back to per-expert HF
|
|
orig_prime_sd = dict(original_hf_sd)
|
|
prime_model.convert_to_prime(orig_prime_sd)
|
|
orig_roundtripped = dict(orig_prime_sd)
|
|
prime_model.convert_to_hf(orig_roundtripped)
|
|
|
|
# All non-expert keys should match exactly, expert keys should match after roundtrip
|
|
for key in orig_roundtripped:
|
|
assert key in converted_hf_sd, f"Missing key: {key}"
|
|
assert torch.equal(orig_roundtripped[key], converted_hf_sd[key]), f"Mismatch at {key}"
|
|
|
|
|
|
def test_qwen3_5_moe_router_replay():
|
|
"""When routed_experts are provided, the model uses them instead of computing routing."""
|
|
_, prime_model = get_model_pairs()
|
|
|
|
with torch.device("cuda"), default_dtype(torch.bfloat16):
|
|
input_ids = torch.randint(0, prime_model.config.vocab_size, (1, 100))
|
|
position_ids = torch.arange(1, 101).unsqueeze(0)
|
|
|
|
seq_lens = torch.tensor([input_ids.shape[1]], device="cuda")
|
|
out_normal = prime_model(input_ids, position_ids=position_ids, seq_lens=seq_lens)
|
|
|
|
num_layers = prime_model.config.num_hidden_layers
|
|
topk = prime_model.config.num_experts_per_tok
|
|
routed_experts = torch.randint(0, prime_model.config.num_experts, (1, 100, num_layers, topk), device="cuda")
|
|
|
|
prime_model.zero_grad()
|
|
out_replay = prime_model(
|
|
input_ids,
|
|
position_ids=position_ids,
|
|
routed_experts=routed_experts,
|
|
seq_lens=seq_lens,
|
|
)
|
|
|
|
assert out_replay["logits"].shape == out_normal["logits"].shape
|
|
|
|
out_replay["logits"].sum().backward()
|
|
assert prime_model.model.embed_tokens.weight.grad is not None
|
|
|
|
|
|
def test_qwen3_5_moe_cp_patching():
|
|
"""Verify substitute_ring_attn patches Qwen3_5MoeGatedFlashAttention._compute_attention."""
|
|
from unittest.mock import MagicMock
|
|
|
|
from prime_rl.trainer.models.afmoe.modeling_afmoe import AfmoeFlashAttention
|
|
from prime_rl.trainer.models.layers.attn import FlashAttention, substitute_ring_attn
|
|
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeGatedFlashAttention
|
|
|
|
# substitute_ring_attn rewrites _compute_attention on all three classes;
|
|
# snapshot every one so the patch can't leak into later tests via the
|
|
# untouched siblings.
|
|
originals = {
|
|
cls: cls._compute_attention for cls in (FlashAttention, AfmoeFlashAttention, Qwen3_5MoeGatedFlashAttention)
|
|
}
|
|
try:
|
|
mock_group = MagicMock()
|
|
substitute_ring_attn(process_group=mock_group, heads_k_stride=1)
|
|
assert Qwen3_5MoeGatedFlashAttention._compute_attention is not originals[Qwen3_5MoeGatedFlashAttention]
|
|
finally:
|
|
for cls, method in originals.items():
|
|
cls._compute_attention = method
|
|
|
|
|
|
def test_qwen3_5_moe_context_parallel_setup_hook():
|
|
from unittest.mock import MagicMock
|
|
|
|
config = Qwen3_5MoeConfig(
|
|
vocab_size=128,
|
|
hidden_size=64,
|
|
num_hidden_layers=2,
|
|
layer_types=["linear_attention", "full_attention"],
|
|
num_attention_heads=4,
|
|
num_key_value_heads=2,
|
|
head_dim=16,
|
|
moe_intermediate_size=64,
|
|
shared_expert_intermediate_size=64,
|
|
num_experts=4,
|
|
num_experts_per_tok=2,
|
|
max_position_embeddings=128,
|
|
linear_conv_kernel_dim=4,
|
|
linear_key_head_dim=8,
|
|
linear_value_head_dim=8,
|
|
linear_num_key_heads=4,
|
|
linear_num_value_heads=8,
|
|
use_grouped_mm=False,
|
|
)
|
|
config._attn_implementation = "flash_attention_2"
|
|
with torch.device("meta"):
|
|
model = PrimeRLQwen3_5MoeForCausalLM(config)
|
|
|
|
linear_layer = model.model.layers[0]
|
|
model.model.layers[0] = torch.nn.Sequential(linear_layer)
|
|
cp_group = MagicMock()
|
|
setup_model_cp(model, cp_group, cp_rank=1, cp_world_size=2)
|
|
|
|
assert model.model._cp_group is cp_group
|
|
assert model.model._cp_rank == 1
|
|
assert model.model._cp_world_size == 2
|
|
assert linear_layer.linear_attn.cp_group is cp_group
|
|
assert linear_layer.linear_attn.cp_world_size == 2
|
|
|
|
|
|
if __name__ == "__main__":
|
|
test_qwen3_5_moe()
|