aircompkit 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of aircompkit might be problematic. Click here for more details.

Files changed (39) hide show
  1. aircompkit/__init__.py +32 -0
  2. aircompkit/__main__.py +5 -0
  3. aircompkit/adversary/__init__.py +175 -0
  4. aircompkit/aircomp/__init__.py +41 -0
  5. aircompkit/aircomp/analytic.py +42 -0
  6. aircompkit/aircomp/power_control.py +183 -0
  7. aircompkit/aircomp/preprocess.py +48 -0
  8. aircompkit/bench.py +159 -0
  9. aircompkit/channel/__init__.py +209 -0
  10. aircompkit/cli.py +165 -0
  11. aircompkit/core/__init__.py +1 -0
  12. aircompkit/core/registry.py +123 -0
  13. aircompkit/core/result.py +45 -0
  14. aircompkit/core/rng.py +47 -0
  15. aircompkit/core/scenario.py +226 -0
  16. aircompkit/defense/__init__.py +156 -0
  17. aircompkit/defense/evaluate.py +48 -0
  18. aircompkit/devices/__init__.py +79 -0
  19. aircompkit/learning/__init__.py +32 -0
  20. aircompkit/learning/aggregate.py +49 -0
  21. aircompkit/learning/array.py +140 -0
  22. aircompkit/learning/bank.py +86 -0
  23. aircompkit/learning/data.py +128 -0
  24. aircompkit/learning/fl.py +249 -0
  25. aircompkit/learning/models.py +89 -0
  26. aircompkit/learning/partition.py +58 -0
  27. aircompkit/metrics/__init__.py +36 -0
  28. aircompkit/metrics/privacy.py +36 -0
  29. aircompkit/plot/__init__.py +5 -0
  30. aircompkit/receiver/__init__.py +244 -0
  31. aircompkit/reproduce/__init__.py +26 -0
  32. aircompkit/reproduce/yang2020.py +182 -0
  33. aircompkit/reproduce/zhu2020.py +205 -0
  34. aircompkit-1.0.0.dist-info/METADATA +167 -0
  35. aircompkit-1.0.0.dist-info/RECORD +39 -0
  36. aircompkit-1.0.0.dist-info/WHEEL +5 -0
  37. aircompkit-1.0.0.dist-info/entry_points.txt +2 -0
  38. aircompkit-1.0.0.dist-info/licenses/LICENSE +21 -0
  39. aircompkit-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,89 @@
1
+ """NumPy models with a flat parameter vector (FEATURES L4, L7).
2
+
3
+ A model exposes ``init(rng) -> params``, ``loss_grad(params, x, y) -> (loss, grad)``, and
4
+ ``evaluate(params, x, y) -> (loss, accuracy)``. ``params`` is a 1-D float array, which is what
5
+ devices transmit. Any object with these three methods can be used as a model (L7).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass, field
11
+
12
+ import numpy as np
13
+
14
+ from aircompkit.core.registry import register
15
+
16
+
17
+ @register("model", "mlp")
18
+ @dataclass
19
+ class MLP:
20
+ """Fully connected network, ReLU hidden layers, softmax cross-entropy. ``hidden=[]`` gives
21
+ multinomial logistic regression."""
22
+
23
+ d_in: int
24
+ n_classes: int
25
+ hidden: list[int] = field(default_factory=lambda: [64])
26
+
27
+ def __post_init__(self) -> None:
28
+ dims = [self.d_in, *self.hidden, self.n_classes]
29
+ self._shapes = [(dims[i], dims[i + 1]) for i in range(len(dims) - 1)]
30
+ sizes = [a * b + b for a, b in self._shapes]
31
+ self._offsets = np.concatenate([[0], np.cumsum(sizes)]).astype(int)
32
+ self.size = int(self._offsets[-1])
33
+
34
+ def _unpack(self, params):
35
+ out = []
36
+ for (a, b), off in zip(self._shapes, self._offsets[:-1]):
37
+ W = params[off: off + a * b].reshape(a, b)
38
+ out.append((W, params[off + a * b: off + a * b + b]))
39
+ return out
40
+
41
+ def init(self, rng: np.random.Generator) -> np.ndarray:
42
+ parts = []
43
+ for a, b in self._shapes:
44
+ parts.append((rng.standard_normal((a, b)) * np.sqrt(2.0 / a)).ravel())
45
+ parts.append(np.zeros(b))
46
+ return np.concatenate(parts)
47
+
48
+ def _forward(self, params, x):
49
+ acts = [x]
50
+ layers = self._unpack(params)
51
+ for i, (W, b) in enumerate(layers):
52
+ z = acts[-1] @ W + b
53
+ acts.append(np.maximum(z, 0.0) if i < len(layers) - 1 else z)
54
+ return layers, acts
55
+
56
+ @staticmethod
57
+ def _softmax_ce(logits, y):
58
+ z = logits - logits.max(axis=1, keepdims=True)
59
+ logp = z - np.log(np.exp(z).sum(axis=1, keepdims=True))
60
+ return -logp[np.arange(len(y)), y].mean(), logp
61
+
62
+ def loss_grad(self, params, x, y):
63
+ layers, acts = self._forward(params, x)
64
+ loss, logp = self._softmax_ce(acts[-1], y)
65
+ delta = np.exp(logp)
66
+ delta[np.arange(len(y)), y] -= 1.0
67
+ delta /= len(y)
68
+ grads = []
69
+ for i in range(len(layers) - 1, -1, -1):
70
+ W, _ = layers[i]
71
+ grads.append(((acts[i].T @ delta).ravel(), delta.sum(axis=0)))
72
+ if i > 0:
73
+ delta = (delta @ W.T) * (acts[i] > 0)
74
+ flat = [g for pair in reversed(grads) for g in pair]
75
+ return float(loss), np.concatenate(flat)
76
+
77
+ def evaluate(self, params, x, y, batch: int = 4096):
78
+ losses, correct = 0.0, 0
79
+ for lo in range(0, len(y), batch):
80
+ _, acts = self._forward(params, x[lo: lo + batch])
81
+ loss, _ = self._softmax_ce(acts[-1], y[lo: lo + batch])
82
+ losses += loss * len(acts[-1])
83
+ correct += int((acts[-1].argmax(axis=1) == y[lo: lo + batch]).sum())
84
+ return losses / len(y), correct / len(y)
85
+
86
+
87
+ @register("model", "logreg")
88
+ def logreg(d_in: int, n_classes: int) -> MLP:
89
+ return MLP(d_in, n_classes, hidden=[])
@@ -0,0 +1,58 @@
1
+ """Splitting a training set across devices (FEATURES L3). Each partitioner is called as
2
+ ``part(labels, K, rng) -> list of K index arrays``."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from dataclasses import dataclass
7
+
8
+ import numpy as np
9
+
10
+ from aircompkit.core.registry import register
11
+
12
+
13
+ @register("partitioner", "iid")
14
+ @dataclass
15
+ class IID:
16
+ """Random equal shares (Zhu et al.: 60000 MNIST samples into 200 shares)."""
17
+
18
+ def __call__(self, labels, K, rng):
19
+ return [np.sort(s) for s in np.array_split(rng.permutation(len(labels)), K)]
20
+
21
+
22
+ @register("partitioner", "shards")
23
+ @dataclass
24
+ class Shards:
25
+ """Sort by label, cut into ``K * shards_per_device`` shards, give each device that many
26
+ (McMahan et al.; Zhu et al. use 400 shards of 150 for 200 devices)."""
27
+
28
+ shards_per_device: int = 2
29
+
30
+ def __call__(self, labels, K, rng):
31
+ order = np.argsort(labels, kind="stable")
32
+ shards = np.array_split(order, K * self.shards_per_device)
33
+ pick = rng.permutation(len(shards))
34
+ return [np.sort(np.concatenate([shards[j] for j in
35
+ pick[k * self.shards_per_device:(k + 1) * self.shards_per_device]]))
36
+ for k in range(K)]
37
+
38
+
39
+ @register("partitioner", "dirichlet")
40
+ @dataclass
41
+ class Dirichlet:
42
+ """Label-Dirichlet(alpha) non-IID split; resamples until every device has ``min_size``."""
43
+
44
+ alpha: float = 0.5
45
+ min_size: int = 10
46
+
47
+ def __call__(self, labels, K, rng):
48
+ classes = np.unique(labels)
49
+ for _ in range(1000):
50
+ idx: list[list[int]] = [[] for _ in range(K)]
51
+ for c in classes:
52
+ ic = rng.permutation(np.flatnonzero(labels == c))
53
+ cuts = (np.cumsum(rng.dirichlet(self.alpha * np.ones(K))) * len(ic)).astype(int)[:-1]
54
+ for k, part in enumerate(np.split(ic, cuts)):
55
+ idx[k].extend(part.tolist())
56
+ if min(len(i) for i in idx) >= self.min_size:
57
+ return [np.sort(np.asarray(i, dtype=np.int64)) for i in idx]
58
+ raise RuntimeError("Dirichlet split: could not satisfy min_size; lower it or raise alpha")
@@ -0,0 +1,36 @@
1
+ """Computation metrics and confidence intervals (FEATURES M1, M6)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+
8
+ def mse_given_channel(
9
+ h: np.ndarray, b: np.ndarray, eta: np.ndarray, noise_var: float, real: bool
10
+ ) -> np.ndarray:
11
+ """Conditional AirComp MSE of the sum, per trial, for unit-power independent symbols.
12
+
13
+ ``sum_k |h_k b_k / sqrt(eta) - 1|^2 + noise_var / eta`` (complex symbols), or with
14
+ ``Re(.)`` in place of the complex amplitude for real symbols. ``noise_var`` is the
15
+ effective noise variance. ``h, b``: ``[trials, K]``; ``eta``: ``[trials]``.
16
+ """
17
+ a = h * b / np.sqrt(eta)[:, None]
18
+ err = (a.real - 1.0) ** 2 if real else np.abs(a - 1.0) ** 2
19
+ return err.sum(axis=1) + noise_var / eta
20
+
21
+
22
+ def nmse(estimate: np.ndarray, target: np.ndarray, axis: int = -1) -> np.ndarray:
23
+ """``||estimate - target||^2 / ||target||^2`` along ``axis``."""
24
+ num = np.sum(np.abs(estimate - target) ** 2, axis=axis)
25
+ den = np.sum(np.abs(target) ** 2, axis=axis)
26
+ return num / np.maximum(den, 1e-300)
27
+
28
+
29
+ def mean_ci(x: np.ndarray, z: float = 1.96) -> tuple[float, float]:
30
+ """Sample mean and normal-approximation CI half-width ``z * s / sqrt(n)``."""
31
+ x = np.asarray(x, float).ravel()
32
+ n = x.size
33
+ if n == 0:
34
+ return float("nan"), float("nan")
35
+ half = z * x.std(ddof=1) / np.sqrt(n) if n > 1 else float("inf")
36
+ return float(x.mean()), float(half)
@@ -0,0 +1,36 @@
1
+ """Differential-privacy accounting for over-the-air aggregation (FEATURES F8, M4).
2
+
3
+ In AirComp the server sees ``sum_k x_k + z`` with Gaussian receiver noise ``z``, so each
4
+ round is a Gaussian mechanism on every device's contribution "for free" (Liu & Simeone,
5
+ JSAC 2021; Koda et al. 2020). For L2 sensitivity ``Delta`` (one device's update changes,
6
+ e.g. clip norm for add/remove) and per-real-dimension noise std ``s``, the Renyi DP of
7
+ order ``a`` is ``a Delta^2 / (2 s^2)`` per round; ``T`` rounds compose additively; the
8
+ conversion ``eps = rdp + log(1/delta) / (a - 1)`` is minimised over ``a``.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import numpy as np
14
+
15
+
16
+ def gaussian_rdp(alpha: np.ndarray | float, sensitivity: float, noise_std: float) -> np.ndarray:
17
+ """RDP of the Gaussian mechanism at order(s) ``alpha > 1``."""
18
+ if noise_std <= 0:
19
+ raise ValueError("noise_std must be > 0")
20
+ return np.asarray(alpha, float) * sensitivity**2 / (2 * noise_std**2)
21
+
22
+
23
+ def gaussian_epsilon(sensitivity: float, noise_std: float, rounds: int = 1,
24
+ delta: float = 1e-5) -> float:
25
+ """``(epsilon, delta)``-DP after ``rounds`` compositions (RDP accountant)."""
26
+ if not 0 < delta < 1 or rounds < 1:
27
+ raise ValueError("need 0 < delta < 1 and rounds >= 1")
28
+ alphas = np.concatenate([np.linspace(1.01, 10, 400), np.geomspace(10, 1e6, 400)])
29
+ eps = rounds * gaussian_rdp(alphas, sensitivity, noise_std) + np.log(1 / delta) / (alphas - 1)
30
+ return float(eps.min())
31
+
32
+
33
+ def aircomp_noise_std(noise_var: float, eta: float, symbols: str = "complex") -> float:
34
+ """Per-real-dimension std of the receiver noise in the normalised AirComp estimate
35
+ ``m^H y / sqrt(eta)``: ``sqrt(noise_var / (2 eta))``."""
36
+ return float(np.sqrt(noise_var / (2 * eta)))
@@ -0,0 +1,5 @@
1
+ """Plot helpers (FEATURES §10).
2
+
3
+ Placeholder package created in P0. Components register themselves with
4
+ ``aircompkit.core.registry.register``.
5
+ """
@@ -0,0 +1,244 @@
1
+ """Receive beamformers for multi-antenna AirComp (FEATURES A4).
2
+
3
+ The server applies a unit-norm combiner ``m`` (shape ``[trials, n_rx]``) to the received
4
+ vector, which reduces the SIMO multiple-access channel to a scalar one with effective
5
+ coefficients ``c_k = m^H h_k`` and unchanged noise variance. Any power-control scheme from
6
+ ``aircompkit.aircomp.power_control`` then runs on ``|c_k|^2``. Splitting the design this
7
+ way covers the standard receive-beamforming designs:
8
+
9
+ * with ``channel_inversion`` (zero-forcing transmit, Yang et al. TWC 2020, Prop. 1) the MSE is
10
+ ``sigma^2 / min_k P_k |m^H h_k|^2``, so the best ``m`` solves the max-min-fair multicast
11
+ problem; this is what ``maxmin`` and ``sdr`` target;
12
+ * ``joint_mmse`` alternates an LMMSE receiver with per-device optimal transmit scaling and is
13
+ meant to be paired with ``optimal`` power control.
14
+
15
+ A combiner is called as ``m = rx(h_est, p_max, noise_var)`` with ``h_est`` of shape
16
+ ``[trials, K, n_rx]``. With ``n_rx = 1`` every combiner returns ``m = 1``.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from dataclasses import dataclass
22
+
23
+ import numpy as np
24
+
25
+ from aircompkit.core.registry import register
26
+
27
+
28
+ def _unit(m: np.ndarray) -> np.ndarray:
29
+ return m / np.maximum(np.linalg.norm(m, axis=-1, keepdims=True), 1e-300)
30
+
31
+
32
+ def effective_gains(h: np.ndarray, m: np.ndarray, p_max: np.ndarray | None = None) -> np.ndarray:
33
+ """``P_k |m^H h_k|^2`` for ``h [..., K, N]`` and ``m [..., N]`` (``P_k = 1`` if not given)."""
34
+ g = np.abs(np.einsum("...kn,...n->...k", h, m.conj())) ** 2
35
+ return g if p_max is None else g * p_max
36
+
37
+
38
+ def zf_mse(h: np.ndarray, m: np.ndarray, p_max: np.ndarray, noise_var: float) -> np.ndarray:
39
+ """MSE of zero-forcing transmission for a given combiner: ``sigma^2 / min_k P_k |m^H h_k|^2``."""
40
+ return noise_var / effective_gains(h, _unit(m), p_max).min(axis=-1)
41
+
42
+
43
+ def _ones(h: np.ndarray) -> np.ndarray:
44
+ return np.ones(h.shape[:1] + h.shape[2:], dtype=complex)
45
+
46
+
47
+ @register("receiver", "eigen")
48
+ @dataclass
49
+ class EigenCombiner:
50
+ """Dominant eigenvector of ``sum_k P_k h_k h_k^H / ||sqrt(P_k) h_k||^2`` (every device
51
+ weighted equally by direction). Cheap baseline; the max-min initialiser."""
52
+
53
+ def __call__(self, h, p_max, noise_var):
54
+ if h.shape[-1] == 1:
55
+ return _ones(h)
56
+ u = _unit(h)
57
+ R = np.einsum("tkn,tkm->tnm", u, u.conj())
58
+ _, vecs = np.linalg.eigh(R)
59
+ return vecs[..., -1]
60
+
61
+
62
+ @register("receiver", "maxmin")
63
+ @dataclass
64
+ class MaxMinCombiner:
65
+ """Max-min-fair combiner ``argmax_{||m||=1} min_k P_k |m^H h_k|^2`` (solver-free).
66
+
67
+ The problem is NP-hard in general (single-group multicast beamforming). This uses
68
+ projected gradient ascent on a log-sum-exp smoothed minimum with an annealed temperature,
69
+ started from every eigenvector of the direction-correlation matrix plus ``random_inits``
70
+ seeded random points, and keeps the best exact objective seen. Deterministic given
71
+ ``seed`` and vectorised over trials. Its value never exceeds the SDR upper bound
72
+ (``sdr_solve``); see the tests and the reproduction of Yang et al. 2020, Figs. 4–5.
73
+ """
74
+
75
+ iters: int = 400
76
+ random_inits: int = 24
77
+ step: float = 0.5
78
+ temp_start: float = 1.0
79
+ temp_end: float = 0.005
80
+ seed: int = 0
81
+
82
+ def __call__(self, h, p_max, noise_var):
83
+ T, _K, N = h.shape
84
+ if N == 1:
85
+ return _ones(h)
86
+ hs = h * np.sqrt(p_max)[None, :, None]
87
+ u = _unit(hs)
88
+ R = np.einsum("tkn,tkm->tnm", u, u.conj())
89
+ _, vecs = np.linalg.eigh(R)
90
+ m = np.swapaxes(vecs, 1, 2) # [T, N inits, N]
91
+ if self.random_inits > 0:
92
+ z = np.random.default_rng(self.seed).standard_normal((T, self.random_inits, N, 2))
93
+ m = np.concatenate([m, _unit(z[..., 0] + 1j * z[..., 1])], axis=1)
94
+ lr = self.step / np.max(np.sum(np.abs(hs) ** 2, axis=2), axis=1)[:, None, None]
95
+
96
+ def gains(mm):
97
+ c = np.einsum("tkn,trn->trk", hs, mm.conj())
98
+ return c, np.abs(c) ** 2
99
+
100
+ c, G = gains(m)
101
+ best_val = G.min(axis=2)
102
+ best_m = m.copy()
103
+ temps = np.geomspace(self.temp_start, self.temp_end, self.iters)
104
+ for tau in temps:
105
+ gmin = G.min(axis=2, keepdims=True)
106
+ z = -(G - gmin) / (tau * np.maximum(gmin, 1e-300))
107
+ w = np.exp(z)
108
+ w /= w.sum(axis=2, keepdims=True)
109
+ # d/dm* of |m^H h_k|^2 is h_k (h_k^H m) = h_k conj(c_k)
110
+ grad = np.einsum("trk,tkn->trn", w * c.conj(), hs)
111
+ m = _unit(m + lr * grad)
112
+ c, G = gains(m)
113
+ val = G.min(axis=2)
114
+ better = val > best_val
115
+ best_val = np.where(better, val, best_val)
116
+ best_m = np.where(better[..., None], m, best_m)
117
+ pick = np.argmax(best_val, axis=1)
118
+ return best_m[np.arange(T), pick]
119
+
120
+
121
+ @register("receiver", "sdr")
122
+ @dataclass
123
+ class SDRCombiner:
124
+ """Semidefinite relaxation + Gaussian randomisation for the max-min combiner, the
125
+ baseline of Yang et al. (TWC 2020) and Chen, Qin & Wei (IEEE WCL 2018).
126
+
127
+ The SDP ``max_{M >= 0, tr M = 1} min_k h_k^H M h_k`` is solved without an external solver
128
+ through its dual (see ``sdr_solve``); then ``randomizations`` candidates
129
+ ``m ~ CN(0, M)`` are drawn and the best one (or the principal eigenvector) is kept.
130
+ """
131
+
132
+ randomizations: int = 100
133
+ iters: int = 400
134
+ seed: int = 0
135
+
136
+ def __call__(self, h, p_max, noise_var):
137
+ _T, _K, N = h.shape
138
+ if N == 1:
139
+ return _ones(h)
140
+ rng = np.random.default_rng(self.seed)
141
+ hs = h * np.sqrt(p_max)[None, :, None]
142
+ M, _, _ = sdr_solve(hs, self.iters)
143
+ return gaussian_randomization(M, hs, self.randomizations, rng)
144
+
145
+
146
+ def sdr_solve(hs: np.ndarray, iters: int = 400) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
147
+ """Solve the max-min SDR ``max_{M >= 0, tr M = 1} min_k h_k^H M h_k`` for ``hs [T, K, N]``.
148
+
149
+ By the minimax theorem its value equals ``min_{w in simplex} lambda_max(sum_k w_k h_k h_k^H)``.
150
+ That convex problem is solved by entropic mirror descent on ``w``; the running average of
151
+ the best responses ``v v^H`` (top eigenvectors) converges to an optimal ``M``.
152
+
153
+ Returns ``(M [T, N, N], lower [T], upper [T])``. ``lower = min_k h_k^H M h_k`` is achieved
154
+ by the returned ``M``; ``upper`` is the smallest dual value seen. The SDR value lies in
155
+ ``[lower, upper]``, and ``upper`` upper-bounds the max-min gain of *every* unit-norm
156
+ combiner, so ``1/upper`` lower-bounds the zero-forcing MSE.
157
+ """
158
+ T, K, N = hs.shape
159
+ H = np.einsum("tkn,tkm->tknm", hs, hs.conj()) # h_k h_k^H
160
+ scale = np.max(np.sum(np.abs(hs) ** 2, axis=2), axis=1)[:, None]
161
+ w = np.full((T, K), 1.0 / K)
162
+ M_sum = np.zeros((T, N, N), dtype=complex)
163
+ upper = np.full(T, np.inf)
164
+ for it in range(1, iters + 1):
165
+ S = np.einsum("tk,tknm->tnm", w, H)
166
+ vals, vecs = np.linalg.eigh(S)
167
+ v = vecs[..., -1]
168
+ upper = np.minimum(upper, vals[..., -1])
169
+ M_sum += np.einsum("tn,tm->tnm", v, v.conj())
170
+ grad = np.abs(np.einsum("tkn,tn->tk", hs.conj(), v)) ** 2 # d lambda_max / d w_k
171
+ w = w * np.exp(-(2.0 / np.sqrt(it)) * grad / scale)
172
+ w /= w.sum(axis=1, keepdims=True)
173
+ M = M_sum / iters
174
+ lower = np.real(np.einsum("tkn,tnm,tkm->tk", hs.conj(), M, hs)).min(axis=1)
175
+ return M, lower, upper
176
+
177
+
178
+ def gaussian_randomization(
179
+ M: np.ndarray, hs: np.ndarray, L: int, rng: np.random.Generator
180
+ ) -> np.ndarray:
181
+ """Per trial, the best of ``L`` normalised draws ``m ~ CN(0, M)`` and the principal
182
+ eigenvector of ``M``, by the exact max-min objective. ``M [T, N, N]``, ``hs [T, K, N]``."""
183
+ T, N, _ = M.shape
184
+ vals, vecs = np.linalg.eigh((M + np.swapaxes(M.conj(), 1, 2)) / 2)
185
+ root = vecs * np.sqrt(np.maximum(vals, 0))[:, None, :]
186
+ z = rng.standard_normal((T, L, N, 2))
187
+ z = (z[..., 0] + 1j * z[..., 1]) / np.sqrt(2)
188
+ cand = np.einsum("tnj,tlj->tln", root, z)
189
+ cand = _unit(np.concatenate([cand, vecs[:, None, :, -1]], axis=1))
190
+ g = np.abs(np.einsum("tkn,tln->tlk", hs, cand.conj())) ** 2
191
+ pick = np.argmax(g.min(axis=2), axis=1)
192
+ return cand[np.arange(T), pick]
193
+
194
+
195
+ @register("receiver", "joint_mmse")
196
+ @dataclass
197
+ class JointMMSE:
198
+ """Alternating transceiver design for the MSE ``sum_k |a^H h_k b_k - 1|^2 + sigma^2 ||a||^2``.
199
+
200
+ * receive step: LMMSE ``a = (sum_k h~_k h~_k^H + sigma^2 I)^{-1} sum_k h~_k``, ``h~_k = h_k b_k``;
201
+ * transmit step (per device, exact): ``b_k = min(sqrt(P_k), 1/|c_k|) c_k^* / |c_k|``,
202
+ ``c_k = a^H h_k``.
203
+
204
+ Each step minimises the MSE in its block, so the MSE never increases. Starts from the
205
+ ``maxmin`` combiner. Returns ``m = a/||a||``; pair with ``optimal`` power control, which
206
+ re-optimises the transmit side for that ``m`` (and so can only lower the MSE further).
207
+ """
208
+
209
+ iters: int = 30
210
+
211
+ def __call__(self, h, p_max, noise_var):
212
+ if h.shape[-1] == 1:
213
+ return _ones(h)
214
+ a, _, _ = self.design(h, p_max, noise_var)
215
+ return _unit(a)
216
+
217
+ def design(self, h, p_max, noise_var):
218
+ """Run the alternation; returns ``(a, b, history)`` where ``history[i]`` is the
219
+ per-trial MSE after ``i`` iterations (``history[0]``: zero-forcing start)."""
220
+ _T, _K, N = h.shape
221
+ m = MaxMinCombiner(iters=150)(h, p_max, noise_var)
222
+ sp = np.sqrt(p_max)[None, :]
223
+ # initial transmit side: zero-forcing for m, scaled so the weakest device is at P_k
224
+ c = np.einsum("tkn,tn->tk", h, m.conj())
225
+ eta = (np.abs(c) ** 2 * p_max).min(axis=1)
226
+ b = np.sqrt(eta)[:, None] * c.conj() / np.abs(c) ** 2
227
+ eye = np.eye(N)[None]
228
+ a = m / np.sqrt(eta)[:, None]
229
+ history = [joint_mse(h, a, b, noise_var)]
230
+ for _ in range(self.iters):
231
+ ht = h * b[..., None]
232
+ A = np.einsum("tkn,tkm->tnm", ht, ht.conj()) + noise_var * eye
233
+ a = np.linalg.solve(A, ht.sum(axis=1)[..., None])[..., 0]
234
+ c = np.einsum("tkn,tn->tk", h, a.conj())
235
+ mag = np.maximum(np.abs(c), 1e-300)
236
+ b = np.minimum(sp, 1.0 / mag) * c.conj() / mag
237
+ history.append(joint_mse(h, a, b, noise_var))
238
+ return a, b, np.array(history)
239
+
240
+
241
+ def joint_mse(h, a, b, noise_var):
242
+ """``sum_k |a^H h_k b_k - 1|^2 + sigma^2 ||a||^2`` per trial (unnormalised ``a``)."""
243
+ c = np.einsum("tkn,tn->tk", h, a.conj())
244
+ return (np.abs(c * b - 1) ** 2).sum(axis=1) + noise_var * np.sum(np.abs(a) ** 2, axis=1)
@@ -0,0 +1,26 @@
1
+ """Paper reproductions (FEATURES R1-R3). Each module registers a ``reproduction`` entry:
2
+ a callable ``run(trials=None, quick=False, out=None) -> dict``; ``CHECKS[name](result)``
3
+ returns the tolerance checks that the reproduction CI enforces (``--check``).
4
+
5
+ aircompkit reproduce # list
6
+ aircompkit reproduce yang2020 --quick --check --out results/yang2020
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import Callable
12
+ from typing import Any
13
+
14
+ from aircompkit.reproduce import yang2020, zhu2020
15
+
16
+ CHECKS: dict[str, Callable[[dict[str, Any]], list[tuple[str, bool, str]]]] = {
17
+ "yang2020": yang2020.check, "zhu2020": zhu2020.check}
18
+
19
+
20
+ def report(name: str, res: dict[str, Any]) -> bool:
21
+ """Print the checks of reproduction ``name`` on ``res``; ``True`` when all pass."""
22
+ checks = CHECKS[name](res)
23
+ print(f"\nchecks ({name}):")
24
+ for label, ok, detail in checks:
25
+ print(f" [{'PASS' if ok else 'FAIL'}] {label}" + (f" ({detail})" if detail else ""))
26
+ return all(ok for _, ok, _ in checks)
@@ -0,0 +1,182 @@
1
+ """Reproduction: K. Yang, T. Jiang, Y. Shi, Z. Ding, "Federated learning via over-the-air
2
+ computation", IEEE Trans. Wireless Commun., 19(3), 2020 (arXiv:1812.11750), Figs. 4 and 5.
3
+
4
+ Setting (paper Sec. VI): ``K = 20`` single-antenna devices, i.i.d. ``h_k ~ CN(0, I_N)``,
5
+ all devices selected, ``phi_k = 1``. With the zero-forcing transmitter of Prop. 1, an MSE
6
+ target ``gamma`` is *feasible* when
7
+
8
+ Q = min_{m != 0} max_k ||m||^2 / |m^H h_k|^2 <= gamma (paper eq. (11))
9
+
10
+ Fig. 4 plots P(feasible) against gamma for N = 6; Fig. 5 plots it against N for
11
+ gamma in {2, 3, 4} dB. In AirCompKit, ``Q`` is exactly the MSE of a scenario with
12
+ ``P = sigma^2 = 1``, complex symbols, ``power_control = channel_inversion`` and the receiver
13
+ under test. ``maxmin`` stands in for the paper's global optimiser / DC method; ``sdr``
14
+ is SDR with Gaussian randomisation; the SDR upper bound gives a guaranteed lower bound on
15
+ ``Q`` and therefore an upper bound on P(feasible) for *any* combiner.
16
+
17
+ Reference values were read by eye from the published figures (about +/- 0.03), for
18
+ comparison only. Known deviation: the paper's SDR curve uses a feasibility-form SDR and is
19
+ much weaker than the max-min SDR + randomisation implemented here, so the SDR curves are
20
+ not expected to match.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import json
26
+ from pathlib import Path
27
+ from typing import Any
28
+
29
+ import numpy as np
30
+
31
+ from aircompkit.core.registry import register
32
+ from aircompkit.core.scenario import Scenario
33
+ from aircompkit.receiver import sdr_solve
34
+
35
+ K = 20
36
+ FIG4_N = 6
37
+ FIG4_GAMMA_DB = np.arange(-10, 36, 5)
38
+ FIG5_N = np.arange(2, 9)
39
+ FIG5_GAMMA_DB = (2.0, 3.0, 4.0)
40
+
41
+ # P(feasible) read from Fig. 5 (DC method), indexed by N = 2..8.
42
+ PAPER_FIG5 = {
43
+ 2.0: [0.00, 0.01, 0.10, 0.40, 0.77, 0.92, 0.99],
44
+ 3.0: [0.00, 0.14, 0.39, 0.78, 0.95, 0.97, 1.00],
45
+ 4.0: [0.02, 0.28, 0.64, 0.86, 0.99, 1.00, 1.00],
46
+ }
47
+ # Fig. 4 (N = 6): the global-optimum / DC curve is 0 at gamma = -5 dB and 1 at gamma = 5 dB.
48
+ PAPER_FIG4_GLOBAL = {-10.0: 0.0, -5.0: 0.0, 5.0: 1.0, 10.0: 1.0}
49
+
50
+
51
+ def zf_q_db(n_rx: int, receiver: Any, trials: int, seed: int) -> np.ndarray:
52
+ """Per-trial ``10 log10 Q`` for a receiver, via the Scenario API."""
53
+ sc = Scenario(
54
+ devices={"name": "fixed", "K": K, "p_max": 1.0},
55
+ channel={"name": "rayleigh", "n_rx": int(n_rx)},
56
+ power_control="channel_inversion",
57
+ receiver=receiver,
58
+ target="sum",
59
+ noise_var=1.0,
60
+ symbols="complex",
61
+ seed=seed,
62
+ )
63
+ return 10 * np.log10(sc.run(trials=trials, dim=0)["mse"])
64
+
65
+
66
+ def sdr_bound_q_db(n_rx: int, trials: int, seed: int) -> np.ndarray:
67
+ """``10 log10 (1 / SDR upper bound)``: no combiner can achieve a smaller ``Q``."""
68
+ from aircompkit.core.rng import SeedTree
69
+
70
+ sc = Scenario(devices={"name": "fixed", "K": K}, channel={"name": "rayleigh", "n_rx": int(n_rx)},
71
+ seed=seed)
72
+ h, _ = sc.channel.sample(SeedTree(seed).generator("channel"), trials, K)
73
+ _, _, upper = sdr_solve(h)
74
+ return -10 * np.log10(upper)
75
+
76
+
77
+ def feasibility(q_db: np.ndarray, gammas_db) -> list[float]:
78
+ return [float(np.mean(q_db <= g)) for g in gammas_db]
79
+
80
+
81
+ @register("reproduction", "yang2020")
82
+ def run(trials: int | None = None, quick: bool = False, out: str | Path | None = None,
83
+ seed: int = 0) -> dict[str, Any]:
84
+ """Reproduce Figs. 4–5. ``quick``: 60 trials (CI smoke test); default 500 (paper: 100)."""
85
+ T = trials or (60 if quick else 500)
86
+ res: dict[str, Any] = {"trials": T, "K": K, "seed": seed}
87
+
88
+ q = {name: zf_q_db(FIG4_N, name, T, seed) for name in ("maxmin", "sdr", "eigen")}
89
+ q["sdr_bound"] = sdr_bound_q_db(FIG4_N, T, seed)
90
+ res["fig4"] = {
91
+ "gamma_db": FIG4_GAMMA_DB.tolist(),
92
+ **{name: feasibility(v, FIG4_GAMMA_DB) for name, v in q.items()},
93
+ "median_q_db": {name: float(np.median(v)) for name, v in q.items()},
94
+ }
95
+
96
+ fig5: dict[str, Any] = {"n_rx": FIG5_N.tolist()}
97
+ q5 = {int(n): zf_q_db(int(n), "maxmin", T, seed) for n in FIG5_N}
98
+ for g in FIG5_GAMMA_DB:
99
+ fig5[f"maxmin_{g:g}dB"] = [float(np.mean(q5[int(n)] <= g)) for n in FIG5_N]
100
+ fig5[f"paper_{g:g}dB"] = PAPER_FIG5[g]
101
+ dev = [abs(a - b) for g in FIG5_GAMMA_DB
102
+ for a, b in zip(fig5[f"maxmin_{g:g}dB"], PAPER_FIG5[g])]
103
+ fig5["max_abs_deviation"] = float(max(dev))
104
+ fig5["mean_abs_deviation"] = float(np.mean(dev))
105
+ res["fig5"] = fig5
106
+
107
+ _print(res)
108
+ if out is not None:
109
+ out = Path(out)
110
+ out.mkdir(parents=True, exist_ok=True)
111
+ (out / "yang2020.json").write_text(json.dumps(res, indent=2))
112
+ _plot(res, out / "yang2020_fig4_fig5.png")
113
+ return res
114
+
115
+
116
+ def _print(res: dict[str, Any]) -> None:
117
+ f4 = res["fig4"]
118
+ print(f"Yang et al. 2020 Fig. 4: P(feasible) vs gamma, K={K}, N={FIG4_N}, {res['trials']} trials")
119
+ print("gamma dB " + " ".join(f"{g:6.0f}" for g in f4["gamma_db"]))
120
+ for name in ("maxmin", "sdr", "eigen", "sdr_bound"):
121
+ print(f"{name:>8} " + " ".join(f"{v:6.2f}" for v in f4[name]))
122
+ f5 = res["fig5"]
123
+ print("\nFig. 5: P(feasible) vs N (maxmin / paper)")
124
+ print(" N " + " ".join(f"{n:11d}" for n in f5["n_rx"]))
125
+ for g in FIG5_GAMMA_DB:
126
+ ours, ref = f5[f"maxmin_{g:g}dB"], f5[f"paper_{g:g}dB"]
127
+ print(f"{g:4.0f} dB " + " ".join(f"{a:5.2f}/{b:5.2f}" for a, b in zip(ours, ref)))
128
+ print(f"mean |ours - paper| = {f5['mean_abs_deviation']:.3f}, "
129
+ f"max = {f5['max_abs_deviation']:.3f}")
130
+
131
+
132
+ def _plot(res: dict[str, Any], path: Path) -> None:
133
+ try:
134
+ import matplotlib.pyplot as plt
135
+ except ImportError:
136
+ return
137
+ fig, (a, b) = plt.subplots(1, 2, figsize=(9.5, 3.6))
138
+ f4 = res["fig4"]
139
+ labels = {"maxmin": "max-min (AirCompKit)", "sdr": "SDR + randomisation",
140
+ "eigen": "eigen combiner", "sdr_bound": "SDR bound (any combiner)"}
141
+ styles = {"maxmin": "o-", "sdr": "s-", "eigen": "^-", "sdr_bound": "k:"}
142
+ for name, lab in labels.items():
143
+ a.plot(f4["gamma_db"], f4[name], styles[name], ms=4, label=lab)
144
+ a.plot(list(PAPER_FIG4_GLOBAL), list(PAPER_FIG4_GLOBAL.values()), "D", mfc="none", ms=8,
145
+ color="tab:red", label="paper: global opt. / DC")
146
+ a.set_xlabel(r"MSE target $\gamma$ (dB)")
147
+ a.set_ylabel("probability of feasibility")
148
+ a.set_title(f"(a) cf. Yang et al. Fig. 4 (K={K}, N={FIG4_N})", fontsize=9)
149
+ a.grid(alpha=0.3)
150
+ a.legend(fontsize=7)
151
+ f5 = res["fig5"]
152
+ for g, c in zip(FIG5_GAMMA_DB, ("tab:blue", "tab:orange", "tab:green")):
153
+ b.plot(f5["n_rx"], f5[f"maxmin_{g:g}dB"], "o-", color=c, ms=4,
154
+ label=rf"AirCompKit, $\gamma$={g:g} dB")
155
+ b.plot(f5["n_rx"], f5[f"paper_{g:g}dB"], "x--", color=c, ms=6, lw=0.8,
156
+ label=rf"paper, $\gamma$={g:g} dB")
157
+ b.set_xlabel("number of BS antennas N")
158
+ b.set_title(f"(b) cf. Yang et al. Fig. 5 (K={K})", fontsize=9)
159
+ b.grid(alpha=0.3)
160
+ b.legend(fontsize=7)
161
+ fig.tight_layout()
162
+ fig.savefig(path, dpi=160)
163
+ print(f"saved {path}")
164
+
165
+
166
+ def check(res: dict[str, Any]) -> list[tuple[str, bool, str]]:
167
+ """Tolerance checks used by ``aircompkit reproduce yang2020 --check`` (reproduction CI)."""
168
+ f4, f5 = res["fig4"], res["fig5"]
169
+ g = f4["gamma_db"]
170
+ mm = dict(zip(g, f4["maxmin"]))
171
+ out = [
172
+ ("Fig. 4: max-min infeasible at -5 dB (paper: 0)", mm[-5] <= 0.05, f"{mm[-5]:.2f}"),
173
+ ("Fig. 4: max-min feasible at 5 dB (paper: 1)", mm[5] >= 0.95, f"{mm[5]:.2f}"),
174
+ ]
175
+ worst = max(f4[n][i] - f4["sdr_bound"][i] for n in ("maxmin", "sdr", "eigen") for i in range(len(g)))
176
+ out.append(("Fig. 4: no combiner beats the SDR bound", worst <= 1e-12, f"max excess {worst:.2g}"))
177
+ mono = all(a <= b for gg in FIG5_GAMMA_DB
178
+ for a, b in zip(f5[f"maxmin_{gg:g}dB"], f5[f"maxmin_{gg:g}dB"][1:]))
179
+ out.append(("Fig. 5: feasibility grows with N", mono, ""))
180
+ out.append(("Fig. 5: mean |AirCompKit - paper| <= 0.15", f5["mean_abs_deviation"] <= 0.15,
181
+ f"{f5['mean_abs_deviation']:.3f}"))
182
+ return out