File size: 3,213 Bytes
a76f68a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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)