File size: 9,378 Bytes
0ca2ffc | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | import unittest
import torch
import torch.nn as nn
import numpy as np
from types import SimpleNamespace
import copy
from graphmetro.models.canonical import MoEModel as CanonicalMoEModel
from graphmetro.models.moe import MoEModel as GeneratedMoEModel
from . import canonical
from . import moe as generation
mock_cfg = SimpleNamespace(
device='cpu',
dataset=SimpleNamespace(
task='node'
)
)
canonical.cfg = mock_cfg
generation.cfg = mock_cfg
class MockEncoder(nn.Module):
def __init__(self, in_dim, out_dim):
super().__init__()
self.linear = nn.Linear(in_dim, out_dim)
def forward(self, x, edge_index, edge_attr, batch):
return self.linear(x)
class MockExpertModel(nn.Module):
def __init__(self, in_dim=8, emb_dim=16, out_dim=4):
super().__init__()
self.encoder = MockEncoder(in_dim, emb_dim)
self.classifier = nn.Linear(emb_dim, out_dim)
def forward(self, x, edge_index, edge_attr, batch):
return self.encoder(x, edge_index, edge_attr, batch)
class MockGatingModel(nn.Module):
def __init__(self, in_dim, num_experts):
super().__init__()
self.scorer = nn.Linear(in_dim, num_experts)
def forward(self, x, edge_index, edge_attr, batch):
return self.scorer(x)
class TestMoEModelEquivalence(unittest.TestCase):
@classmethod
def setUpClass(cls):
torch.manual_seed(42)
np.random.seed(42)
cls.num_nodes = 10
cls.num_edges = 20
cls.feat_dim = 8
cls.emb_dim = 16
cls.num_experts = 3
cls.num_classes = 4
cls.original_data = SimpleNamespace(
x=torch.randn(cls.num_nodes, cls.feat_dim),
edge_index=torch.randint(0, cls.num_nodes, (2, cls.num_edges)),
edge_attr=torch.randn(cls.num_edges, 1),
batch=torch.sort(torch.randint(0, 2, (cls.num_nodes,)))[0]
)
cls.transformed_data = SimpleNamespace(
x=torch.randn(cls.num_nodes, cls.feat_dim),
edge_index=torch.randint(0, cls.num_nodes, (2, cls.num_edges)),
edge_attr=torch.randn(cls.num_edges, 1),
batch=cls.original_data.batch
)
cls.node_mask = torch.ones(cls.num_nodes, dtype=torch.bool)
cls.gating_targets = torch.tensor([0.0, 1.0, 0.0])
cls.trans_func_dict = {f'trans_{i}': lambda x: x for i in range(cls.num_experts)}
gating_model = MockGatingModel(cls.feat_dim, cls.num_experts)
expert_models = [MockExpertModel(cls.feat_dim, cls.emb_dim, cls.num_classes) for _ in range(cls.num_experts)]
cls.canonical_model = CanonicalMoEModel(
trans_func_dict=cls.trans_func_dict,
gating_model=gating_model,
expert_models=copy.deepcopy(expert_models)
)
cls.generated_model = GeneratedMoEModel(
trans_func_dict=cls.trans_func_dict,
gating_model=gating_model,
expert_models=copy.deepcopy(expert_models)
)
cls.canonical_model.eval()
cls.generated_model.eval()
def assert_tensors_close(self, tensor1, tensor2, msg):
self.assertIsInstance(tensor1, torch.Tensor, f"{msg} - Canonical output is not a tensor.")
self.assertIsInstance(tensor2, torch.Tensor, f"{msg} - Generated output is not a tensor.")
self.assertEqual(tensor1.shape, tensor2.shape, f"{msg} - Shape mismatch.")
torch.testing.assert_close(tensor1, tensor2, rtol=1e-5, atol=1e-6, msg=msg)
def test_01_init_equivalence(self):
self.assertEqual(self.canonical_model.num_experts, self.generated_model.num_experts)
self.assertIsNotNone(self.canonical_model.classifier)
self.assertIsNotNone(self.generated_model.classifier)
self.assertEqual(len(list(self.canonical_model.classifier.parameters())), len(list(self.generated_model.classifier.parameters())))
for i in range(self.num_experts):
self.assertIsNone(self.canonical_model.experts[i].classifier, f"Canonical expert {i} still has a classifier.")
self.assertIsNone(self.generated_model.experts[i].classifier, f"Generated expert {i} still has a classifier.")
def test_02_get_expert_weights_equivalence(self):
canonical_weights_softmax = self.canonical_model.get_expert_weights(self.transformed_data, softmax=True)
generated_weights_softmax = self.generated_model.get_expert_weights(self.transformed_data, softmax=True)
self.assert_tensors_close(canonical_weights_softmax, generated_weights_softmax, "Weight mismatch with softmax=True")
canonical_weights_logits = self.canonical_model.get_expert_weights(self.transformed_data, softmax=False)
generated_weights_logits = self.generated_model.get_expert_weights(self.transformed_data, softmax=False)
self.assert_tensors_close(canonical_weights_logits, generated_weights_logits, "Weight mismatch with softmax=False (logits)")
def test_03_aggregate_equivalence(self):
weights = torch.rand(self.num_nodes, self.num_experts)
weights = weights.softmax(dim=-1)
canonical_soft = self.canonical_model._aggregate(self.original_data, weights, hard=False)
generated_soft = self.generated_model._aggregate(self.original_data, weights, hard=False)
self.assert_tensors_close(canonical_soft, generated_soft, "Mismatch in soft aggregation")
canonical_hard = self.canonical_model._aggregate(self.original_data, weights, hard=True)
generated_hard = self.generated_model._aggregate(self.original_data, weights, hard=True)
self.assert_tensors_close(canonical_hard, generated_hard, "Mismatch in hard aggregation from weights")
expert_idx = 1
canonical_hard_idx = self.canonical_model._aggregate(self.original_data, expert_idx, hard=True)
generated_hard_idx = self.generated_model._aggregate(self.original_data, expert_idx, hard=True)
self.assert_tensors_close(canonical_hard_idx, generated_hard_idx, "Mismatch in hard aggregation from integer index")
def test_04_forward_equivalence(self):
c_out_hard, c_gate_hard = self.canonical_model.forward(self.transformed_data, hard=True, return_gating_out=True)
g_out_hard, g_gate_hard = self.generated_model.forward(self.transformed_data, hard=True, return_gating_out=True)
self.assert_tensors_close(c_out_hard, g_out_hard, "Mismatch in forward output (hard agg)")
self.assert_tensors_close(c_gate_hard, g_gate_hard, "Mismatch in forward gating weights (hard agg)")
c_out_soft, c_gate_soft = self.canonical_model.forward(self.transformed_data, hard=False, return_gating_out=True)
g_out_soft, g_gate_soft = self.generated_model.forward(self.transformed_data, hard=False, return_gating_out=True)
self.assert_tensors_close(c_out_soft, g_out_soft, "Mismatch in forward output (soft agg)")
self.assert_tensors_close(c_gate_soft, g_gate_soft, "Mismatch in forward gating weights (soft agg)")
c_out_only = self.canonical_model.forward(self.transformed_data, hard=False, return_gating_out=False)
g_out_only = self.generated_model.forward(self.transformed_data, hard=False, return_gating_out=False)
self.assertIsInstance(c_out_only, torch.Tensor)
self.assert_tensors_close(c_out_only, g_out_only, "Mismatch in forward output (gating output off)")
def test_05_losses_equivalence(self):
c_loss_vals = self.canonical_model.losses(self.original_data, self.transformed_data, self.node_mask, self.gating_targets, hard=True)
g_loss_vals = self.generated_model.losses(self.original_data, self.transformed_data, self.node_mask, self.gating_targets, hard=True)
self.assertEqual(len(c_loss_vals), 4, "Canonical losses should return 4 values")
self.assertEqual(len(g_loss_vals), 4, "Generated losses should return 4 values")
c_emb, c_gloss, c_aloss, c_gacc = c_loss_vals
g_emb, g_gloss, g_aloss, g_gacc = g_loss_vals
self.assert_tensors_close(c_emb, g_emb, "Mismatch in aggregated embedding from losses (hard agg)")
self.assert_tensors_close(c_gloss, g_gloss, "Mismatch in gating loss from losses (hard agg)")
self.assert_tensors_close(c_aloss, g_aloss, "Mismatch in alignment loss from losses (hard agg)")
self.assert_tensors_close(c_gacc, g_gacc, "Mismatch in gating accuracy from losses (hard agg)")
c_loss_vals_soft = self.canonical_model.losses(self.original_data, self.transformed_data, self.node_mask, self.gating_targets, hard=False)
g_loss_vals_soft = self.generated_model.losses(self.original_data, self.transformed_data, self.node_mask, self.gating_targets, hard=False)
c_emb_s, c_gloss_s, c_aloss_s, c_gacc_s = c_loss_vals_soft
g_emb_s, g_gloss_s, g_aloss_s, g_gacc_s = g_loss_vals_soft
self.assert_tensors_close(c_emb_s, g_emb_s, "Mismatch in aggregated embedding from losses (soft agg)")
self.assert_tensors_close(c_gloss_s, g_gloss_s, "Mismatch in gating loss from losses (soft agg)")
self.assert_tensors_close(c_gloss, c_gloss_s, "Canonical gating loss should be independent of 'hard' flag")
self.assert_tensors_close(c_aloss_s, g_aloss_s, "Mismatch in alignment loss from losses (soft agg)")
if __name__ == '__main__':
unittest.main() |