File size: 10,497 Bytes
1f48ccf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
"""Core simulation library for reproducing arXiv:2602.02431 (ICML 2026 #26332).

Single-index model:  x_i ~ N(0, I_d),  y_i = sigma(<x_i, theta*>),  ||theta*|| = 1.

Activations
-----------
* ``quad``          sigma(z) = z^2                      (paper Sec. 3.1)
* ``trunc``         sigma(z) = min(z^2, M)              (paper eq. 4.3, hard truncation)
* ``smooth``        sigma(z) = int_0^{z^2} phi(u) du    (paper eq. 3.10, smooth truncation)

Algorithms
----------
* ``spherical_flow``  full-batch spherical GD on the correlation loss
                      L(theta) = -(1/n) sum_i y_i sigma(<x_i, theta>)
                      theta <- normalize(theta + eta (I - theta theta^T) A(theta) theta)
                      with A(theta) = (2/n) sum_i y_i phi(<x_i,theta>^2) x_i x_i^T.
* ``online_sgd``      one-pass spherical SGD on the same loss (each sample used once).
* ``squared_gd``      full-batch Euclidean GD on the squared loss (paper Sec. 4).
"""

from __future__ import annotations

import math
from dataclasses import dataclass

import torch


# --------------------------------------------------------------------------- #
# activations
# --------------------------------------------------------------------------- #
def _bump(u: torch.Tensor) -> torch.Tensor:
    """gamma(u) = exp(-1/u) for u > 0, else 0."""
    out = torch.zeros_like(u)
    pos = u > 0
    out[pos] = torch.exp(-1.0 / u[pos])
    return out


def phi_smooth(u: torch.Tensor, M: float) -> torch.Tensor:
    """C^inf cutoff: phi = 1 for |u| <= M, 0 for |u| >= 2M (paper Sec. 3.2)."""
    t = (u.abs() - M) / M
    g0, g1 = _bump(t), _bump(1.0 - t)
    S = torch.where(g0 + g1 > 0, g0 / (g0 + g1 + 1e-300), torch.zeros_like(t))
    return (1.0 - S).clamp_(0.0, 1.0)


_SMOOTH_TABLE: dict[tuple[float, str, str], tuple[torch.Tensor, torch.Tensor]] = {}


def _smooth_sigma_table(M: float, device, dtype, npts: int = 200_001):
    key = (M, str(device), str(dtype))
    if key not in _SMOOTH_TABLE:
        u = torch.linspace(0.0, 2.0 * M, npts, device=device, dtype=dtype)
        f = phi_smooth(u, M)
        du = u[1] - u[0]
        cum = torch.cumsum((f[1:] + f[:-1]) * 0.5 * du, dim=0)
        cum = torch.cat([torch.zeros(1, device=device, dtype=dtype), cum])
        _SMOOTH_TABLE[key] = (u, cum)
    return _SMOOTH_TABLE[key]


def sigma(z: torch.Tensor, act: str, M: float) -> torch.Tensor:
    if act == "quad":
        return z * z
    if act == "trunc":
        return torch.clamp(z * z, max=M)
    if act == "smooth":
        u, cum = _smooth_sigma_table(M, z.device, z.dtype)
        w = torch.clamp(z * z, max=2.0 * M)
        idx = torch.clamp(
            torch.searchsorted(u, w.reshape(-1).contiguous()), 1, u.numel() - 1
        )
        u0, u1 = u[idx - 1], u[idx]
        c0, c1 = cum[idx - 1], cum[idx]
        frac = (w.reshape(-1) - u0) / (u1 - u0)
        return (c0 + frac * (c1 - c0)).reshape(z.shape)
    raise ValueError(act)


def phi(w: torch.Tensor, act: str, M: float) -> torch.Tensor:
    """phi(u) with sigma'(z) = 2 z phi(z^2); argument ``w`` is z^2."""
    if act == "quad":
        return torch.ones_like(w)
    if act == "trunc":
        return (w < M).to(w.dtype)
    if act == "smooth":
        return phi_smooth(w, M)
    raise ValueError(act)


def sigma_prime(z: torch.Tensor, act: str, M: float) -> torch.Tensor:
    return 2.0 * z * phi(z * z, act, M)


# --------------------------------------------------------------------------- #
# data
# --------------------------------------------------------------------------- #
@dataclass
class Data:
    X: torch.Tensor
    y: torch.Tensor
    theta_star: torch.Tensor


def make_data(d: int, n: int, seed: int, act: str, M: float, device, dtype) -> Data:
    g = torch.Generator(device=device).manual_seed(seed)
    theta_star = torch.randn(d, generator=g, device=device, dtype=dtype)
    theta_star /= theta_star.norm()
    X = torch.randn(n, d, generator=g, device=device, dtype=dtype)
    y = sigma(X @ theta_star, act, M)
    return Data(X, y, theta_star)


def rand_sphere(d: int, seed: int, device, dtype) -> torch.Tensor:
    g = torch.Generator(device=device).manual_seed(seed)
    v = torch.randn(d, generator=g, device=device, dtype=dtype)
    return v / v.norm()


# --------------------------------------------------------------------------- #
# full-batch spherical gradient descent on the correlation loss
# --------------------------------------------------------------------------- #
def a_star(data: Data) -> torch.Tensor:
    """A* = (2/n) sum_i y_i x_i x_i^T  (paper eq. 3.3)."""
    n = data.X.shape[0]
    return (2.0 / n) * (data.X.T @ (data.y[:, None] * data.X))


def _Atheta_matvec(data: Data, theta: torch.Tensor, act: str, M: float) -> torch.Tensor:
    """A(theta) @ theta without forming A(theta)  (paper eq. 3.11)."""
    z = data.X @ theta
    w = data.y * phi(z * z, act, M) * z
    return (2.0 / data.X.shape[0]) * (data.X.T @ w)


def spherical_flow(
    data: Data,
    theta0: torch.Tensor,
    act: str,
    M: float,
    eta: float = 0.1,
    T: int = 1000,
    tol: float = 1e-12,
    check_every: int = 50,
    use_matrix: bool | None = None,
    record_every: int = 0,
):
    """Full-batch spherical GD on the correlation loss (paper eq. 3.4 / 3.12).

    Returns ``(theta, steps_run, trace)`` where ``trace`` is a list of
    ``(step, squared_overlap)`` when ``record_every > 0``.
    """
    if use_matrix is None:
        use_matrix = act == "quad"
    A = a_star(data) if use_matrix else None
    theta = theta0.clone()
    ts = data.theta_star
    trace = []
    prev_ray = None
    prev_ov = None
    steps = T
    for t in range(T):
        Ath = (A @ theta) if use_matrix else _Atheta_matvec(data, theta, act, M)
        ray = theta @ Ath
        grad = Ath - ray * theta                    # (I - theta theta^T) A(theta) theta
        theta = theta + eta * grad
        theta = theta / theta.norm()
        if record_every and (t % record_every == 0 or t == T - 1):
            trace.append((t + 1, float((theta @ ts) ** 2)))
        if (t + 1) % check_every == 0:
            # converged: Rayleigh quotient (= -loss) and overlap both stationary
            ray, ov = float(ray), float((theta @ ts) ** 2)
            if (
                prev_ray is not None
                and abs(ray - prev_ray) <= tol * max(abs(ray), 1e-30)
                and abs(ov - prev_ov) <= tol
            ):
                steps = t + 1
                break
            prev_ray, prev_ov = ray, ov
    return theta, steps, trace


# --------------------------------------------------------------------------- #
# one-pass (online) spherical SGD on the correlation loss
# --------------------------------------------------------------------------- #
def online_sgd(
    d: int,
    n: int,
    seeds: int,
    act: str,
    M: float,
    eta: float,
    seed0: int,
    device,
    dtype,
    checkpoints: list[int],
    chunk: int = 2048,
):
    """One-pass spherical SGD, vectorised over ``seeds`` independent replicas.

    theta <- normalize(theta + eta (I - theta theta^T) y_t sigma'(<x_t,theta>) x_t)

    Returns dict ``{n_used: mean squared overlap}`` measured at ``checkpoints``.
    """
    g = torch.Generator(device=device).manual_seed(seed0)
    ts = torch.randn(seeds, d, generator=g, device=device, dtype=dtype)
    ts /= ts.norm(dim=1, keepdim=True)
    th = torch.randn(seeds, d, generator=g, device=device, dtype=dtype)
    th /= th.norm(dim=1, keepdim=True)

    out: dict[int, float] = {}
    cps = sorted(checkpoints)
    ci = 0
    done = 0
    while done < n:
        m = min(chunk, n - done)
        Xc = torch.randn(seeds, m, d, generator=g, device=device, dtype=dtype)
        for j in range(m):
            x = Xc[:, j, :]                                   # (S, d)
            zstar = (x * ts).sum(1)
            y = sigma(zstar, act, M)
            z = (x * th).sum(1)
            coef = y * sigma_prime(z, act, M)                 # (S,)
            gvec = coef[:, None] * x
            gvec = gvec - (gvec * th).sum(1, keepdim=True) * th
            th = th + eta * gvec
            th = th / th.norm(dim=1, keepdim=True)
            done += 1
            while ci < len(cps) and done == cps[ci]:
                out[done] = float(((th * ts).sum(1) ** 2).mean())
                ci += 1
        del Xc
    return out


# --------------------------------------------------------------------------- #
# full-batch Euclidean GD on the squared loss (paper Sec. 4)
# --------------------------------------------------------------------------- #
def squared_gd(
    data: Data,
    theta0: torch.Tensor,
    act: str,
    M: float,
    eta: float,
    T: int,
    record_every: int = 1,
    stop_err: float | None = None,
):
    """theta_{t+1} = theta_t - eta * (1/n) sum_i (sigma(<x_i,th>) - y_i) sigma'(<x_i,th>) x_i.

    Returns a dict of trajectory arrays (step, sq_overlap, norm, dist2, loss).
    """
    X, y, ts = data.X, data.y, data.theta_star
    n = X.shape[0]
    theta = theta0.clone()
    rec = {"step": [], "sq_overlap": [], "norm": [], "dist2": [], "loss": []}

    def _record(t):
        nr = float(theta.norm())
        ov = float((theta @ ts) ** 2) / max(nr * nr, 1e-300)
        d2 = min(
            float(((theta - ts) ** 2).sum()), float(((theta + ts) ** 2).sum())
        )
        z = X @ theta
        loss = float((0.5 / n) * ((sigma(z, act, M) - y) ** 2).sum())
        rec["step"].append(t)
        rec["sq_overlap"].append(ov)
        rec["norm"].append(nr)
        rec["dist2"].append(d2)
        rec["loss"].append(loss)
        return d2

    _record(0)
    for t in range(1, T + 1):
        z = X @ theta
        resid = (sigma(z, act, M) - y) * sigma_prime(z, act, M)
        grad = (X.T @ resid) / n
        theta = theta - eta * grad
        if record_every and (t % record_every == 0 or t == T):
            d2 = _record(t)
            if stop_err is not None and d2 < stop_err:
                break
    return rec


# --------------------------------------------------------------------------- #
# helpers
# --------------------------------------------------------------------------- #
def top2_eig(A: torch.Tensor):
    """Top-two eigenvalues and top eigenvector of a symmetric matrix."""
    A = 0.5 * (A + A.T)
    evals, evecs = torch.linalg.eigh(A.double())
    return float(evals[-1]), float(evals[-2]), evecs[:, -1].to(A.dtype)


def log2_steps(d: int, mult: float = 1000.0) -> int:
    return int(mult * math.log(d) ** 2)