* 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
251 lines
9.6 KiB
Python
251 lines
9.6 KiB
Python
import pytest
|
|
import torch
|
|
from transformers import AutoConfig
|
|
from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import (
|
|
Qwen3_5MoeForConditionalGeneration as HFQwen3_5MoeVLM,
|
|
)
|
|
|
|
from prime_rl.trainer.model import can_reinit_empty_buffers
|
|
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
|
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeForCausalLM
|
|
from prime_rl.utils.utils import default_dtype
|
|
|
|
pytestmark = [pytest.mark.gpu]
|
|
|
|
|
|
def _tiny_vlm_config():
|
|
"""HF composite config shrunk for unit testing."""
|
|
config = AutoConfig.from_pretrained(
|
|
"Qwen/Qwen3.5-35B-A3B", trust_remote_code=True, attn_implementation="flash_attention_2"
|
|
)
|
|
config.use_cache = False
|
|
tc = config.text_config
|
|
tc.vocab_size = 256
|
|
tc.hidden_size = 256
|
|
tc.num_hidden_layers = 2
|
|
tc.layer_types = ["linear_attention", "full_attention"]
|
|
tc.num_attention_heads = 4
|
|
tc.num_key_value_heads = 2
|
|
tc.head_dim = 64
|
|
tc.moe_intermediate_size = 128
|
|
tc.shared_expert_intermediate_size = 128
|
|
tc.num_experts = 4
|
|
tc.num_experts_per_tok = 2
|
|
tc.max_position_embeddings = 512
|
|
tc.linear_key_head_dim = 32
|
|
tc.linear_value_head_dim = 32
|
|
tc.linear_num_key_heads = 4
|
|
tc.linear_num_value_heads = 8
|
|
tc.use_cache = False
|
|
tc.rope_parameters["mrope_section"] = [3, 3, 2]
|
|
|
|
vc = config.vision_config
|
|
vc.depth = 2
|
|
vc.hidden_size = 128
|
|
vc.intermediate_size = 256
|
|
vc.num_heads = 4
|
|
vc.out_hidden_size = tc.hidden_size
|
|
|
|
# Special token IDs must fit within the tiny vocab
|
|
config.image_token_id = 250
|
|
config.video_token_id = 251
|
|
config.vision_start_token_id = 252
|
|
config.vision_end_token_id = 253
|
|
return config
|
|
|
|
|
|
def _make_image_inputs(config, device="cuda", dtype=torch.bfloat16):
|
|
"""Create minimal image inputs matching the vision config."""
|
|
vc = config.vision_config
|
|
patch_dim = vc.in_channels * vc.temporal_patch_size * vc.patch_size * vc.patch_size
|
|
image_grid_thw = torch.tensor([[1, 2, 2]], device=device)
|
|
num_patches = int(image_grid_thw.prod().item())
|
|
pixel_values = torch.randn(num_patches, patch_dim, device=device, dtype=dtype)
|
|
num_image_tokens = num_patches // (vc.spatial_merge_size**2)
|
|
return pixel_values, image_grid_thw, num_image_tokens
|
|
|
|
|
|
def _make_mm_token_type_ids(input_ids, image_token_id):
|
|
mm_token_type_ids = torch.zeros_like(input_ids)
|
|
mm_token_type_ids[input_ids == image_token_id] = 1
|
|
return mm_token_type_ids
|
|
|
|
|
|
def _seq_lens(input_ids: torch.Tensor) -> torch.Tensor:
|
|
return torch.tensor([input_ids.shape[1]], device=input_ids.device)
|
|
|
|
|
|
def test_vlm_forward():
|
|
"""Custom VLM produces logits for both text-only and multimodal inputs."""
|
|
config = _tiny_vlm_config()
|
|
with torch.device("cuda"), default_dtype(torch.bfloat16):
|
|
model = Qwen3_5MoeForCausalLM(config)
|
|
inject_prime_lm_head(model)
|
|
|
|
vocab = config.text_config.vocab_size
|
|
|
|
# Text-only (avoid special token range 250-253)
|
|
input_ids = torch.randint(0, 200, (1, 20), device="cuda")
|
|
position_ids = torch.arange(1, 21, device="cuda").unsqueeze(0)
|
|
out_text = model(input_ids=input_ids, position_ids=position_ids, seq_lens=_seq_lens(input_ids))
|
|
assert out_text["logits"].shape == (1, 20, vocab)
|
|
|
|
# Multimodal
|
|
pixel_values, image_grid_thw, n_img_tokens = _make_image_inputs(config)
|
|
text_part = torch.randint(0, 200, (1, 10), device="cuda")
|
|
img_part = torch.full((1, n_img_tokens), config.image_token_id, device="cuda")
|
|
input_ids_mm = torch.cat([text_part[:, :5], img_part, text_part[:, 5:]], dim=1)
|
|
mm_token_type_ids = _make_mm_token_type_ids(input_ids_mm, config.image_token_id)
|
|
|
|
out_mm = model(
|
|
input_ids=input_ids_mm,
|
|
pixel_values=pixel_values,
|
|
image_grid_thw=image_grid_thw,
|
|
mm_token_type_ids=mm_token_type_ids,
|
|
seq_lens=_seq_lens(input_ids_mm),
|
|
)
|
|
assert out_mm["logits"].shape == (1, input_ids_mm.shape[1], vocab)
|
|
|
|
|
|
def test_vlm_backward():
|
|
"""Gradients flow through both vision scatter and text model."""
|
|
config = _tiny_vlm_config()
|
|
with torch.device("cuda"), default_dtype(torch.bfloat16):
|
|
model = Qwen3_5MoeForCausalLM(config)
|
|
inject_prime_lm_head(model)
|
|
|
|
pixel_values, image_grid_thw, n_img_tokens = _make_image_inputs(config)
|
|
text_part = torch.randint(0, 200, (1, 10), device="cuda")
|
|
img_part = torch.full((1, n_img_tokens), config.image_token_id, device="cuda")
|
|
input_ids = torch.cat([text_part[:, :5], img_part, text_part[:, 5:]], dim=1)
|
|
mm_token_type_ids = _make_mm_token_type_ids(input_ids, config.image_token_id)
|
|
|
|
out = model(
|
|
input_ids=input_ids,
|
|
pixel_values=pixel_values,
|
|
image_grid_thw=image_grid_thw,
|
|
mm_token_type_ids=mm_token_type_ids,
|
|
seq_lens=_seq_lens(input_ids),
|
|
)
|
|
out["logits"].sum().backward()
|
|
|
|
assert model.model.language_model.embed_tokens.weight.grad is not None
|
|
assert model.model.visual.patch_embed.proj.weight.grad is not None
|
|
|
|
|
|
def test_vlm_weight_load_from_hf():
|
|
"""Weights from HF VLM checkpoint load correctly into custom VLM after conversion.
|
|
|
|
Text model numerical match is already validated by test_qwen3_5_moe.py::test_qwen3_5_moe.
|
|
This test verifies that VLM weight conversion + loading produces a working model.
|
|
"""
|
|
config = _tiny_vlm_config()
|
|
with torch.device("cuda"), default_dtype(torch.bfloat16):
|
|
hf_model = HFQwen3_5MoeVLM._from_config(config)
|
|
prime_model = Qwen3_5MoeForCausalLM(config)
|
|
|
|
# Copy weights: HF -> PrimeRL (with MoE conversion)
|
|
with torch.no_grad():
|
|
hf_sd = hf_model.state_dict()
|
|
prime_model.convert_to_prime(hf_sd)
|
|
prime_model.load_state_dict(hf_sd)
|
|
inject_prime_lm_head(prime_model)
|
|
|
|
# Verify vision encoder weights match exactly (should be untouched by conversion)
|
|
for name, param in hf_model.model.visual.named_parameters():
|
|
prime_param = dict(prime_model.model.visual.named_parameters())[name]
|
|
assert torch.equal(param, prime_param), f"Vision weight mismatch: {name}"
|
|
|
|
# Verify model produces output after weight loading
|
|
input_ids = torch.randint(0, 200, (1, 20), device="cuda")
|
|
position_ids = torch.arange(1, 21, device="cuda").unsqueeze(0)
|
|
out = prime_model(input_ids=input_ids, position_ids=position_ids, seq_lens=_seq_lens(input_ids))
|
|
assert out["logits"].shape[2] == config.text_config.vocab_size
|
|
assert not torch.isnan(out["logits"]).any()
|
|
|
|
|
|
def test_vlm_weight_roundtrip():
|
|
"""HF -> PrimeRL -> HF weight conversion is lossless (vision keys untouched, text keys converted)."""
|
|
config = _tiny_vlm_config()
|
|
with torch.device("cuda"), default_dtype(torch.bfloat16):
|
|
hf_model = HFQwen3_5MoeVLM._from_config(config)
|
|
prime_model = Qwen3_5MoeForCausalLM(config)
|
|
|
|
hf_sd = hf_model.state_dict()
|
|
original_vision_key = "model.visual.blocks.0.mlp.linear_fc1.weight"
|
|
original_vision_weight = hf_sd[original_vision_key].clone()
|
|
|
|
# HF -> PrimeRL
|
|
prime_sd = dict(hf_sd)
|
|
prime_model.convert_to_prime(prime_sd)
|
|
assert any("language_model" in k and "mlp.experts.w1" in k for k in prime_sd)
|
|
assert original_vision_key in prime_sd
|
|
|
|
# PrimeRL -> HF
|
|
roundtripped = dict(prime_sd)
|
|
prime_model.convert_to_hf(roundtripped)
|
|
|
|
# Original HF also needs roundtrip for expert format normalization
|
|
orig_rt = dict(hf_sd)
|
|
prime_model.convert_to_prime(orig_rt)
|
|
prime_model.convert_to_hf(orig_rt)
|
|
|
|
for key in orig_rt:
|
|
assert key in roundtripped, f"Missing key: {key}"
|
|
assert torch.equal(orig_rt[key], roundtripped[key]), f"Mismatch at {key}"
|
|
|
|
# Vision weights preserved through the whole roundtrip
|
|
assert torch.equal(roundtripped[original_vision_key], original_vision_weight)
|
|
|
|
|
|
def test_vlm_router_replay():
|
|
"""routed_experts bypasses router computation in VLM multimodal forward."""
|
|
config = _tiny_vlm_config()
|
|
with torch.device("cuda"), default_dtype(torch.bfloat16):
|
|
model = Qwen3_5MoeForCausalLM(config)
|
|
inject_prime_lm_head(model)
|
|
|
|
vocab = config.text_config.vocab_size
|
|
pixel_values, image_grid_thw, n_img_tokens = _make_image_inputs(config)
|
|
text_part = torch.randint(0, 200, (1, 10), device="cuda")
|
|
img_part = torch.full((1, n_img_tokens), config.image_token_id, device="cuda")
|
|
input_ids = torch.cat([text_part[:, :5], img_part, text_part[:, 5:]], dim=1)
|
|
mm_token_type_ids = _make_mm_token_type_ids(input_ids, config.image_token_id)
|
|
seq_len = input_ids.shape[1]
|
|
|
|
num_layers = config.text_config.num_hidden_layers
|
|
topk = config.text_config.num_experts_per_tok
|
|
routed_experts = torch.randint(0, config.text_config.num_experts, (1, seq_len, num_layers, topk), device="cuda")
|
|
|
|
out = model(
|
|
input_ids=input_ids,
|
|
pixel_values=pixel_values,
|
|
image_grid_thw=image_grid_thw,
|
|
mm_token_type_ids=mm_token_type_ids,
|
|
routed_experts=routed_experts,
|
|
seq_lens=_seq_lens(input_ids),
|
|
)
|
|
assert out["logits"].shape == (1, seq_len, vocab)
|
|
|
|
out["logits"].sum().backward()
|
|
assert model.model.language_model.embed_tokens.weight.grad is not None
|
|
|
|
|
|
def test_vlm_meta_device_and_buffer_reinit():
|
|
"""Model can be created on meta device and buffers reinitialized."""
|
|
config = _tiny_vlm_config()
|
|
with torch.device("meta"):
|
|
model = Qwen3_5MoeForCausalLM.from_config(config)
|
|
|
|
assert can_reinit_empty_buffers(model)
|
|
|
|
model.to_empty(device="cuda")
|
|
model.init_buffers_post_meta()
|
|
|
|
lm_inv = model.model.language_model.rotary_emb.inv_freq
|
|
vis_inv = model.model.visual.rotary_pos_emb.inv_freq
|
|
assert lm_inv.device.type == "cuda"
|
|
assert vis_inv.device.type == "cuda"
|
|
assert lm_inv.abs().sum() > 0
|
|
assert vis_inv.abs().sum() > 0
|