import numpy as np
import matplotlib.pyplot as plt
from cycler import cycler
from matplotlib_inline.backend_inline import set_matplotlib_formats
set_matplotlib_formats("svg")
FIG_GRAY = "#808080"
FIG_COLORS = ["#0072B2", "#D55E00", "#009E73", "#cb77a6", "#c28600", "#1d99e0", "#7f7f7f"]
plt.rcParams.update({
"figure.facecolor": "none", "axes.facecolor": "none",
"savefig.facecolor": "none", "savefig.transparent": True,
"text.color": FIG_GRAY, "axes.labelcolor": FIG_GRAY, "axes.edgecolor": FIG_GRAY,
"xtick.color": FIG_GRAY, "ytick.color": FIG_GRAY,
"grid.color": FIG_GRAY, "grid.alpha": 0.25,
"legend.facecolor": "none", "legend.edgecolor": FIG_GRAY, "legend.framealpha": 0,
"axes.prop_cycle": cycler(color=FIG_COLORS),
"svg.hashsalt": "aiml", "svg.fonttype": "path",
})
rng = np.random.default_rng(0)
dims = [8, 16, 32, 64, 128, 256, 512]
var_raw, var_scaled = [], []
for d_k in dims:
q = rng.standard_normal((10_000, d_k))
k = rng.standard_normal((10_000, d_k))
s = (q * k).sum(axis=1)
var_raw.append(s.var())
var_scaled.append((s / np.sqrt(d_k)).var())
print(f"d_k = {d_k:3d} Var(q.k) = {var_raw[-1]:7.1f} Var(q.k / sqrt(d_k)) = {var_scaled[-1]:.2f}")