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
|
#!/usr/bin/env python3
"""Validate the beta law for random feedback alignment.
For independent isotropic matrix directions A, B in R^{rows x cols}, the
squared Frobenius cosine
Q = <A, B>_F^2 / (||A||_F^2 ||B||_F^2)
has distribution Beta(1/2, (D - 1)/2), where D = rows * cols.
"""
from __future__ import annotations
import argparse
import json
from dataclasses import asdict, dataclass
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
from scipy import special, stats
@dataclass(frozen=True)
class RunConfig:
rows: int
cols: int
samples: int
batch_size: int
seed: int
dist_a: str
dist_b: str
thresholds: list[float]
outdir: str
plot: bool
@dataclass(frozen=True)
class Summary:
dimension: int
beta_alpha: float
beta_beta: float
empirical_mean: float
theoretical_mean: float
empirical_var: float
theoretical_var: float
ks_statistic: float
ks_pvalue: float
quantiles: dict[str, float]
tail_probabilities: dict[str, dict[str, float]]
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Monte Carlo validation of the FA static alignment beta law."
)
parser.add_argument("--rows", type=int, default=16, help="Matrix row count.")
parser.add_argument("--cols", type=int, default=16, help="Matrix column count.")
parser.add_argument("--samples", type=int, default=50_000, help="Number of pairs.")
parser.add_argument(
"--batch-size",
type=int,
default=10_000,
help="Number of pairs to sample per batch.",
)
parser.add_argument("--seed", type=int, default=0, help="Random seed.")
parser.add_argument(
"--dist-a",
choices=["gaussian", "sphere", "rademacher"],
default="gaussian",
help="Distribution for A.",
)
parser.add_argument(
"--dist-b",
choices=["gaussian", "sphere", "rademacher"],
default="gaussian",
help="Distribution for B.",
)
parser.add_argument(
"--thresholds",
type=float,
nargs="*",
default=None,
help="Tail thresholds q. Defaults to {1, 2, 5, 10}/D.",
)
parser.add_argument(
"--outdir",
type=Path,
default=Path("outputs/static_alignment_beta"),
help="Directory for summary and plots.",
)
parser.add_argument("--plot", action="store_true", help="Save diagnostic plots.")
return parser.parse_args()
def sample_vectors(
rng: np.random.Generator, count: int, dim: int, distribution: str
) -> np.ndarray:
if distribution == "gaussian":
return rng.standard_normal((count, dim))
if distribution == "sphere":
values = rng.standard_normal((count, dim))
norms = np.linalg.norm(values, axis=1, keepdims=True)
return values / np.maximum(norms, np.finfo(values.dtype).tiny)
if distribution == "rademacher":
return rng.choice(np.array([-1.0, 1.0]), size=(count, dim))
raise ValueError(f"Unknown distribution: {distribution}")
def squared_cosines(config: RunConfig) -> np.ndarray:
dim = config.rows * config.cols
rng = np.random.default_rng(config.seed)
values = np.empty(config.samples, dtype=np.float64)
offset = 0
while offset < config.samples:
count = min(config.batch_size, config.samples - offset)
a = sample_vectors(rng, count, dim, config.dist_a)
b = sample_vectors(rng, count, dim, config.dist_b)
dot = np.einsum("ij,ij->i", a, b)
a_norm_sq = np.einsum("ij,ij->i", a, a)
b_norm_sq = np.einsum("ij,ij->i", b, b)
values[offset : offset + count] = (dot * dot) / (a_norm_sq * b_norm_sq)
offset += count
return values
def summarize(q_values: np.ndarray, dimension: int, thresholds: list[float]) -> Summary:
alpha = 0.5
beta_param = (dimension - 1) / 2
beta_dist = stats.beta(alpha, beta_param)
quantile_levels = [0.01, 0.05, 0.10, 0.50, 0.90, 0.95, 0.99]
quantiles = {
f"{level:.2f}": float(np.quantile(q_values, level))
for level in quantile_levels
}
tail_probabilities: dict[str, dict[str, float]] = {}
for threshold in thresholds:
empirical_tail = float(np.mean(q_values >= threshold))
theoretical_tail = float(1.0 - special.betainc(alpha, beta_param, threshold))
tail_probabilities[f"{threshold:.12g}"] = {
"empirical": empirical_tail,
"theoretical": theoretical_tail,
"absolute_error": abs(empirical_tail - theoretical_tail),
}
ks = stats.kstest(q_values, beta_dist.cdf)
return Summary(
dimension=dimension,
beta_alpha=alpha,
beta_beta=beta_param,
empirical_mean=float(np.mean(q_values)),
theoretical_mean=float(beta_dist.mean()),
empirical_var=float(np.var(q_values, ddof=1)),
theoretical_var=float(beta_dist.var()),
ks_statistic=float(ks.statistic),
ks_pvalue=float(ks.pvalue),
quantiles=quantiles,
tail_probabilities=tail_probabilities,
)
def write_summary(config: RunConfig, summary: Summary, outdir: Path) -> Path:
outdir.mkdir(parents=True, exist_ok=True)
path = outdir / "summary.json"
payload = {
"config": asdict(config),
"summary": asdict(summary),
}
path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n")
return path
def save_plots(q_values: np.ndarray, dimension: int, outdir: Path) -> list[Path]:
outdir.mkdir(parents=True, exist_ok=True)
alpha = 0.5
beta_param = (dimension - 1) / 2
beta_dist = stats.beta(alpha, beta_param)
paths: list[Path] = []
hist_path = outdir / "histogram_beta_overlay.png"
x_min = float(max(beta_dist.ppf(1e-5), np.finfo(float).tiny))
x_max = float(max(np.quantile(q_values, 0.999), beta_dist.ppf(0.999)))
xs = np.linspace(x_min, x_max, 500)
beta_pdf = np.exp(np.clip(beta_dist.logpdf(xs), -745, 80))
plt.figure(figsize=(7, 4.5))
plt.hist(q_values, bins=80, density=True, alpha=0.45, label="empirical")
plt.plot(xs, beta_pdf, color="black", linewidth=2, label="beta law")
plt.xlabel("Q = squared Frobenius cosine")
plt.ylabel("density")
plt.title(f"Static alignment distribution, D={dimension}")
plt.legend()
plt.tight_layout()
plt.savefig(hist_path, dpi=180)
plt.close()
paths.append(hist_path)
qq_path = outdir / "qq_plot.png"
probs = (np.arange(1, len(q_values) + 1) - 0.5) / len(q_values)
empirical = np.sort(q_values)
theoretical = beta_dist.ppf(probs)
max_value = float(max(empirical[-1], theoretical[-1]))
plt.figure(figsize=(5, 5))
plt.scatter(theoretical, empirical, s=4, alpha=0.35)
plt.plot([0, max_value], [0, max_value], color="black", linewidth=1)
plt.xlabel("theoretical beta quantile")
plt.ylabel("empirical quantile")
plt.title("Q-Q plot")
plt.tight_layout()
plt.savefig(qq_path, dpi=180)
plt.close()
paths.append(qq_path)
return paths
def main() -> None:
args = parse_args()
dimension = args.rows * args.cols
if dimension < 2:
raise ValueError("rows * cols must be at least 2 for the beta law.")
if args.samples < 1:
raise ValueError("--samples must be positive.")
if args.batch_size < 1:
raise ValueError("--batch-size must be positive.")
thresholds = args.thresholds
if thresholds is None:
thresholds = [1 / dimension, 2 / dimension, 5 / dimension, 10 / dimension]
thresholds = [q for q in thresholds if 0 <= q <= 1]
config = RunConfig(
rows=args.rows,
cols=args.cols,
samples=args.samples,
batch_size=args.batch_size,
seed=args.seed,
dist_a=args.dist_a,
dist_b=args.dist_b,
thresholds=thresholds,
outdir=str(args.outdir),
plot=args.plot,
)
q_values = squared_cosines(config)
summary = summarize(q_values, dimension, thresholds)
summary_path = write_summary(config, summary, args.outdir)
plot_paths: list[Path] = []
if args.plot:
plot_paths = save_plots(q_values, dimension, args.outdir)
print(f"dimension: {dimension}")
print(f"samples: {args.samples}")
print(
"mean: "
f"empirical={summary.empirical_mean:.8g}, "
f"theoretical={summary.theoretical_mean:.8g}"
)
print(
"variance: "
f"empirical={summary.empirical_var:.8g}, "
f"theoretical={summary.theoretical_var:.8g}"
)
print(
"KS: "
f"statistic={summary.ks_statistic:.6g}, "
f"pvalue={summary.ks_pvalue:.6g}"
)
print(f"summary: {summary_path}")
for path in plot_paths:
print(f"plot: {path}")
if __name__ == "__main__":
main()
|