wire-repro-code / src /reproduce.py
Hrushi's picture
Add independent theory and local proxy scripts
b7338a5 verified
Raw
History Blame Contribute Delete
7.55 kB
"""Independent NumPy checks for the WIRE theory claims.
The script intentionally has no paper-code dependency. It implements the
rotation in Eq. (2), computes Laplacian eigenfeatures, and checks the
permutation/gauge, grid, and effective-resistance statements numerically.
"""
from __future__ import annotations
import json
from pathlib import Path
import numpy as np
ROOT = Path(__file__).resolve().parents[1]
RESULTS = ROOT / "results"
def laplacian(n: int, edges: list[tuple[int, int]]) -> np.ndarray:
a = np.zeros((n, n), dtype=float)
for i, j in edges:
a[i, j] = a[j, i] = 1.0
return np.diag(a.sum(axis=1)) - a
def wire_rotate(z: np.ndarray, features: np.ndarray, frequencies: np.ndarray) -> np.ndarray:
"""Apply block-diagonal RoPE to rows of z using graph features."""
n, d = z.shape
assert d % 2 == 0
angles = features @ frequencies.T
out = z.copy()
for block in range(d // 2):
c = np.cos(angles[:, block])
s = np.sin(angles[:, block])
x, y = z[:, 2 * block], z[:, 2 * block + 1]
out[:, 2 * block] = c * x - s * y
out[:, 2 * block + 1] = s * x + c * y
return out
def spectral_features(l: np.ndarray, m: int, resistance_weighted: bool = False) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
eigenvalues, eigenvectors = np.linalg.eigh(l)
if resistance_weighted:
features = eigenvectors[:, 1:m] / np.sqrt(eigenvalues[1:m])
else:
features = eigenvectors[:, :m]
return features, eigenvalues, eigenvectors
def effective_resistance(l: np.ndarray, i: int, j: int) -> float:
vals, vecs = np.linalg.eigh(l)
pinv = (vecs[:, 1:] / vals[1:]) @ vecs[:, 1:].T
return float(pinv[i, i] + pinv[j, j] - 2 * pinv[i, j])
def check_claim_1(rng: np.random.Generator) -> dict[str, float]:
n, d, m = 12, 8, 4
edges = [(i, j) for i in range(n) for j in range(i + 1, n) if rng.random() < 0.22]
# Ensure a connected-ish graph for stable spectral features.
edges += [(i, i + 1) for i in range(n - 1)]
features, _, _ = spectral_features(laplacian(n, edges), m)
frequencies = rng.normal(0, 0.7, size=(d // 2, m))
z = rng.normal(size=(n, d))
rotated = wire_rotate(z, features, frequencies)
angles = features @ frequencies.T
block_norm_error = 0.0
for b in range(d // 2):
c, s = np.cos(angles[0, b]), np.sin(angles[0, b])
rot = np.array([[c, -s], [s, c]])
block_norm_error = max(block_norm_error, abs(np.linalg.det(rot) - 1.0), np.linalg.norm(rot.T @ rot - np.eye(2)))
return {
"nodes": float(n),
"spectral_feature_dim": float(m),
"angle_std": float(angles.std()),
"rotation_orthogonality_error": float(block_norm_error),
"output_finite": float(np.isfinite(rotated).all()),
}
def check_claim_2(rng: np.random.Generator) -> dict[str, float]:
n, d, m = 14, 8, 4
edges = [(i, i + 1) for i in range(n - 1)] + [(0, 5), (3, 9), (7, 12), (1, 10)]
l = laplacian(n, edges)
features, _, u = spectral_features(l, m)
perm = rng.permutation(n)
lp = l[np.ix_(perm, perm)]
fp, _, up = spectral_features(lp, m)
expected = u[perm, :m]
signs = np.sign(np.sum(fp * expected, axis=0))
signs[signs == 0] = 1
aligned_feature_error = float(np.max(np.abs(fp * signs - expected)))
z = rng.normal(size=(n, d))
omega = rng.normal(0, 0.4, size=(d // 2, m))
# A sign change is absorbed by the corresponding frequency reparameterisation.
omega_perm = omega * signs[None, :]
out = wire_rotate(z, features, omega)
out_perm = wire_rotate(z[perm], fp, omega_perm)
equivariance_error = float(np.max(np.abs(out[perm] - out_perm)))
# A 4-cycle has a repeated Laplacian eigenvalue (the 2-eigenspace).
cycle_edges = [(0, 1), (1, 2), (2, 3), (3, 0)]
lc = laplacian(4, cycle_edges)
_, vals_c, uc = spectral_features(lc, 4)
p2 = np.array([1, 2, 3, 0])
_, _, up2 = spectral_features(lc[np.ix_(p2, p2)], 4)
# Compare subspaces, not individual basis vectors, in the repeated block.
a, b = uc[p2, 1:3], up2[:, 1:3]
principal_cosines = np.linalg.svd(a.T @ b, compute_uv=False)
return {
"permutation_feature_max_error_after_sign_alignment": aligned_feature_error,
"permutation_wire_max_error_after_frequency_gauge": equivariance_error,
"cycle_degenerate_eigenvalue_pair": float(vals_c[1]),
"cycle_degenerate_subspace_min_cosine": float(principal_cosines.min()),
}
def check_claim_3() -> dict[str, float]:
n = 25
i = np.arange(n, dtype=float)
l = laplacian(n, [(k, k + 1) for k in range(n - 1)])
_, vals, u = spectral_features(l, 2)
# Theorem 2 uses u_1[i] = -cos((i+1/2) pi / N).
raw_formula = -np.cos((i + 0.5) * np.pi / n)
formula_scale = np.linalg.norm(raw_formula)
formula = raw_formula / formula_scale
eig_sign = np.sign(np.dot(u[:, 1], formula)) or 1.0
u1 = eig_sign * u[:, 1]
formula_error = float(np.max(np.abs(u1 - formula)))
recovered_position = np.arccos(-(u1 * formula_scale)) * n / np.pi - 0.5
position_error = float(np.max(np.abs(recovered_position - i)))
monotone = float(np.all(np.diff(u1) > 0))
return {
"path_second_eigenvalue": float(vals[1]),
"theorem_2_eigenvector_formula_max_error": formula_error,
"bijective_coordinate_recovery_max_error": position_error,
"coordinate_monotonicity": monotone,
}
def check_claim_4(rng: np.random.Generator) -> dict[str, float]:
n, d = 10, 12
edges = [(i, i + 1) for i in range(n - 1)] + [(0, 3), (2, 7), (4, 8), (1, 6)]
l = laplacian(n, edges)
features, vals, vecs = spectral_features(l, n, resistance_weighted=True)
i, j = 1, 8
resistance = effective_resistance(l, i, j)
std = 0.08
q = np.ones(d)
k = np.ones(d)
qk = float(q @ k)
draws = 4096
scores = np.empty(draws)
delta = features[i] - features[j]
for t in range(draws):
omega = rng.normal(0, std, size=(d // 2, n - 1))
angles = omega @ delta
scores[t] = 2 * np.sum(np.cos(angles))
exact_gaussian = qk * np.exp(-std**2 * resistance / 2)
first_order = qk * (1 - std**2 * resistance / 2)
return {
"effective_resistance": resistance,
"spectral_resistance_identity_error": abs(resistance - float(delta @ delta)),
"mc_mean_score": float(scores.mean()),
"gaussian_expectation": float(exact_gaussian),
"first_order_prediction": float(first_order),
"mc_abs_error_to_first_order": float(abs(scores.mean() - first_order)),
"mc_standard_error": float(scores.std(ddof=1) / np.sqrt(draws)),
"omega_std": std,
"nonzero_eigenvalues": float(np.count_nonzero(vals[1:] > 1e-10)),
}
def main() -> None:
rng = np.random.default_rng(18382)
results = {
"paper": {
"title": "Rotary Position Encodings for Graphs",
"arxiv": "https://huggingface.co/papers/2509.22259",
"openreview": "https://openreview.net/forum?id=trn64znfNx",
"reference_code": "https://anonymous.4open.science/r/WIRE_Graphs-4584/",
},
"claim_1": check_claim_1(rng),
"claim_2": check_claim_2(rng),
"claim_3": check_claim_3(),
"claim_4": check_claim_4(rng),
}
RESULTS.mkdir(parents=True, exist_ok=True)
(RESULTS / "core_results.json").write_text(json.dumps(results, indent=2) + "\n")
print(json.dumps(results, indent=2))
if __name__ == "__main__":
main()