import torch
from modelexpress.refit.reshard.geometry import capture_geometry
from modelexpress.refit.reshard.slice_plan import Shard, plan_pull
HIDDEN = 4
INTER = 8 TP_SIZE = 2
TP_RANK = 0
INTER_PER_TP = INTER // TP_SIZE
LOCAL_EXPERTS = 2
class FusedMoEModel(torch.nn.Module):
def __init__(self):
super().__init__()
self.w13_weight = torch.nn.Parameter(
torch.empty(LOCAL_EXPERTS, 2 * INTER_PER_TP, HIDDEN)
)
self.w13_weight.weight_loader = self._expert_loader
def _expert_loader(self, *, param, loaded_weight, shard_id, expert_id):
expert_data = param.data[expert_id]
member = 0 if shard_id == "w1" else 1
dest = expert_data.narrow(0, member * INTER_PER_TP, INTER_PER_TP)
src = loaded_weight.narrow(0, TP_RANK * INTER_PER_TP, INTER_PER_TP)
dest.copy_(src)
def load_weights(self, weights):
for name, loaded in weights:
expert_id = int(name.split(".experts.")[1].split(".")[0])
shard_id = "w1" if "gate_proj" in name else "w3"
experts_shard = loaded.unsqueeze(0)
for local_id, loaded_expert in enumerate(
experts_shard.unbind(), start=expert_id
):
self.w13_weight.weight_loader(
param=self.w13_weight,
loaded_weight=loaded_expert,
shard_id=shard_id,
expert_id=local_id,
)
def _name(expert: int, proj: str) -> str:
return f"model.layers.0.mlp.experts.{expert}.{proj}.weight"
def _manifest():
return [
(_name(e, proj), torch.float32, [INTER, HIDDEN])
for e in range(LOCAL_EXPERTS)
for proj in ("gate_proj", "up_proj")
]
def test_per_expert_sources_capture_into_fused_destination():
with torch.device("meta"):
model = FusedMoEModel()
result = capture_geometry(model, _manifest())
assert result.unsupported == []
assert result.unsupported_reasons == {}
assert result.unattributed == 0
assert len(result.copies) == 2 * LOCAL_EXPERTS
by_src = {c.src_name: c for c in result.copies}
assert set(by_src) == {n for n, _, _ in _manifest()}
for copy in result.copies:
assert copy.param_name == "w13_weight"
assert copy.dest_shape == (INTER_PER_TP, HIDDEN)
assert ("unbind", (), ()) in copy.op_chain
def test_unbind_is_recorded_and_does_not_change_rank():
with torch.device("meta"):
model = FusedMoEModel()
result = capture_geometry(model, _manifest())
copy = next(c for c in result.copies if c.src_name == _name(0, "gate_proj"))
ops = [name for name, _args, _kw in copy.op_chain]
assert ops[:3] == ["unsqueeze", "unbind", "__getitem__"]
assert "narrow" in ops
def test_expert_copies_plan_to_the_right_source_bytes():
with torch.device("meta"):
model = FusedMoEModel()
result = capture_geometry(model, _manifest())
copy = next(c for c in result.copies if c.src_name == _name(1, "up_proj"))
shard = Shard(
shard_offset=(0, 0),
shape=(INTER, HIDDEN),
session="pub0",
addr=0,
elsize=4,
)
segments = plan_pull(
copy,
global_shape=(INTER, HIDDEN),
src_dtype=torch.float32,
elsize=4,
shards=[shard],
)
assert segments, "expert copy produced no pull segments"
pulled = sum(s.nbytes for s in segments)
assert pulled == INTER_PER_TP * HIDDEN * 4
assert min(s.src_addr for s in segments) == 0
expected_dst = (
1 * (2 * INTER_PER_TP) * HIDDEN + INTER_PER_TP * HIDDEN
) * 4
assert min(s.dst_byte for s in segments) == expected_dst