File size: 8,481 Bytes
d7ff85b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
import unittest
import numpy as np
import types
import torch

# Import target classes from both implementations
from canonical import TAHyper as CanonicalTAHyper
from tahyper import TAHyper as GeneratedTAHyper


def _to_numpy(x):
    """Normalize tensors/lists/scalars to numpy for fair comparison."""
    if torch.is_tensor(x):
        return x.detach().cpu().numpy()
    if isinstance(x, (list, tuple)):
        return np.asarray(x, dtype=np.float64)
    if isinstance(x, (np.ndarray, np.number, float, int)):
        return np.asarray(x, dtype=np.float64)
    try:
        return np.array(x, dtype=np.float64)
    except Exception as e:
        raise AssertionError(f"Unable to convert output to numpy array: {type(x)}: {e}")


def _extract_outputs(output):
    """
    Instruction: forward should return (y, lp_cls_loss). Some implementations may
    return extra values (e.g., (y, rep, p1, loss)). We accept that and extract the
    first as y and the last as loss when length > 2.
    """
    if isinstance(output, (list, tuple)):
        if len(output) == 2:
            y, loss = output
        elif len(output) > 2:
            y, loss = output[0], output[-1]
        else:
            raise AssertionError("`forward` must return at least two values (y, loss)")
    else:
        raise AssertionError("`forward` must return a tuple/list-like (y, loss)")
    return _to_numpy(y), _to_numpy(loss)


def build_args(feat_dim):
    """Construct a minimal args namespace needed by both implementations."""
    return types.SimpleNamespace(
        manifold="PoincareBall",  # or "Hyperboloid"/"Euclidean" depending on your setup
        c=1.0,
        cuda=-1,
        device="cpu",
        feat_dim=feat_dim,
        n_nodes=64,
        model="HGCN",   # must match the encoder name expected in your codebase
        dim=8,
        nout=1,
        dropout=0.0,
        bias=True,
        # Additional attributes needed by HGCN encoder
        num_layers=2,  # Must be > 1 for HGCN
        act="relu",    # Activation function
        use_att=False, # Use attention
        local_agg=False, # Local aggregation
        use_feats=True, # Use features
        pretrained_embeddings=None, # No pretrained embeddings
        n_heads=1,     # Number of attention heads (for GAT)
        alpha=0.2,     # Alpha parameter (for GAT)
    )


def build_idx(adj, t, k=2):
    """
    Build indices for relationship identification: [N, K, 3] as LongTensor
    For each node i, pick up to K rows: (i, same-treat neighbor, diff-treat neighbor).
    Fallbacks keep the test lightweight and always valid.
    """
    n = len(adj)
    all_rows = []
    for i in range(n):
        same = [j for j in range(n) if j != i and adj[i][j] and t[j] == t[i]]
        diff = [j for j in range(n) if j != i and adj[i][j] and t[j] != t[i]]
        if not same:
            same = [i]
        if not diff:
            diff = [(i + 1) % n]
        rows = []
        for kk in range(k):
            rows.append([i, same[kk % len(same)], diff[kk % len(diff)]])
        all_rows.append(rows)
    return torch.tensor(all_rows, dtype=torch.long)


# ----- Small synthetic graphs -----

def small_chain_graph(n=5, d=3, seed=0):
    rng = np.random.RandomState(seed)
    x = torch.tensor(rng.randn(n, d), dtype=torch.float32)
    adj = np.zeros((n, n), dtype=np.int64)
    for i in range(n - 1):
        adj[i, i + 1] = adj[i + 1, i] = 1
    t = np.array([i % 2 for i in range(n)], dtype=np.int64)
    idx = build_idx(adj, t, k=2)
    return x, torch.tensor(adj, dtype=torch.float32), torch.tensor(t, dtype=torch.long), idx


def small_star_graph(n=6, d=4, seed=1):
    rng = np.random.RandomState(seed)
    x = torch.tensor(rng.randn(n, d), dtype=torch.float32)
    adj = np.zeros((n, n), dtype=np.int64)
    for j in range(1, n):
        adj[0, j] = adj[j, 0] = 1
    t = np.array([0] * (n // 2) + [1] * (n - n // 2), dtype=np.int64)
    idx = build_idx(adj, t, k=2)
    return x, torch.tensor(adj, dtype=torch.float32), torch.tensor(t, dtype=torch.long), idx


def single_node_graph(d=2):
    x = torch.tensor([[0.1] * d], dtype=torch.float32)
    adj = torch.tensor([[0]], dtype=torch.float32)
    t = torch.tensor([0], dtype=torch.long)
    idx = torch.tensor([[[0, 0, 0]]], dtype=torch.long)  # [1,1,3]
    return x, adj, t, idx


class TestTAHyperForwardEquivalence(unittest.TestCase):
    def _call_both(self, x, adj, t, idx):
        # Rebuild models per feature dim to keep args.feat_dim consistent with input
        feat_dim = x.shape[1]
        args = build_args(feat_dim)
        can_model = CanonicalTAHyper(args)
        gen_model = GeneratedTAHyper(args)

        # Ensure identical parameters: copy canonical weights into generated
        gen_model.load_state_dict(can_model.state_dict(), strict=False)

        # Ensure CPU for deterministic comparison
        can_model.eval()
        gen_model.eval()

        with torch.no_grad():
            can_out = can_model.forward(x, adj, t, idx)
            gen_out = gen_model.forward(x, adj, t, idx)

        cy, closs = _extract_outputs(can_out)
        gy, gloss = _extract_outputs(gen_out)
        return cy, closs, gy, gloss

    # --- Contract tests (canonical alone) ---
    def test_canonical_output_contract(self):
        for x, adj, t, idx in [
            small_chain_graph(n=5, d=3, seed=0),
            small_star_graph(n=6, d=4, seed=1),
            single_node_graph(d=2),
        ]:
            feat_dim = x.shape[1]
            args = build_args(feat_dim)
            model = CanonicalTAHyper(args).eval()
            with torch.no_grad():
                out = model.forward(x, adj, t, idx)
            y, loss = _extract_outputs(out)
            self.assertEqual(y.ndim, 1, "y must be a 1D array-like of per-node predictions")
            self.assertEqual(len(y), x.shape[0], "y length must equal number of nodes")
            self.assertGreaterEqual(loss.size, 1, "loss must be scalar or vector")

    # --- Equivalence: numeric allclose ---
    def test_equivalence_values_allclose(self):
        for x, adj, t, idx in [
            small_chain_graph(n=5, d=3, seed=0),
            small_star_graph(n=6, d=4, seed=1),
            single_node_graph(d=2),
        ]:
            cy, closs, gy, gloss = self._call_both(x, adj, t, idx)
            np.testing.assert_allclose(
                cy, gy, rtol=1e-5, atol=1e-7,
                err_msg="Predicted factual outcomes differ between canonical and generated implementations.",
            )
            if closs.shape != gloss.shape:
                np.testing.assert_allclose(np.mean(closs), np.mean(gloss), rtol=1e-5, atol=1e-7,
                                           err_msg="Relationship-identification loss differs (after mean reduction).")
            else:
                np.testing.assert_allclose(closs, gloss, rtol=1e-5, atol=1e-7,
                                           err_msg="Relationship-identification loss differs.")

    def test_equivalence_structure(self):
        for x, adj, t, idx in [
            small_chain_graph(n=5, d=3, seed=0),
            small_star_graph(n=6, d=4, seed=1),
            single_node_graph(d=2),
        ]:
            cy, closs, gy, gloss = self._call_both(x, adj, t, idx)
            self.assertEqual(cy.shape, gy.shape, "y shape mismatch between canonical and generated")
            self.assertEqual(closs.ndim, gloss.ndim, "loss dimensionality mismatch")

    def test_edge_case_all_treated(self):
        x, adj, _, idx = small_chain_graph(n=5, d=3, seed=42)
        t = torch.ones(x.shape[0], dtype=torch.long)
        cy, closs, gy, gloss = self._call_both(x, adj, t, idx)
        np.testing.assert_allclose(cy, gy, rtol=1e-5, atol=1e-7)
        if closs.shape != gloss.shape:
            np.testing.assert_allclose(np.mean(closs), np.mean(gloss), rtol=1e-5, atol=1e-7)
        else:
            np.testing.assert_allclose(closs, gloss, rtol=1e-5, atol=1e-7)

    def test_edge_case_all_control(self):
        x, adj, _, idx = small_star_graph(n=6, d=4, seed=24)
        t = torch.zeros(x.shape[0], dtype=torch.long)
        cy, closs, gy, gloss = self._call_both(x, adj, t, idx)
        np.testing.assert_allclose(cy, gy, rtol=1e-5, atol=1e-7)
        if closs.shape != gloss.shape:
            np.testing.assert_allclose(np.mean(closs), np.mean(gloss), rtol=1e-5, atol=1e-7)
        else:
            np.testing.assert_allclose(closs, gloss, rtol=1e-5, atol=1e-7)


if __name__ == "__main__":
    unittest.main()