Add independent theory and local proxy scripts
Browse files- src/reproduce.py +194 -0
- src/train_synthetic.py +170 -0
src/reproduce.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Independent NumPy checks for the WIRE theory claims.
|
| 2 |
+
|
| 3 |
+
The script intentionally has no paper-code dependency. It implements the
|
| 4 |
+
rotation in Eq. (2), computes Laplacian eigenfeatures, and checks the
|
| 5 |
+
permutation/gauge, grid, and effective-resistance statements numerically.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import json
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 17 |
+
RESULTS = ROOT / "results"
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def laplacian(n: int, edges: list[tuple[int, int]]) -> np.ndarray:
|
| 21 |
+
a = np.zeros((n, n), dtype=float)
|
| 22 |
+
for i, j in edges:
|
| 23 |
+
a[i, j] = a[j, i] = 1.0
|
| 24 |
+
return np.diag(a.sum(axis=1)) - a
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def wire_rotate(z: np.ndarray, features: np.ndarray, frequencies: np.ndarray) -> np.ndarray:
|
| 28 |
+
"""Apply block-diagonal RoPE to rows of z using graph features."""
|
| 29 |
+
n, d = z.shape
|
| 30 |
+
assert d % 2 == 0
|
| 31 |
+
angles = features @ frequencies.T
|
| 32 |
+
out = z.copy()
|
| 33 |
+
for block in range(d // 2):
|
| 34 |
+
c = np.cos(angles[:, block])
|
| 35 |
+
s = np.sin(angles[:, block])
|
| 36 |
+
x, y = z[:, 2 * block], z[:, 2 * block + 1]
|
| 37 |
+
out[:, 2 * block] = c * x - s * y
|
| 38 |
+
out[:, 2 * block + 1] = s * x + c * y
|
| 39 |
+
return out
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def spectral_features(l: np.ndarray, m: int, resistance_weighted: bool = False) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
| 43 |
+
eigenvalues, eigenvectors = np.linalg.eigh(l)
|
| 44 |
+
if resistance_weighted:
|
| 45 |
+
features = eigenvectors[:, 1:m] / np.sqrt(eigenvalues[1:m])
|
| 46 |
+
else:
|
| 47 |
+
features = eigenvectors[:, :m]
|
| 48 |
+
return features, eigenvalues, eigenvectors
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def effective_resistance(l: np.ndarray, i: int, j: int) -> float:
|
| 52 |
+
vals, vecs = np.linalg.eigh(l)
|
| 53 |
+
pinv = (vecs[:, 1:] / vals[1:]) @ vecs[:, 1:].T
|
| 54 |
+
return float(pinv[i, i] + pinv[j, j] - 2 * pinv[i, j])
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def check_claim_1(rng: np.random.Generator) -> dict[str, float]:
|
| 58 |
+
n, d, m = 12, 8, 4
|
| 59 |
+
edges = [(i, j) for i in range(n) for j in range(i + 1, n) if rng.random() < 0.22]
|
| 60 |
+
# Ensure a connected-ish graph for stable spectral features.
|
| 61 |
+
edges += [(i, i + 1) for i in range(n - 1)]
|
| 62 |
+
features, _, _ = spectral_features(laplacian(n, edges), m)
|
| 63 |
+
frequencies = rng.normal(0, 0.7, size=(d // 2, m))
|
| 64 |
+
z = rng.normal(size=(n, d))
|
| 65 |
+
rotated = wire_rotate(z, features, frequencies)
|
| 66 |
+
angles = features @ frequencies.T
|
| 67 |
+
block_norm_error = 0.0
|
| 68 |
+
for b in range(d // 2):
|
| 69 |
+
c, s = np.cos(angles[0, b]), np.sin(angles[0, b])
|
| 70 |
+
rot = np.array([[c, -s], [s, c]])
|
| 71 |
+
block_norm_error = max(block_norm_error, abs(np.linalg.det(rot) - 1.0), np.linalg.norm(rot.T @ rot - np.eye(2)))
|
| 72 |
+
return {
|
| 73 |
+
"nodes": float(n),
|
| 74 |
+
"spectral_feature_dim": float(m),
|
| 75 |
+
"angle_std": float(angles.std()),
|
| 76 |
+
"rotation_orthogonality_error": float(block_norm_error),
|
| 77 |
+
"output_finite": float(np.isfinite(rotated).all()),
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def check_claim_2(rng: np.random.Generator) -> dict[str, float]:
|
| 82 |
+
n, d, m = 14, 8, 4
|
| 83 |
+
edges = [(i, i + 1) for i in range(n - 1)] + [(0, 5), (3, 9), (7, 12), (1, 10)]
|
| 84 |
+
l = laplacian(n, edges)
|
| 85 |
+
features, _, u = spectral_features(l, m)
|
| 86 |
+
perm = rng.permutation(n)
|
| 87 |
+
lp = l[np.ix_(perm, perm)]
|
| 88 |
+
fp, _, up = spectral_features(lp, m)
|
| 89 |
+
expected = u[perm, :m]
|
| 90 |
+
signs = np.sign(np.sum(fp * expected, axis=0))
|
| 91 |
+
signs[signs == 0] = 1
|
| 92 |
+
aligned_feature_error = float(np.max(np.abs(fp * signs - expected)))
|
| 93 |
+
z = rng.normal(size=(n, d))
|
| 94 |
+
omega = rng.normal(0, 0.4, size=(d // 2, m))
|
| 95 |
+
# A sign change is absorbed by the corresponding frequency reparameterisation.
|
| 96 |
+
omega_perm = omega * signs[None, :]
|
| 97 |
+
out = wire_rotate(z, features, omega)
|
| 98 |
+
out_perm = wire_rotate(z[perm], fp, omega_perm)
|
| 99 |
+
equivariance_error = float(np.max(np.abs(out[perm] - out_perm)))
|
| 100 |
+
|
| 101 |
+
# A 4-cycle has a repeated Laplacian eigenvalue (the 2-eigenspace).
|
| 102 |
+
cycle_edges = [(0, 1), (1, 2), (2, 3), (3, 0)]
|
| 103 |
+
lc = laplacian(4, cycle_edges)
|
| 104 |
+
_, vals_c, uc = spectral_features(lc, 4)
|
| 105 |
+
p2 = np.array([1, 2, 3, 0])
|
| 106 |
+
_, _, up2 = spectral_features(lc[np.ix_(p2, p2)], 4)
|
| 107 |
+
# Compare subspaces, not individual basis vectors, in the repeated block.
|
| 108 |
+
a, b = uc[p2, 1:3], up2[:, 1:3]
|
| 109 |
+
principal_cosines = np.linalg.svd(a.T @ b, compute_uv=False)
|
| 110 |
+
return {
|
| 111 |
+
"permutation_feature_max_error_after_sign_alignment": aligned_feature_error,
|
| 112 |
+
"permutation_wire_max_error_after_frequency_gauge": equivariance_error,
|
| 113 |
+
"cycle_degenerate_eigenvalue_pair": float(vals_c[1]),
|
| 114 |
+
"cycle_degenerate_subspace_min_cosine": float(principal_cosines.min()),
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def check_claim_3() -> dict[str, float]:
|
| 119 |
+
n = 25
|
| 120 |
+
i = np.arange(n, dtype=float)
|
| 121 |
+
l = laplacian(n, [(k, k + 1) for k in range(n - 1)])
|
| 122 |
+
_, vals, u = spectral_features(l, 2)
|
| 123 |
+
# Theorem 2 uses u_1[i] = -cos((i+1/2) pi / N).
|
| 124 |
+
raw_formula = -np.cos((i + 0.5) * np.pi / n)
|
| 125 |
+
formula_scale = np.linalg.norm(raw_formula)
|
| 126 |
+
formula = raw_formula / formula_scale
|
| 127 |
+
eig_sign = np.sign(np.dot(u[:, 1], formula)) or 1.0
|
| 128 |
+
u1 = eig_sign * u[:, 1]
|
| 129 |
+
formula_error = float(np.max(np.abs(u1 - formula)))
|
| 130 |
+
recovered_position = np.arccos(-(u1 * formula_scale)) * n / np.pi - 0.5
|
| 131 |
+
position_error = float(np.max(np.abs(recovered_position - i)))
|
| 132 |
+
monotone = float(np.all(np.diff(u1) > 0))
|
| 133 |
+
return {
|
| 134 |
+
"path_second_eigenvalue": float(vals[1]),
|
| 135 |
+
"theorem_2_eigenvector_formula_max_error": formula_error,
|
| 136 |
+
"bijective_coordinate_recovery_max_error": position_error,
|
| 137 |
+
"coordinate_monotonicity": monotone,
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def check_claim_4(rng: np.random.Generator) -> dict[str, float]:
|
| 142 |
+
n, d = 10, 12
|
| 143 |
+
edges = [(i, i + 1) for i in range(n - 1)] + [(0, 3), (2, 7), (4, 8), (1, 6)]
|
| 144 |
+
l = laplacian(n, edges)
|
| 145 |
+
features, vals, vecs = spectral_features(l, n, resistance_weighted=True)
|
| 146 |
+
i, j = 1, 8
|
| 147 |
+
resistance = effective_resistance(l, i, j)
|
| 148 |
+
std = 0.08
|
| 149 |
+
q = np.ones(d)
|
| 150 |
+
k = np.ones(d)
|
| 151 |
+
qk = float(q @ k)
|
| 152 |
+
draws = 4096
|
| 153 |
+
scores = np.empty(draws)
|
| 154 |
+
delta = features[i] - features[j]
|
| 155 |
+
for t in range(draws):
|
| 156 |
+
omega = rng.normal(0, std, size=(d // 2, n - 1))
|
| 157 |
+
angles = omega @ delta
|
| 158 |
+
scores[t] = 2 * np.sum(np.cos(angles))
|
| 159 |
+
exact_gaussian = qk * np.exp(-std**2 * resistance / 2)
|
| 160 |
+
first_order = qk * (1 - std**2 * resistance / 2)
|
| 161 |
+
return {
|
| 162 |
+
"effective_resistance": resistance,
|
| 163 |
+
"spectral_resistance_identity_error": abs(resistance - float(delta @ delta)),
|
| 164 |
+
"mc_mean_score": float(scores.mean()),
|
| 165 |
+
"gaussian_expectation": float(exact_gaussian),
|
| 166 |
+
"first_order_prediction": float(first_order),
|
| 167 |
+
"mc_abs_error_to_first_order": float(abs(scores.mean() - first_order)),
|
| 168 |
+
"mc_standard_error": float(scores.std(ddof=1) / np.sqrt(draws)),
|
| 169 |
+
"omega_std": std,
|
| 170 |
+
"nonzero_eigenvalues": float(np.count_nonzero(vals[1:] > 1e-10)),
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def main() -> None:
|
| 175 |
+
rng = np.random.default_rng(18382)
|
| 176 |
+
results = {
|
| 177 |
+
"paper": {
|
| 178 |
+
"title": "Rotary Position Encodings for Graphs",
|
| 179 |
+
"arxiv": "https://huggingface.co/papers/2509.22259",
|
| 180 |
+
"openreview": "https://openreview.net/forum?id=trn64znfNx",
|
| 181 |
+
"reference_code": "https://anonymous.4open.science/r/WIRE_Graphs-4584/",
|
| 182 |
+
},
|
| 183 |
+
"claim_1": check_claim_1(rng),
|
| 184 |
+
"claim_2": check_claim_2(rng),
|
| 185 |
+
"claim_3": check_claim_3(),
|
| 186 |
+
"claim_4": check_claim_4(rng),
|
| 187 |
+
}
|
| 188 |
+
RESULTS.mkdir(parents=True, exist_ok=True)
|
| 189 |
+
(RESULTS / "core_results.json").write_text(json.dumps(results, indent=2) + "\n")
|
| 190 |
+
print(json.dumps(results, indent=2))
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
if __name__ == "__main__":
|
| 194 |
+
main()
|
src/train_synthetic.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Scaled GPU proxy for the paper's monochromatic-subgraph experiment.
|
| 2 |
+
|
| 3 |
+
This is deliberately a small independent implementation: 5x5 grids with
|
| 4 |
+
random edge deletions, node colours, a transformer regressor, and optional
|
| 5 |
+
spectral WIRE rotations in every self-attention layer. It is not claimed to
|
| 6 |
+
reproduce the paper's full 10k/1k, 250-epoch run.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
import random
|
| 14 |
+
import time
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
import torch
|
| 19 |
+
from torch import nn
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
N = 25
|
| 23 |
+
GRID_EDGES = [(r * 5 + c, r * 5 + c + 1) for r in range(5) for c in range(4)]
|
| 24 |
+
GRID_EDGES += [(r * 5 + c, (r + 1) * 5 + c) for r in range(4) for c in range(5)]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def make_dataset(count: int, seed: int, ape_dim: int = 3) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 28 |
+
rng = np.random.default_rng(seed)
|
| 29 |
+
laplacians = np.zeros((count, N, N), dtype=np.float32)
|
| 30 |
+
colours = rng.integers(0, 2, size=(count, N), dtype=np.int64)
|
| 31 |
+
labels = np.zeros(count, dtype=np.float32)
|
| 32 |
+
for b in range(count):
|
| 33 |
+
edges = [e for e in GRID_EDGES if rng.random() > rng.uniform(0.05, 0.45)]
|
| 34 |
+
# Keep the grid backbone connected enough for meaningful low modes.
|
| 35 |
+
a = np.zeros((N, N), dtype=np.float32)
|
| 36 |
+
for i, j in edges:
|
| 37 |
+
a[i, j] = a[j, i] = 1.0
|
| 38 |
+
laplacians[b] = np.diag(a.sum(axis=1)) - a
|
| 39 |
+
seen = np.zeros(N, dtype=bool)
|
| 40 |
+
best = 0
|
| 41 |
+
for start in range(N):
|
| 42 |
+
if seen[start]:
|
| 43 |
+
continue
|
| 44 |
+
colour = colours[b, start]
|
| 45 |
+
stack = [start]
|
| 46 |
+
seen[start] = True
|
| 47 |
+
size = 0
|
| 48 |
+
while stack:
|
| 49 |
+
node = stack.pop()
|
| 50 |
+
size += 1
|
| 51 |
+
for nxt in np.flatnonzero(a[node]):
|
| 52 |
+
if not seen[nxt] and colours[b, nxt] == colour:
|
| 53 |
+
seen[nxt] = True
|
| 54 |
+
stack.append(int(nxt))
|
| 55 |
+
best = max(best, size)
|
| 56 |
+
labels[b] = best / N
|
| 57 |
+
_, vecs = np.linalg.eigh(laplacians)
|
| 58 |
+
# Include low-frequency spectral coordinates as APE inputs for both arms;
|
| 59 |
+
# WIRE uses the same coordinates to generate rotations.
|
| 60 |
+
spectral = vecs[:, :, : max(ape_dim, 3)]
|
| 61 |
+
colour_onehot = np.eye(2, dtype=np.float32)[colours]
|
| 62 |
+
x = np.concatenate([colour_onehot, spectral], axis=-1).astype(np.float32)
|
| 63 |
+
return torch.from_numpy(x), torch.from_numpy(labels), torch.from_numpy(spectral[:, :, :ape_dim].astype(np.float32))
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class WireAttention(nn.Module):
|
| 67 |
+
def __init__(self, d_model: int, heads: int, wire_dim: int):
|
| 68 |
+
super().__init__()
|
| 69 |
+
assert d_model % heads == 0 and (d_model // heads) % 2 == 0
|
| 70 |
+
self.heads = heads
|
| 71 |
+
self.head_dim = d_model // heads
|
| 72 |
+
self.wire_dim = wire_dim
|
| 73 |
+
self.qkv = nn.Linear(d_model, 3 * d_model)
|
| 74 |
+
self.out = nn.Linear(d_model, d_model)
|
| 75 |
+
self.freq = nn.Parameter(torch.randn(heads, self.head_dim // 2, max(wire_dim, 1)) * 0.15)
|
| 76 |
+
|
| 77 |
+
def forward(self, x: torch.Tensor, spectral: torch.Tensor) -> torch.Tensor:
|
| 78 |
+
batch, nodes, d_model = x.shape
|
| 79 |
+
q, k, v = self.qkv(x).chunk(3, dim=-1)
|
| 80 |
+
q = q.view(batch, nodes, self.heads, self.head_dim).transpose(1, 2)
|
| 81 |
+
k = k.view(batch, nodes, self.heads, self.head_dim).transpose(1, 2)
|
| 82 |
+
v = v.view(batch, nodes, self.heads, self.head_dim).transpose(1, 2)
|
| 83 |
+
if self.wire_dim:
|
| 84 |
+
angles = torch.einsum("bnm,hdm->bhnd", spectral[..., : self.wire_dim], self.freq[..., : self.wire_dim])
|
| 85 |
+
def rotate(z: torch.Tensor) -> torch.Tensor:
|
| 86 |
+
z = z.view(batch, self.heads, nodes, self.head_dim // 2, 2)
|
| 87 |
+
c, s = angles.cos(), angles.sin()
|
| 88 |
+
x0, x1 = z[..., 0], z[..., 1]
|
| 89 |
+
return torch.stack([c * x0 - s * x1, s * x0 + c * x1], dim=-1).flatten(-2)
|
| 90 |
+
q, k = rotate(q), rotate(k)
|
| 91 |
+
weights = torch.softmax(q @ k.transpose(-1, -2) / self.head_dim**0.5, dim=-1)
|
| 92 |
+
return self.out((weights @ v).transpose(1, 2).reshape(batch, nodes, d_model))
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class Block(nn.Module):
|
| 96 |
+
def __init__(self, d_model: int, heads: int, wire_dim: int):
|
| 97 |
+
super().__init__()
|
| 98 |
+
self.norm1 = nn.LayerNorm(d_model)
|
| 99 |
+
self.attn = WireAttention(d_model, heads, wire_dim)
|
| 100 |
+
self.norm2 = nn.LayerNorm(d_model)
|
| 101 |
+
self.ff = nn.Sequential(nn.Linear(d_model, 2 * d_model), nn.GELU(), nn.Linear(2 * d_model, d_model))
|
| 102 |
+
|
| 103 |
+
def forward(self, x: torch.Tensor, spectral: torch.Tensor) -> torch.Tensor:
|
| 104 |
+
x = x + self.attn(self.norm1(x), spectral)
|
| 105 |
+
return x + self.ff(self.norm2(x))
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
class GraphTransformer(nn.Module):
|
| 109 |
+
def __init__(self, input_dim: int, wire_dim: int):
|
| 110 |
+
super().__init__()
|
| 111 |
+
self.embed = nn.Linear(input_dim, 32)
|
| 112 |
+
self.blocks = nn.ModuleList([Block(32, 4, wire_dim) for _ in range(2)])
|
| 113 |
+
self.head = nn.Sequential(nn.LayerNorm(32), nn.Linear(32, 1))
|
| 114 |
+
|
| 115 |
+
def forward(self, x: torch.Tensor, spectral: torch.Tensor) -> torch.Tensor:
|
| 116 |
+
h = self.embed(x)
|
| 117 |
+
for block in self.blocks:
|
| 118 |
+
h = block(h, spectral)
|
| 119 |
+
return self.head(h.mean(dim=1)).squeeze(-1)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def train_arm(train: tuple[torch.Tensor, ...], test: tuple[torch.Tensor, ...], wire_dim: int, seed: int, device: torch.device) -> float:
|
| 123 |
+
torch.manual_seed(seed)
|
| 124 |
+
model = GraphTransformer(train[0].shape[-1], wire_dim).to(device)
|
| 125 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=2e-3, weight_decay=1e-4)
|
| 126 |
+
x, y, s = [v.to(device) for v in train]
|
| 127 |
+
xt, yt, st = [v.to(device) for v in test]
|
| 128 |
+
for _ in range(80):
|
| 129 |
+
order = torch.randperm(len(x), device=device)
|
| 130 |
+
for idx in order.split(64):
|
| 131 |
+
pred = model(x[idx], s[idx])
|
| 132 |
+
loss = ((pred - y[idx]) ** 2).mean()
|
| 133 |
+
optimizer.zero_grad(set_to_none=True)
|
| 134 |
+
loss.backward()
|
| 135 |
+
optimizer.step()
|
| 136 |
+
model.eval()
|
| 137 |
+
with torch.no_grad():
|
| 138 |
+
rmse = float(torch.sqrt(((model(xt, st) - yt) ** 2).mean()).cpu())
|
| 139 |
+
return rmse
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def main() -> None:
|
| 143 |
+
start = time.time()
|
| 144 |
+
random.seed(18382)
|
| 145 |
+
np.random.seed(18382)
|
| 146 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 147 |
+
train = make_dataset(1600, 18382)
|
| 148 |
+
test = make_dataset(400, 19382)
|
| 149 |
+
results = {
|
| 150 |
+
"paper": "https://huggingface.co/papers/2509.22259",
|
| 151 |
+
"job_proxy": "monochromatic-subgraph; 1,600/400 graphs vs paper 10,000/1,000; 80 vs 250 epochs; 2-layer 32d model vs 4-layer 32d; 2 seeds",
|
| 152 |
+
"device": str(device),
|
| 153 |
+
"baseline_rmse": [],
|
| 154 |
+
"wire_rmse": [],
|
| 155 |
+
}
|
| 156 |
+
for seed in (0, 1):
|
| 157 |
+
results["baseline_rmse"].append(train_arm(train, test, 0, seed, device))
|
| 158 |
+
results["wire_rmse"].append(train_arm(train, test, 3, seed, device))
|
| 159 |
+
results["baseline_mean"] = float(np.mean(results["baseline_rmse"]))
|
| 160 |
+
results["wire_mean"] = float(np.mean(results["wire_rmse"]))
|
| 161 |
+
results["relative_rmse_change_pct"] = 100 * (results["wire_mean"] / results["baseline_mean"] - 1)
|
| 162 |
+
results["wall_seconds"] = time.time() - start
|
| 163 |
+
out_dir = Path("/data") if Path("/data").exists() else Path(".")
|
| 164 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 165 |
+
(out_dir / "synthetic_results.json").write_text(json.dumps(results, indent=2) + "\n")
|
| 166 |
+
print(json.dumps(results, indent=2))
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
if __name__ == "__main__":
|
| 170 |
+
main()
|