File size: 6,449 Bytes
6e03b1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a76f68a
 
 
 
 
 
 
 
 
6e03b1a
 
a76f68a
 
6e03b1a
 
a76f68a
 
6e03b1a
 
 
 
 
 
 
 
 
 
 
 
 
a76f68a
 
 
 
6e03b1a
 
 
 
 
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
"""ST-GFN and baseline GFlowNet models.

Reimplemented from the paper text (Sec. 3, Def. 5, Alg. 1, App. C) since no
author code accompanies the submission.

IMPORTANT INTERPRETATION NOTE (documented in the logbook):
The paper's Unified Spectral Loss (Definition 5) contains only
    ||P_F_hat(s,t) - P_B_hat(s,t)||^2  +  lambda * E_a[ ||V_hat(s,a)||_H^2 ]
i.e. it has NO reward/terminal term. Taken literally that objective is
reward-independent and cannot train a GFlowNet to sample proportional to R
(its global minimum is P_F == P_B with zero spectral energy). Definition 2
does carry the reward terms (r_term, r_int), so we read Definition 5 as the
*regularizer pair* that rides on top of a standard reward-matching GFlowNet
objective. We therefore implement

    L_STGFN = L_TB(with intrinsic AC reward)  +  w_c * L_spectral_consistency
                                              +  lambda * L_spectral_reg

with lambda adaptive (lambda = exp(theta_lambda)) per Eq. 14-15. All baselines
share the identical backbone/optimizer so the comparison isolates the spectral
machinery.
"""
from __future__ import annotations

import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F


class RFF(nn.Module):
    """Random Fourier Feature map z(s) = sqrt(2/D)[cos(w_i^T s + b_i)]_{i<D}.
    Gaussian kernel k(s,s') = exp(-||s-s'||^2 / (2 sigma^2))  (App. C.1.3)."""

    def __init__(self, in_dim: int, D: int = 256, sigma: float = 1.0, seed: int = 0):
        super().__init__()
        g = torch.Generator().manual_seed(seed)
        omega = torch.randn(D, in_dim, generator=g) / sigma
        b = torch.rand(D, generator=g) * 2 * math.pi
        self.register_buffer("omega", omega)
        self.register_buffer("bias", b)
        self.D = D

    def forward(self, x):
        proj = x @ self.omega.T + self.bias
        return math.sqrt(2.0 / self.D) * torch.cos(proj)


class GFNNet(nn.Module):
    """Shared backbone: 3 layers, 256 hidden units (App. C.1.1).

    Heads: forward-policy logits, backward-policy logits (over the same
    successor/action set, used by the spectral consistency term and by TB when
    a state has multiple parents), and log-flow log F(s,t)."""

    def __init__(self, state_dim: int, n_actions: int, max_t: int, hidden: int = 256, n_layers: int = 3):
        super().__init__()
        self.max_t = max_t
        in_dim = state_dim + max_t + 1
        layers = []
        d = in_dim
        for _ in range(n_layers):
            layers += [nn.Linear(d, hidden), nn.LeakyReLU()]
            d = hidden
        self.trunk = nn.Sequential(*layers)
        self.pf_head = nn.Linear(hidden, n_actions)
        self.pb_head = nn.Linear(hidden, n_actions)
        self.logF_head = nn.Linear(hidden, 1)
        self.logZ = nn.Parameter(torch.zeros(1))

    def _time_emb(self, t, device, batch):
        te = torch.zeros(batch, self.max_t + 1, device=device)
        te[torch.arange(batch, device=device), t.clamp(max=self.max_t)] = 1.0
        return te

    def forward(self, s, t):
        te = self._time_emb(t, s.device, s.shape[0])
        h = self.trunk(torch.cat([s, te], dim=-1))
        return self.pf_head(h), self.pb_head(h), self.logF_head(h).squeeze(-1)


class RNDNet(nn.Module):
    """Random Network Distillation bonus (Burda et al. 2018) for TB+RND."""

    def __init__(self, state_dim: int, hidden: int = 128, out: int = 64, seed: int = 0):
        super().__init__()
        torch.manual_seed(seed)
        self.target = nn.Sequential(
            nn.Linear(state_dim, hidden), nn.ReLU(), nn.Linear(hidden, out)
        )
        for p in self.target.parameters():
            p.requires_grad_(False)
        self.pred = nn.Sequential(
            nn.Linear(state_dim, hidden), nn.ReLU(), nn.Linear(hidden, out)
        )

    def bonus(self, s):
        with torch.no_grad():
            t = self.target(s)
        p = self.pred(s)
        return ((p - t) ** 2).mean(-1)


class ICMNet(nn.Module):
    """Intrinsic Curiosity Module forward-model error (Pathak et al. 2017)."""

    def __init__(self, state_dim: int, n_actions: int, hidden: int = 128):
        super().__init__()
        self.fwd = nn.Sequential(
            nn.Linear(state_dim + n_actions, hidden), nn.ReLU(), nn.Linear(hidden, state_dim)
        )
        self.n_actions = n_actions

    def error(self, s, a, s_next):
        a1h = F.one_hot(a, self.n_actions).float()
        pred = self.fwd(torch.cat([s, a1h], dim=-1))
        return ((pred - s_next) ** 2).mean(-1)


class AutocorrIntrinsic:
    """Online autocorrelated intrinsic reward (Alg. 1, lines 11-19).

    Maintains a circular buffer of raw local rewards and EMA estimates of the
    autocorrelation R_rr[tau_i], then r_AC(t) = sum_i w_i * R_rr_hat[tau_i]_t.

    `mode` controls the lag weights w_i, which the paper under-specifies:
      "uniform" - w_i = 1/K, the stated initialisation (App C.1.3). With uniform
                  weights r_AC sums every lag, so it tracks overall reward
                  magnitude and is NOT period-selective.
      "peak"    - mass concentrated on the strongest ACF lag (softmax over the
                  ACF). This is the charitable reading of Fig. 9(d), which shows
                  "learned lag weights concentrating on the period and its
                  harmonics" but gives no update rule anywhere in the paper.
    """

    def __init__(self, k_max: int = 8, alpha: float = 0.1, mode: str = "uniform",
                 temp: float = 0.5):
        self.k_max = k_max
        self.alpha = alpha
        self.mode = mode
        self.temp = temp
        self.weights = np.ones(k_max) / k_max
        self.reset()

    def reset(self):
        self.buf: list[float] = []
        self.acf = np.zeros(self.k_max)

    def update(self, r_t: float) -> float:
        self.buf.append(r_t)
        for i in range(1, self.k_max + 1):
            if len(self.buf) > i:
                prod = r_t * self.buf[-1 - i]
                self.acf[i - 1] = (1 - self.alpha) * self.acf[i - 1] + self.alpha * prod
        if self.mode == "peak":
            a = self.acf / (np.abs(self.acf).max() + 1e-12)
            e = np.exp((a - a.max()) / self.temp)
            self.weights = e / e.sum()
        return float((self.weights * self.acf).sum())

    def periodicity_score(self) -> float:
        m = np.abs(self.acf).mean()
        return float(np.abs(self.acf).max() / m) if m > 1e-12 else 0.0