| """Training loop for ST-GFN and 10 baselines across 4 environments. |
| |
| Vectorized rollouts: all B trajectories in a batch advance together so each |
| timestep costs one network forward pass. |
| |
| Methods implemented (paper Sec. 4 / App. C.1.1): |
| Standard GFlowNets : tb, fm, subtb, db |
| Stochastic GFlowNets : eflownet, stochastic_gfn |
| Exploration-enhanced : tb_rnd, tb_novelty, tb_icm, tb_cv |
| Ours : stgfn (+ ablations stgfn_no_spectral, stgfn_no_intrinsic) |
| """ |
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import math |
| import os |
| import time |
| from collections import defaultdict |
|
|
| import numpy as np |
| import torch |
| import torch.nn.functional as F |
|
|
| from envs import ENVS |
| from models import RFF, GFNNet, RNDNet, ICMNet, AutocorrIntrinsic |
|
|
| DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
|
|
| MAX_T = {"bitsequence": 8, "hypergrid": 70, "tictactoe": 9, "singlecell_proxy": 3} |
|
|
|
|
| def max_horizon(env_name, cfg): |
| """Longest possible trajectory, so rollouts are never truncated. |
| |
| HyperGrid needs 2*(size-1) moves to reach the far corner plus one stop |
| action; a fixed cap silently truncates trajectories on larger grids and |
| quietly corrupts every terminal-state metric. |
| """ |
| if env_name == "hypergrid": |
| return 2 * (cfg["grid_size"] - 1) + 2 |
| if env_name == "bitsequence": |
| return cfg["bit_length"] |
| if env_name == "singlecell_proxy": |
| return cfg["k_genes"] |
| return MAX_T[env_name] |
|
|
|
|
| def backward_mask(env, state, n_actions): |
| """Actions that could have produced `state` from a valid parent. |
| |
| A mask with a single entry means the state has a unique parent, so |
| log P_B(parent|state) = 0 and the backward term drops out of the TB |
| residual. Getting this right matters: marking every action as a possible |
| parent lets the learned P_B cancel P_F in the residual, which silently |
| removes all reward signal from the objective. |
| """ |
| m = np.zeros(n_actions, dtype=np.float32) |
| if env.name == "hypergrid": |
| x, y, stopped = state |
| if stopped: |
| m[2] = 1 |
| return m |
| if x > 0: |
| m[0] = 1 |
| if y > 0: |
| m[1] = 1 |
| if m.sum() == 0: |
| m[2] = 1 |
| elif env.name == "singlecell_proxy": |
| for g in state: |
| m[g] = 1 |
| if m.sum() == 0: |
| m[0] = 1 |
| else: |
| m[0] = 1 |
| return m |
|
|
|
|
| def forward_mask(env, state, n_actions): |
| m = np.zeros(n_actions, dtype=np.float32) |
| for a in env.valid_actions(state): |
| m[a] = 1 |
| return m |
|
|
|
|
| def masked_log_softmax(logits, mask): |
| logits = logits.masked_fill(mask < 0.5, -1e9) |
| return F.log_softmax(logits, dim=-1) |
|
|
|
|
| class Trainer: |
| def __init__(self, env_name, method, seed, cfg): |
| self.cfg = cfg |
| self.method = method |
| self.env_name = env_name |
| self.seed = seed |
| torch.manual_seed(seed) |
| np.random.seed(seed) |
| self.rng = np.random.RandomState(seed) |
|
|
| env_kwargs = {} |
| if env_name == "bitsequence": |
| env_kwargs = dict(length=cfg["bit_length"], p_fail=cfg["p_fail"]) |
| elif env_name == "hypergrid": |
| env_kwargs = dict(size=cfg["grid_size"], period=cfg["period"]) |
| elif env_name == "tictactoe": |
| env_kwargs = dict(opp_optimal_prob=cfg["opp_optimal"]) |
| elif env_name == "singlecell_proxy": |
| env_kwargs = dict(n_genes=cfg["n_genes"], k=cfg["k_genes"]) |
| self.env = ENVS[env_name](**env_kwargs) |
|
|
| self.max_t = max_horizon(env_name, cfg) |
| self.model = GFNNet(self.env.state_dim, self.env.n_actions, self.max_t).to(DEVICE) |
| |
| |
| policy_params = [p for n, p in self.model.named_parameters() if n != "logZ"] |
| self.opt = torch.optim.Adam( |
| [ |
| {"params": policy_params, "lr": cfg["lr"]}, |
| {"params": [self.model.logZ], "lr": cfg["lr_logz"]}, |
| ] |
| ) |
|
|
| self.rff = RFF(self.env.state_dim, D=cfg["rff_dim"], sigma=cfg["rff_sigma"], seed=seed).to(DEVICE) |
|
|
| |
| self.theta_lambda = torch.tensor( |
| [math.log(cfg["lambda_init"])], device=DEVICE, requires_grad=True |
| ) |
| self.opt_lambda = torch.optim.Adam([self.theta_lambda], lr=cfg["lr_lambda"]) |
|
|
| self.rnd = RNDNet(self.env.state_dim, seed=seed).to(DEVICE) if method == "tb_rnd" else None |
| if self.rnd: |
| self.opt_rnd = torch.optim.Adam(self.rnd.pred.parameters(), lr=cfg["lr"]) |
| self.icm = ICMNet(self.env.state_dim, self.env.n_actions).to(DEVICE) if method == "tb_icm" else None |
| if self.icm: |
| self.opt_icm = torch.optim.Adam(self.icm.parameters(), lr=cfg["lr"]) |
|
|
| self.visit_counts = defaultdict(int) |
| self.use_intrinsic = method in ("stgfn", "stgfn_no_spectral") |
| self.use_spectral = method in ("stgfn", "stgfn_no_intrinsic") |
| self.ac = AutocorrIntrinsic(k_max=cfg["k_max"], alpha=cfg["ac_alpha"], |
| mode=cfg["ac_weight_mode"]) |
|
|
| self.cv_baseline = 0.0 |
|
|
| |
| self.seen_terminals = set() |
| self.seen_modes = set() |
| self.history = defaultdict(list) |
| self.total_env_steps = 0 |
| self.grad_norms = [] |
| self.last_acf = None |
| self.last_weights = None |
|
|
| |
| def rollout(self, B, epsilon): |
| env = self.env |
| states = [env.reset() for _ in range(B)] |
| alive = list(range(B)) |
| traj = [ |
| {"s": [states[i]], "a": [], "t": [], "raw_r": [], "ac_r": []} for i in range(B) |
| ] |
| self.ac.reset() |
| per_traj_ac = [AutocorrIntrinsic(self.cfg["k_max"], self.cfg["ac_alpha"], |
| mode=self.cfg["ac_weight_mode"]) for _ in range(B)] |
|
|
| for t in range(self.max_t): |
| if not alive: |
| break |
| enc = torch.tensor( |
| np.stack([env.encode(states[i]) for i in alive]), device=DEVICE |
| ) |
| tt = torch.full((len(alive),), t, dtype=torch.long, device=DEVICE) |
| with torch.no_grad(): |
| pf_logits, _, _ = self.model(enc, tt) |
| fmask = torch.tensor( |
| np.stack([forward_mask(env, states[i], env.n_actions) for i in alive]), |
| device=DEVICE, |
| ) |
| logp = masked_log_softmax(pf_logits, fmask) |
| probs = logp.exp() |
|
|
| |
| unif = fmask / fmask.sum(dim=-1, keepdim=True).clamp(min=1e-9) |
| mix = (1 - epsilon) * probs + epsilon * unif |
| mix = mix / mix.sum(dim=-1, keepdim=True).clamp(min=1e-9) |
| actions = torch.multinomial(mix, 1).squeeze(-1).cpu().numpy() |
|
|
| next_alive = [] |
| for j, i in enumerate(alive): |
| a = int(actions[j]) |
| s = states[i] |
| ns, done = env.step(s, a, self.rng) |
| self.total_env_steps += 1 |
| self.visit_counts[ns] += 1 |
| |
| |
| |
| |
| if self.cfg["ac_signal"] == "reward": |
| raw = float(env.reward(ns)) |
| else: |
| raw = 1.0 / math.sqrt(self.visit_counts[ns]) |
| ac_val = per_traj_ac[j].update(raw) if self.use_intrinsic else 0.0 |
| traj[i]["a"].append(a) |
| traj[i]["t"].append(t) |
| traj[i]["s"].append(ns) |
| traj[i]["raw_r"].append(raw) |
| traj[i]["ac_r"].append(ac_val) |
| states[i] = ns |
| if not done and env.valid_actions(ns): |
| next_alive.append(i) |
| alive = next_alive |
| |
| |
| if self.use_intrinsic: |
| acfs = np.stack([a.acf for a in per_traj_ac]) |
| self.last_acf = acfs.mean(0) |
| self.last_weights = np.stack([a.weights for a in per_traj_ac]).mean(0) |
| return traj, states |
|
|
| |
| def spectral_terms(self, states_list, t_list, pf_logp, pb_logp, sampled_actions): |
| """Returns (consistency_loss, reg_energy) per the Unified Spectral Loss. |
| |
| P_hat(s,t) = E_{a~P}[ E_{s'~P_env(.|s,a)}[ z(s') ] ] |
| V_hat(s,a) = E_{s'~P_env(.|s,a)}[ z(s') ] |
| """ |
| env = self.env |
| flat_enc, owner_sa, out_prob = [], [], [] |
| sa_index = {} |
| sa_list = [] |
| for i, (s, _) in enumerate(zip(states_list, t_list)): |
| for a in env.valid_actions(s): |
| sa_index[(i, a)] = len(sa_list) |
| sa_list.append((i, a)) |
| for p, ns in env.expected_next_encodings(s, a): |
| flat_enc.append(env.encode(ns)) |
| owner_sa.append(sa_index[(i, a)]) |
| out_prob.append(p) |
| if not flat_enc: |
| z = torch.zeros(1, device=DEVICE) |
| return z.sum(), z.sum() |
|
|
| enc_t = torch.tensor(np.stack(flat_enc), device=DEVICE) |
| z = self.rff(enc_t) |
| owner = torch.tensor(owner_sa, device=DEVICE) |
| w = torch.tensor(out_prob, device=DEVICE, dtype=torch.float32).unsqueeze(-1) |
| n_sa = len(sa_list) |
| V_hat = torch.zeros(n_sa, z.shape[1], device=DEVICE).index_add_(0, owner, z * w) |
|
|
| |
| n_states = len(states_list) |
| PF = torch.zeros(n_states, z.shape[1], device=DEVICE) |
| PB = torch.zeros(n_states, z.shape[1], device=DEVICE) |
| idx_state = torch.tensor([i for (i, a) in sa_list], device=DEVICE) |
| act_idx = torch.tensor([a for (i, a) in sa_list], device=DEVICE) |
| pf_w = pf_logp.exp()[idx_state, act_idx].unsqueeze(-1) |
| pb_w = pb_logp.exp()[idx_state, act_idx].unsqueeze(-1) |
| PF = PF.index_add_(0, idx_state, V_hat * pf_w) |
| PB = PB.index_add_(0, idx_state, V_hat * pb_w) |
|
|
| consistency = ((PF - PB) ** 2).sum(-1).mean() |
|
|
| |
| |
| |
| |
| energy = (V_hat ** 2).sum(-1) |
| pf_sel = pf_logp.exp()[idx_state, act_idx] |
| reg_per_state = torch.zeros(n_states, device=DEVICE).index_add_( |
| 0, idx_state, energy * pf_sel |
| ) |
| reg = reg_per_state.mean() |
| self.last_energy_spread = float( |
| (energy.max() - energy.min()).item() |
| ) if energy.numel() else 0.0 |
| return consistency, reg |
|
|
| |
| def compute_loss(self, traj, finals): |
| env = self.env |
| cfg = self.cfg |
| method = self.method |
|
|
| flat_s, flat_t, flat_a, flat_next_s, traj_id = [], [], [], [], [] |
| for i, tr in enumerate(traj): |
| for j, a in enumerate(tr["a"]): |
| flat_s.append(tr["s"][j]) |
| flat_t.append(tr["t"][j]) |
| flat_a.append(a) |
| flat_next_s.append(tr["s"][j + 1]) |
| traj_id.append(i) |
| if not flat_s: |
| return None, {} |
|
|
| enc = torch.tensor(np.stack([env.encode(s) for s in flat_s]), device=DEVICE) |
| enc_next = torch.tensor(np.stack([env.encode(s) for s in flat_next_s]), device=DEVICE) |
| tt = torch.tensor(flat_t, dtype=torch.long, device=DEVICE) |
| at = torch.tensor(flat_a, dtype=torch.long, device=DEVICE) |
| tid = torch.tensor(traj_id, dtype=torch.long, device=DEVICE) |
|
|
| pf_logits, pb_logits, logF = self.model(enc, tt) |
| fmask = torch.tensor( |
| np.stack([forward_mask(env, s, env.n_actions) for s in flat_s]), device=DEVICE |
| ) |
| pf_logp_full = masked_log_softmax(pf_logits, fmask) |
| pf_logp = pf_logp_full.gather(1, at.unsqueeze(1)).squeeze(1) |
|
|
| bmask = torch.tensor( |
| np.stack([backward_mask(env, s, env.n_actions) for s in flat_next_s]), device=DEVICE |
| ) |
| _, pb_logits_next, logF_next = self.model(enc_next, (tt + 1).clamp(max=self.max_t)) |
| pb_logp_full = masked_log_softmax(pb_logits_next, bmask) |
| multi_parent = bmask.sum(-1) > 1 |
| pb_logp = torch.where( |
| multi_parent, |
| pb_logp_full.gather(1, at.unsqueeze(1)).squeeze(1), |
| torch.zeros_like(pf_logp), |
| ) |
|
|
| |
| R = torch.tensor( |
| [max(env.reward(s), 1e-8) for s in finals], device=DEVICE, dtype=torch.float32 |
| ) |
| logR = R.clamp(min=1e-8).log() |
| if self.use_intrinsic: |
| |
| |
| |
| bonus = torch.tensor( |
| [float(np.mean(tr["ac_r"])) if tr["ac_r"] else 0.0 for tr in traj], |
| device=DEVICE, |
| ) |
| logR = logR + cfg["beta"] * bonus / (bonus.abs().mean() + 1e-8) |
|
|
| |
| if method == "tb_rnd": |
| b = self.rnd.bonus(enc_next) |
| rnd_loss = b.mean() |
| per_traj = torch.zeros(len(traj), device=DEVICE).index_add_(0, tid, b.detach()) |
| logR = logR + cfg["beta"] * per_traj / (per_traj.abs().mean() + 1e-8) |
| self.opt_rnd.zero_grad(); rnd_loss.backward(); self.opt_rnd.step() |
| elif method == "tb_novelty": |
| nov = torch.tensor( |
| [1.0 / math.sqrt(self.visit_counts[s]) for s in flat_next_s], device=DEVICE |
| ) |
| per_traj = torch.zeros(len(traj), device=DEVICE).index_add_(0, tid, nov) |
| logR = logR + cfg["beta"] * per_traj / (per_traj.abs().mean() + 1e-8) |
| elif method == "tb_icm": |
| e = self.icm.error(enc, at, enc_next) |
| icm_loss = e.mean() |
| per_traj = torch.zeros(len(traj), device=DEVICE).index_add_(0, tid, e.detach()) |
| logR = logR + cfg["beta"] * per_traj / (per_traj.abs().mean() + 1e-8) |
| self.opt_icm.zero_grad(); icm_loss.backward(); self.opt_icm.step() |
|
|
| n_traj = len(traj) |
| sum_pf = torch.zeros(n_traj, device=DEVICE).index_add_(0, tid, pf_logp) |
| sum_pb = torch.zeros(n_traj, device=DEVICE).index_add_(0, tid, pb_logp) |
|
|
| metrics = {} |
| |
| if method in ("tb", "tb_rnd", "tb_novelty", "tb_icm", "tb_cv", "stgfn", |
| "stgfn_no_spectral", "stgfn_no_intrinsic", "eflownet", |
| "stochastic_gfn"): |
| resid = self.model.logZ + sum_pf - sum_pb - logR |
| if method == "tb_cv": |
| |
| self.cv_baseline = 0.9 * self.cv_baseline + 0.1 * resid.mean().item() |
| resid = resid - self.cv_baseline |
| if method == "eflownet": |
| |
| |
| loss = F.huber_loss(resid, torch.zeros_like(resid), delta=1.0) |
| elif method == "stochastic_gfn": |
| |
| |
| loss = (resid ** 2).mean() + 0.1 * (logF - logF.detach().mean()).pow(2).mean() |
| else: |
| loss = (resid ** 2).mean() |
| elif method in ("db", "fm"): |
| is_term = torch.tensor( |
| [0.0 if env.valid_actions(s) else 1.0 for s in flat_next_s], |
| device=DEVICE, |
| ) |
| logR_next = torch.tensor( |
| [math.log(max(env.reward(s), 1e-8)) if not env.valid_actions(s) else 0.0 |
| for s in flat_next_s], |
| device=DEVICE, |
| ) |
| |
| |
| target = torch.where(is_term > 0.5, logR_next, logF_next) |
| if method == "db": |
| loss = ((logF + pf_logp - target - pb_logp) ** 2).mean() |
| else: |
| loss = ((logF + pf_logp - target) ** 2).mean() |
| elif method == "subtb": |
| |
| resid_full = self.model.logZ + sum_pf - sum_pb - logR |
| step_resid = logF + pf_logp - logF_next - pb_logp |
| loss = (resid_full ** 2).mean() + cfg["subtb_lambda"] * (step_resid ** 2).mean() |
| else: |
| raise ValueError(method) |
|
|
| |
| if self.use_spectral: |
| |
| |
| |
| |
| pb_succ_logp = masked_log_softmax(pb_logits, fmask) |
| cons, reg = self.spectral_terms(flat_s, flat_t, pf_logp_full, pb_succ_logp, flat_a) |
| lam = self.theta_lambda.exp() |
| loss = loss + cfg["w_consistency"] * cons + lam.detach() * reg |
| metrics["spectral_consistency"] = float(cons.item()) |
| metrics["spectral_energy"] = float(reg.item()) |
| metrics["lambda"] = float(lam.item()) |
| self._pending_meta = (reg.detach(),) |
| else: |
| self._pending_meta = None |
|
|
| metrics["loss"] = float(loss.item()) |
| metrics["logZ"] = float(self.model.logZ.item()) |
| return loss, metrics |
|
|
| def step(self, B, epsilon): |
| traj, finals = self.rollout(B, epsilon) |
| loss, metrics = self.compute_loss(traj, finals) |
| if loss is None: |
| return {}, traj, finals |
| self.opt.zero_grad() |
| loss.backward() |
| gn = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.cfg["grad_clip"]) |
| self.grad_norms.append(float(gn)) |
| self.opt.step() |
|
|
| |
| if self._pending_meta is not None: |
| (reg_val,) = self._pending_meta |
| lam = self.theta_lambda.exp() |
| meta = (lam * reg_val - self.cfg["v_target"]) ** 2 |
| self.opt_lambda.zero_grad() |
| meta.backward() |
| self.opt_lambda.step() |
| with torch.no_grad(): |
| self.theta_lambda.clamp_(math.log(1e-4), math.log(10.0)) |
| return metrics, traj, finals |
|
|
|
|
| def evaluate(trainer, n_samples=2048): |
| """Draw on-policy samples and compute the paper's reported metrics.""" |
| env = trainer.env |
| B = 256 |
| rewards, terminals = [], [] |
| for _ in range(max(1, n_samples // B)): |
| traj, finals = trainer.rollout(B, epsilon=0.0) |
| for s in finals: |
| rewards.append(env.reward(s)) |
| terminals.append(s) |
| rewards = np.array(rewards) |
| out = {} |
| k = min(100, len(rewards)) |
| top = np.sort(rewards)[-k:] |
| rmax = { |
| "bitsequence": 10.1, |
| "hypergrid": 10.0, |
| "tictactoe": 5.0, |
| "singlecell_proxy": None, |
| }[env.name] |
| if rmax is None: |
| rmax = max(rewards.max(), 1e-8) |
| out["top100_reward"] = float(top.mean() / rmax) |
| out["mean_reward"] = float(rewards.mean() / rmax) |
| uniq = set(terminals) |
| out["unique_states"] = len(uniq) |
| counts = np.array([terminals.count(u) for u in uniq], dtype=float) |
| p = counts / counts.sum() |
| out["entropy"] = float(-(p * np.log(p + 1e-12)).sum()) |
| out["diversity"] = float(len(uniq) / len(terminals)) |
|
|
| if env.name == "hypergrid": |
| modes = {env.mode_id(s) for s in terminals if env.mode_id(s) is not None} |
| total_modes = (env.size // env.period) ** 2 |
| out["modes_found"] = len(modes) |
| out["coverage_pct"] = 100.0 * len(modes) / total_modes |
| if env.name == "bitsequence": |
| out["modes_found"] = len({s for s in terminals if env.is_mode(s)}) |
| if env.name == "tictactoe": |
| out["win_pct"] = 100.0 * float(np.mean([env.is_win(s) for s in terminals])) |
|
|
| |
| support = enumerate_terminals(env) |
| if support is not None: |
| Rv = np.array([env.reward(s) for s in support], dtype=float) |
| Pstar = Rv / Rv.sum() |
| idx = {s: i for i, s in enumerate(support)} |
| emp = np.zeros(len(support)) |
| for s in terminals: |
| j = idx.get(s) |
| if j is not None: |
| emp[j] += 1 |
| emp = emp / max(emp.sum(), 1) |
| out["l1_to_target"] = float(np.abs(emp - Pstar).sum()) |
| mask = emp > 0 |
| out["kl_to_target"] = float((emp[mask] * np.log(emp[mask] / Pstar[mask])).sum()) |
| return out |
|
|
|
|
| _TERMINAL_CACHE: dict = {} |
|
|
|
|
| def enumerate_terminals(env): |
| """Full terminal-state support for the small environments (used for exact |
| L1/KL to the target distribution). Returns None when intractable.""" |
| key = (env.name, getattr(env, "L", None), getattr(env, "size", None), |
| getattr(env, "n", None), getattr(env, "k", None)) |
| if key in _TERMINAL_CACHE: |
| return _TERMINAL_CACHE[key] |
| import itertools |
| if env.name == "bitsequence": |
| out = list(itertools.product([0, 1], repeat=env.L)) |
| elif env.name == "hypergrid": |
| out = [(x, y, 1) for x in range(env.size) for y in range(env.size)] |
| elif env.name == "singlecell_proxy": |
| combos = list(itertools.combinations(range(env.n), env.k)) |
| out = combos if len(combos) <= 20000 else None |
| else: |
| out = None |
| _TERMINAL_CACHE[key] = out |
| return out |
|
|
|
|
| def optimal_move_rate(trainer, n_games=200): |
| """TicTacToe move-quality: fraction of agent moves matching minimax.""" |
| env = trainer.env |
| if env.name != "tictactoe": |
| return None |
| optimal, total, blunders = 0, 0, 0 |
| for _ in range(n_games): |
| s = env.reset() |
| for t in range(9): |
| va = env.valid_actions(s) |
| if not va: |
| break |
| enc = torch.tensor(env.encode(s)[None, :], device=DEVICE) |
| tt = torch.tensor([t], dtype=torch.long, device=DEVICE) |
| with torch.no_grad(): |
| pf, _, _ = trainer.model(enc, tt) |
| m = torch.tensor(forward_mask(env, s, env.n_actions)[None, :], device=DEVICE) |
| a = int(masked_log_softmax(pf, m).argmax(-1).item()) |
| best_val, _ = env._minimax(s, 1) |
| nb = list(s); nb[a] = 1 |
| val_after, _ = env._minimax(tuple(nb), -1) |
| if val_after >= best_val: |
| optimal += 1 |
| if val_after < best_val: |
| blunders += 1 |
| total += 1 |
| s, done = env.step(s, a, trainer.rng) |
| if done: |
| break |
| return { |
| "optimal_pct": 100.0 * optimal / max(total, 1), |
| "blunder_pct": 100.0 * blunders / max(total, 1), |
| } |
|
|
|
|
| def run(env_name, method, seed, cfg, out_dir, log_every=None): |
| t0 = time.time() |
| tr = Trainer(env_name, method, seed, cfg) |
| iters = cfg["iters"] |
| log_every = log_every or max(25, iters // 40) |
| eps0, epsf = cfg["eps0"], cfg["epsf"] |
| curve = [] |
| for it in range(iters): |
| eps = epsf + (eps0 - epsf) * (cfg["eps_decay"] ** it) |
| metrics, traj, finals = tr.step(cfg["batch"], eps) |
| if (it + 1) % log_every == 0 or it == 0: |
| ev = evaluate(tr, n_samples=512) |
| row = {"iter": it + 1, "env_steps": tr.total_env_steps, **metrics, **ev} |
| curve.append(row) |
| final_eval = evaluate(tr, n_samples=cfg["eval_samples"]) |
| if env_name == "tictactoe": |
| final_eval.update(optimal_move_rate(tr, n_games=cfg["ttt_eval_games"])) |
| if env_name == "singlecell_proxy": |
| |
| import itertools |
| combos = list(itertools.combinations(range(tr.env.n), tr.env.k)) |
| if len(combos) > 3000: |
| idx = tr.rng.choice(len(combos), 3000, replace=False) |
| combos = [combos[i] for i in idx] |
| true_r = np.array([tr.env.reward(c) for c in combos]) |
| |
| scores = [] |
| for c in combos: |
| s, lp = tr.env.reset(), 0.0 |
| for g in sorted(c): |
| enc = torch.tensor(tr.env.encode(s)[None, :], device=DEVICE) |
| tt = torch.tensor([len(s)], dtype=torch.long, device=DEVICE) |
| with torch.no_grad(): |
| pf, _, _ = tr.model(enc, tt) |
| m = torch.tensor(forward_mask(tr.env, s, tr.env.n_actions)[None, :], device=DEVICE) |
| lp += float(masked_log_softmax(pf, m)[0, g].item()) |
| s, _ = tr.env.step(s, g, tr.rng) |
| scores.append(lp) |
| scores = np.array(scores) |
| lr = np.log(true_r + 1e-8) |
| final_eval["target_corr"] = float(np.corrcoef(scores, lr)[0, 1]) |
| sn = (scores - scores.mean()) / (scores.std() + 1e-8) |
| ln = (lr - lr.mean()) / (lr.std() + 1e-8) |
| final_eval["l1_error"] = float(np.abs(sn - ln).mean()) |
|
|
| |
| losses = [r["loss"] for r in curve if "loss" in r][-10:] |
| final_eval["stability_cv"] = float(np.std(losses) / (abs(np.mean(losses)) + 1e-8)) if losses else None |
| final_eval["grad_norm_var"] = float(np.var(tr.grad_norms[-200:])) if tr.grad_norms else None |
| final_eval["wall_time_s"] = time.time() - t0 |
| final_eval["env_steps"] = tr.total_env_steps |
| if tr.use_intrinsic and getattr(tr, "last_acf", None) is not None: |
| acf = np.abs(tr.last_acf) |
| final_eval["periodicity_score"] = float(acf.max() / (acf.mean() + 1e-12)) |
| final_eval["acf"] = tr.last_acf.tolist() |
| final_eval["acf_peak_lag"] = int(np.argmax(tr.last_acf) + 1) |
| final_eval["lag_weights"] = tr.last_weights.tolist() |
|
|
| result = { |
| "env": env_name, "method": method, "seed": seed, |
| "config": cfg, "curve": curve, "final": final_eval, |
| "device": str(DEVICE), |
| } |
| os.makedirs(out_dir, exist_ok=True) |
| path = os.path.join(out_dir, f"{env_name}__{method}__seed{seed}.json") |
| with open(path, "w") as f: |
| json.dump(result, f, indent=2) |
| print(f"[done] {env_name}/{method}/seed{seed} " |
| f"top100={final_eval.get('top100_reward'):.3f} " |
| f"modes={final_eval.get('modes_found')} " |
| f"time={final_eval['wall_time_s']:.1f}s") |
| return result |
|
|
|
|
| DEFAULT_CFG = dict( |
| lr=1e-4, lr_logz=1e-1, lr_lambda=1e-2, grad_clip=5.0, batch=32, iters=500, |
| rff_dim=256, rff_sigma=1.0, lambda_init=0.05, v_target=0.1, |
| w_consistency=1.0, beta=0.5, k_max=8, ac_alpha=0.1, ac_signal="reward", ac_weight_mode="uniform", |
| eps0=0.8, epsf=0.05, eps_decay=0.9995, subtb_lambda=0.5, |
| bit_length=8, p_fail=0.9, grid_size=32, period=4, |
| opp_optimal=0.9, n_genes=24, k_genes=3, |
| eval_samples=2048, ttt_eval_games=200, |
| ) |
|
|
| ALL_METHODS = ["stgfn", "tb", "fm", "subtb", "db", "eflownet", "stochastic_gfn", |
| "tb_rnd", "tb_novelty", "tb_icm", "tb_cv"] |
|
|
| if __name__ == "__main__": |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--env", required=True) |
| ap.add_argument("--methods", default="all") |
| ap.add_argument("--seeds", default="0,1,2") |
| ap.add_argument("--iters", type=int, default=None) |
| ap.add_argument("--out", default="outputs") |
| ap.add_argument("--set", nargs="*", default=[]) |
| args = ap.parse_args() |
|
|
| cfg = dict(DEFAULT_CFG) |
| if args.iters: |
| cfg["iters"] = args.iters |
| for kv in args.set: |
| k, v = kv.split("=") |
| cfg[k] = type(cfg[k])(v) if k in cfg and cfg[k] is not None else float(v) |
|
|
| methods = ALL_METHODS if args.methods == "all" else args.methods.split(",") |
| seeds = [int(s) for s in args.seeds.split(",")] |
| print(f"device={DEVICE} env={args.env} methods={methods} seeds={seeds} iters={cfg['iters']}") |
| for m in methods: |
| for sd in seeds: |
| run(args.env, m, sd, cfg, args.out) |
|
|