stgfn-repro-code / rff_error.py
Gonzalez
Upload folder using huggingface_hub
a76f68a verified
Raw
History Blame Contribute Delete
3.21 kB
"""Check the RFF kernel-approximation claim (App C.1.3 / Prop. 1).
The paper states: "RFF Parameters: D = 256 frequencies, Gaussian kernel
k(s,s') = exp(-||s-s'||^2 / 2 sigma^2) with scale sigma = 1.0. Approximation
error < 0.02 (validated empirically, consistent with O(1/sqrt(D)) theory)."
We measure |z(x)^T z(y) - k(x,y)| over state pairs actually drawn from each
environment, sweeping D, and check both the magnitude and the 1/sqrt(D) rate.
"""
from __future__ import annotations
import json
import numpy as np
import torch
from envs import ENVS
from models import RFF
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def sample_states(env, n, rng):
out = []
while len(out) < n:
s = env.reset()
for _ in range(rng.randint(0, 8)):
va = env.valid_actions(s)
if not va:
break
s, done = env.step(s, va[rng.randint(len(va))], rng)
if done:
break
out.append(env.encode(s))
return np.stack(out)
if __name__ == "__main__":
rng = np.random.RandomState(0)
sigma = 1.0
envs = {
"bitsequence": ENVS["bitsequence"](length=8, p_fail=0.9),
"hypergrid": ENVS["hypergrid"](size=32, period=4),
"tictactoe": ENVS["tictactoe"](opp_optimal_prob=0.9),
"singlecell_proxy": ENVS["singlecell_proxy"](n_genes=24, k=3),
}
out = {}
print(f"Mean |z(x)ᵀz(y) − k(x,y)| over 400 sampled states (79,800 pairs), σ={sigma}")
print(f"{'environment':20s}" + "".join(f"{'D='+str(d):>11s}" for d in [64, 128, 256, 512, 1024]))
for name, env in envs.items():
X = torch.tensor(sample_states(env, 400, rng), device=DEVICE)
d2 = torch.cdist(X, X) ** 2
K = torch.exp(-d2 / (2 * sigma ** 2))
iu = torch.triu_indices(len(X), len(X), offset=1)
row, errs = [], {}
for D in [64, 128, 256, 512, 1024]:
# average several RFF draws so the number is not one lucky seed
vals = []
for seed in range(5):
rff = RFF(X.shape[1], D=D, sigma=sigma, seed=seed).to(DEVICE)
Z = rff(X)
approx = Z @ Z.T
e = (approx - K)[iu[0], iu[1]].abs()
vals.append(float(e.mean().item()))
errs[D] = float(np.mean(vals))
row.append(f"{errs[D]:11.4f}")
out[name] = errs
print(f"{name:20s}" + "".join(row))
# verify the O(1/sqrt(D)) rate: error should halve when D quadruples
print("\nrate check — error(D) * sqrt(D) should be roughly constant:")
print(f"{'environment':20s}" + "".join(f"{'D='+str(d):>11s}" for d in [64, 256, 1024]))
for name, errs in out.items():
print(f"{name:20s}" + "".join(f"{errs[d]*np.sqrt(d):11.3f}" for d in [64, 256, 1024]))
at256 = {k: v[256] for k, v in out.items()}
print(f"\nPaper claims approximation error < 0.02 at D = 256.")
print(f"Measured at D = 256: {min(at256.values()):.4f}{max(at256.values()):.4f}"
f" ({'consistent' if max(at256.values()) < 0.02 else 'ABOVE the stated bound'})")
with open("../outputs/rff_error.json", "w") as f:
json.dump(out, f, indent=2)