"""Structural diagnostics of the paper's two spectral terms. Checks, per environment, how much the spectral regularizer ||V_hat(s,a)||_H^2 with V_hat(s,a) = E_{s'~P(.|s,a)}[ z(s') ] can actually vary across the available actions. Because the RFF map satisfies ||z(s)||_2 = 1 exactly for every state (z = sqrt(2/D)[cos(.)], so ||z||^2 = (2/D) * sum cos^2 -> 1), the regularizer is *identically 1* whenever the transition kernel is deterministic, and therefore contributes no gradient to the policy. It only becomes informative under environment stochasticity, where ||E[z(s')]||^2 < 1 measures the spread of the outcome distribution. """ 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 analyse(env, rff, n_states=400, rng=None): rng = rng or np.random.RandomState(0) z_norms, energies, spreads = [], [], [] # collect a sample of reachable states by random walks states = [] for _ in range(n_states): s = env.reset() for _ in range(rng.randint(0, 6)): va = env.valid_actions(s) if not va: break s, done = env.step(s, va[rng.randint(len(va))], rng) if done: break if env.valid_actions(s): states.append(s) for s in states: per_action = [] for a in env.valid_actions(s): outs = env.expected_next_encodings(s, a) enc = torch.tensor(np.stack([env.encode(ns) for ns in [o[1] for o in outs]]), device=DEVICE) w = torch.tensor([o[0] for o in outs], device=DEVICE, dtype=torch.float32).unsqueeze(-1) z = rff(enc) z_norms.extend((z ** 2).sum(-1).tolist()) V = (z * w).sum(0) per_action.append(float((V ** 2).sum().item())) if per_action: energies.extend(per_action) spreads.append(max(per_action) - min(per_action)) return { "n_states_probed": len(states), "mean_z_norm_sq": float(np.mean(z_norms)), "std_z_norm_sq": float(np.std(z_norms)), "mean_energy": float(np.mean(energies)), "std_energy": float(np.std(energies)), "mean_across_action_spread": float(np.mean(spreads)) if spreads else 0.0, "max_across_action_spread": float(np.max(spreads)) if spreads else 0.0, } if __name__ == "__main__": out = {} specs = [ ("bitsequence_pfail0.0", ENVS["bitsequence"](length=8, p_fail=0.0)), ("bitsequence_pfail0.9", 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)), ] for name, env in specs: rff = RFF(env.state_dim, D=256, sigma=1.0, seed=0).to(DEVICE) res = analyse(env, rff) out[name] = res print(f"{name:24s} ||z||^2={res['mean_z_norm_sq']:.4f}+-{res['std_z_norm_sq']:.4f} " f"energy={res['mean_energy']:.4f}+-{res['std_energy']:.4f} " f"action-spread mean={res['mean_across_action_spread']:.2e} " f"max={res['max_across_action_spread']:.2e}") with open("../outputs/spectral_diagnostics.json", "w") as f: json.dump(out, f, indent=2) print("\nInterpretation: action-spread ~0 means the spectral regularization term") print("cannot influence the policy in that environment (no gradient signal).")