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
aircompkit/__init__.py ADDED
@@ -0,0 +1,32 @@
1
+ """AirCompKit: security-aware over-the-air computation simulator."""
2
+
3
+ __version__ = "1.0.0"
4
+
5
+ # Importing the component packages registers their components.
6
+ from aircompkit import ( # noqa: F401
7
+ adversary,
8
+ aircomp,
9
+ channel,
10
+ defense,
11
+ devices,
12
+ learning,
13
+ metrics,
14
+ receiver,
15
+ reproduce,
16
+ )
17
+ from aircompkit.core.registry import KINDS, available, build, get, register
18
+ from aircompkit.core.result import Result
19
+ from aircompkit.core.rng import SeedTree
20
+ from aircompkit.core.scenario import Scenario
21
+
22
+ __all__ = [
23
+ "KINDS",
24
+ "Result",
25
+ "Scenario",
26
+ "SeedTree",
27
+ "__version__",
28
+ "available",
29
+ "build",
30
+ "get",
31
+ "register",
32
+ ]
aircompkit/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from aircompkit.cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,175 @@
1
+ """Threat model and attack library (FEATURES §5).
2
+
3
+ A ``ThreatModel`` says *who* attacks (a fixed set of ``n_attackers`` devices or a
4
+ ``fraction``), *what they know* (``knowledge``) and *how much power* they may use
5
+ (``max_boost_db``), plus an optional external ``jammer``. Attacks declare what they
6
+ ``need``; building a threat model whose attack needs more than it grants is an error (T5),
7
+ so results always state their assumptions.
8
+
9
+ Attacks act on the array-level path (``aircompkit.learning.array``): honest devices send
10
+ ``t_k = b_k x_k`` with unit-power symbols ``x_k`` and AirComp pre-equaliser ``b_k``; an
11
+ attacker replaces its row via ``transmit(x_own, b_own, ctx)``, may distort the server's CSI
12
+ of its own channel (``distort_csi``), or poison its local labels (``poisons_labels``).
13
+ ``boost_db`` is the attacker's power over what the power-control rule prescribes.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from dataclasses import dataclass, field
19
+ from typing import Any
20
+
21
+ import numpy as np
22
+
23
+ from aircompkit.channel import _cn
24
+ from aircompkit.core.registry import build, register
25
+
26
+ KNOWLEDGE = frozenset({"own_data", "own_csi", "honest_mean", "receiver"})
27
+
28
+
29
+ @dataclass
30
+ class Attack:
31
+ """Base class for attacks: subclass it, override ``transmit`` (and optionally ``distort_csi``,
32
+ ``flip_labels``), set ``needs``, and register with ``@register("attack", name)``."""
33
+
34
+ boost_db: float = 0.0
35
+ needs = frozenset({"own_data"})
36
+ poisons_labels = False
37
+
38
+ @property
39
+ def gain(self) -> float:
40
+ return float(10 ** (self.boost_db / 20))
41
+
42
+ def transmit(self, x, b, ctx):
43
+ return self.gain * x * b[:, None]
44
+
45
+ def distort_csi(self, h_est):
46
+ return h_est
47
+
48
+ def flip_labels(self, y, n_classes):
49
+ return y
50
+
51
+
52
+ @register("attack", "gaussian")
53
+ @dataclass
54
+ class GaussianNoise(Attack):
55
+ """Transmit ``CN(0, P_k)`` noise at the boosted power limit (jamming from inside)."""
56
+
57
+ needs = frozenset()
58
+
59
+ def transmit(self, x, b, ctx):
60
+ P = np.asarray(ctx["p_max"], float)[:, None]
61
+ return self.gain * np.sqrt(P) * _cn(ctx["rng"], x.shape)
62
+
63
+
64
+ @register("attack", "sign_flip")
65
+ @dataclass
66
+ class SignFlip(Attack):
67
+ """Send ``-x_k`` (own update reversed) with power boost; independent across attackers."""
68
+
69
+ def transmit(self, x, b, ctx):
70
+ return -self.gain * x * b[:, None]
71
+
72
+
73
+ @register("attack", "scaled")
74
+ @dataclass
75
+ class Scaled(Attack):
76
+ """Send the own honest update with a power boost (pure power-control violation)."""
77
+
78
+
79
+ @register("attack", "collude")
80
+ @dataclass
81
+ class Collude(Attack):
82
+ """Omniscient colluders: all send the same unit-power vector opposite to the honest mean
83
+ (rank-1 attack, the hardest for spatial detection)."""
84
+
85
+ needs = frozenset({"honest_mean"})
86
+
87
+ def transmit(self, x, b, ctx):
88
+ g = ctx["gref"]
89
+ v = -g / np.sqrt(max(float(np.mean(np.abs(g) ** 2)), 1e-300))
90
+ return self.gain * v[None, :] * b[:, None]
91
+
92
+
93
+ @register("attack", "misalign")
94
+ @dataclass
95
+ class Misalign(Attack):
96
+ """Rotate the own (honest) signal by ``phase`` radians: destructive superposition without
97
+ changing the payload; ``phase = pi`` equals ``sign_flip``."""
98
+
99
+ phase: float = float(np.pi / 2)
100
+
101
+ def transmit(self, x, b, ctx):
102
+ return self.gain * np.exp(1j * self.phase) * x * b[:, None]
103
+
104
+
105
+ @register("attack", "label_flip")
106
+ @dataclass
107
+ class LabelFlip(Attack):
108
+ """Data poisoning: train on labels ``y -> C - 1 - y``, then transmit like an honest device."""
109
+
110
+ poisons_labels = True
111
+
112
+ def flip_labels(self, y, n_classes):
113
+ return n_classes - 1 - y
114
+
115
+
116
+ @register("attack", "csi_spoof")
117
+ @dataclass
118
+ class CSISpoof(Attack):
119
+ """Pilot manipulation: the attacker makes its channel look ``factor`` times weaker. With
120
+ channel inversion the weakest device sets the receive scaling, so every device's SNR drops,
121
+ and the attacker's own row arrives ``1/factor`` times too strong."""
122
+
123
+ factor: float = 0.1
124
+ needs = frozenset({"own_data", "own_csi"})
125
+
126
+ def distort_csi(self, h_est):
127
+ return self.factor * h_est
128
+
129
+
130
+ @dataclass
131
+ class ThreatModel:
132
+ attack: Any = "sign_flip"
133
+ n_attackers: int = 0
134
+ fraction: float | None = None
135
+ knowledge: list[str] = field(default_factory=lambda: ["own_data", "own_csi"])
136
+ max_boost_db: float | None = None
137
+ jammer: dict[str, float] | None = None
138
+ seed: int = 0
139
+
140
+ def __post_init__(self) -> None:
141
+ self.attack = build("attack", self.attack)
142
+ unknown = set(self.knowledge) - KNOWLEDGE
143
+ if unknown:
144
+ raise ValueError(f"unknown knowledge flags {sorted(unknown)}; allowed {sorted(KNOWLEDGE)}")
145
+ missing = set(self.attack.needs) - set(self.knowledge)
146
+ if missing:
147
+ raise ValueError(
148
+ f"attack {type(self.attack).__name__} needs knowledge {sorted(missing)} that the "
149
+ "threat model does not grant (add it to 'knowledge')")
150
+ if self.max_boost_db is not None and self.attack.boost_db > self.max_boost_db:
151
+ raise ValueError(f"boost_db {self.attack.boost_db} exceeds max_boost_db {self.max_boost_db}")
152
+ if self.fraction is not None and not 0 <= self.fraction < 1:
153
+ raise ValueError("fraction must be in [0, 1)")
154
+ if self.jammer is not None and self.jammer.get("power", 0) < 0:
155
+ raise ValueError("jammer power must be >= 0")
156
+
157
+ def attackers(self, K: int) -> np.ndarray:
158
+ n = round(self.fraction * K) if self.fraction is not None else self.n_attackers
159
+ if not 0 <= n < K:
160
+ raise ValueError(f"need 0 <= attackers < K, got {n} of {K}")
161
+ rng = np.random.default_rng(self.seed)
162
+ return np.sort(rng.choice(K, n, replace=False)) if n else np.zeros(0, int)
163
+
164
+ def to_dict(self) -> dict[str, Any]:
165
+ from aircompkit.core.registry import spec_of
166
+
167
+ return {"attack": spec_of("attack", self.attack), "n_attackers": self.n_attackers,
168
+ "fraction": self.fraction, "knowledge": list(self.knowledge),
169
+ "max_boost_db": self.max_boost_db, "jammer": self.jammer, "seed": self.seed}
170
+
171
+
172
+ def as_threat(x: ThreatModel | dict[str, Any] | None) -> ThreatModel | None:
173
+ if x is None or isinstance(x, ThreatModel):
174
+ return x
175
+ return ThreatModel(**x)
@@ -0,0 +1,41 @@
1
+ """AirComp transmitter side: target functions and power control (FEATURES A1, A3, A8)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+ from aircompkit.aircomp.power_control import (
8
+ ChannelInversion,
9
+ FullPower,
10
+ OptimalPowerControl,
11
+ TruncatedInversion,
12
+ )
13
+ from aircompkit.core.registry import register
14
+
15
+
16
+ @register("aircomp", "sum")
17
+ @dataclass
18
+ class Sum:
19
+ """Target ``f = sum_k x_k``."""
20
+
21
+ def scale(self, K: int) -> float:
22
+ return 1.0
23
+
24
+
25
+ @register("aircomp", "mean")
26
+ @dataclass
27
+ class Mean:
28
+ """Target ``f = (1/K) sum_k x_k``. The receiver divides the sum estimate by ``K``."""
29
+
30
+ def scale(self, K: int) -> float:
31
+ return 1.0 / K
32
+
33
+
34
+ __all__ = [
35
+ "ChannelInversion",
36
+ "FullPower",
37
+ "Mean",
38
+ "OptimalPowerControl",
39
+ "Sum",
40
+ "TruncatedInversion",
41
+ ]
@@ -0,0 +1,42 @@
1
+ """Closed-form AirComp MSE expressions, used for validation and as plot references.
2
+
3
+ All expressions follow the model in ``aircompkit.aircomp.power_control`` and use the
4
+ *effective* noise variance (``sigma^2`` for complex symbols, ``sigma^2/2`` for real ones).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Sequence
10
+
11
+ import numpy as np
12
+
13
+
14
+ def channel_inversion_awgn_mse(
15
+ gains: Sequence[float], p_max: float | Sequence[float], noise_var: float
16
+ ) -> float:
17
+ """Non-fading channel ``|h_k|^2 = gains_k``: ``MSE = sigma^2 / min_k P_k g_k``."""
18
+ g = np.asarray(gains, float)
19
+ p = np.broadcast_to(np.asarray(p_max, float), g.shape)
20
+ return float(noise_var / np.min(p * g))
21
+
22
+
23
+ def truncated_inversion_rayleigh_mse(
24
+ mean_gains: Sequence[float],
25
+ p_max: float | Sequence[float],
26
+ threshold: float,
27
+ noise_var: float,
28
+ relative: bool = True,
29
+ ) -> float:
30
+ """Average MSE of truncated channel inversion under Rayleigh fading.
31
+
32
+ With ``|h_k|^2 ~ Exp(mean beta_k)``, device ``k`` is silent with probability
33
+ ``q_k = 1 - exp(-thr_k / beta_k)`` and then contributes error 1; ``eta = min_k P_k thr_k``
34
+ is deterministic, so
35
+
36
+ E[MSE] = sum_k q_k + sigma^2 / eta.
37
+ """
38
+ beta = np.asarray(mean_gains, float)
39
+ p = np.broadcast_to(np.asarray(p_max, float), beta.shape)
40
+ thr = threshold * beta if relative else np.full_like(beta, threshold)
41
+ q = 1.0 - np.exp(-thr / beta)
42
+ return float(q.sum() + noise_var / np.min(p * thr))
@@ -0,0 +1,183 @@
1
+ """Transmit power control for single-antenna AirComp (FEATURES A3).
2
+
3
+ System model (per vector entry, per trial)::
4
+
5
+ y = sum_k h_k b_k x_k + n, n ~ CN(0, sigma^2), |b_k|^2 = p_k <= P_k
6
+ f_hat = y / sqrt(eta) (estimate of f = sum_k x_k)
7
+
8
+ All schemes use phase-aligned pre-scaling ``b_k = sqrt(p_k) h_k^* / |h_k|``, so device ``k``
9
+ arrives with real amplitude ``sqrt(p_k g_k)`` where ``g_k = |h_k|^2``. With unit-power,
10
+ independent symbols the conditional MSE is
11
+
12
+ MSE = sum_k (sqrt(p_k g_k / eta) - 1)^2 + sigma_eff^2 / eta
13
+
14
+ where ``sigma_eff^2`` is ``sigma^2`` for complex symbols and ``sigma^2/2`` for real symbols
15
+ (the receiver keeps the real part). A scheme maps ``(g, beta, P, sigma_eff^2)`` to
16
+ ``(p, eta)``; ``g, beta`` have shape ``[trials, K]``, ``P`` shape ``[K]``, and the outputs
17
+ have shapes ``[trials, K]`` and ``[trials]``.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from dataclasses import dataclass
23
+
24
+ import numpy as np
25
+
26
+ from aircompkit.core.registry import register
27
+
28
+ _TINY = 1e-300
29
+ _EULER_GAMMA = 0.5772156649015329
30
+
31
+
32
+ def exp1(x: float) -> float:
33
+ """Exponential integral ``E_1(x) = int_x^inf e^{-t}/t dt`` for ``x > 0`` (NumPy-free scalar).
34
+
35
+ Power series for ``x <= 1``; modified-Lentz continued fraction otherwise. Relative
36
+ accuracy ~1e-14.
37
+ """
38
+ if x <= 0:
39
+ raise ValueError("exp1 needs x > 0")
40
+ if x <= 1.0:
41
+ total, term, n = 0.0, 1.0, 1
42
+ while True:
43
+ term *= -x / n
44
+ add = -term / n
45
+ total += add
46
+ if abs(add) < 1e-17 * abs(total) or n > 200:
47
+ break
48
+ n += 1
49
+ return -_EULER_GAMMA - float(np.log(x)) + total
50
+ # E_1(x) = e^{-x} / (x + 1 - 1/(x + 3 - 4/(x + 5 - ...)))
51
+ tiny = 1e-300
52
+ b = x + 1.0
53
+ c = 1.0 / tiny
54
+ d = 1.0 / b
55
+ f = d
56
+ for i in range(1, 300):
57
+ a = -float(i * i)
58
+ b += 2.0
59
+ d = 1.0 / (a * d + b)
60
+ c = b + a / c
61
+ delta = c * d
62
+ f *= delta
63
+ if abs(delta - 1.0) < 1e-16:
64
+ break
65
+ return float(f * np.exp(-x))
66
+
67
+
68
+ @register("power_control", "channel_inversion")
69
+ @dataclass
70
+ class ChannelInversion:
71
+ """Zero-forcing: every device inverts its channel; ``eta = min_k P_k g_k``.
72
+
73
+ Error-free alignment, but the weakest device sets ``eta``. Under Rayleigh fading the
74
+ *average* MSE is infinite (``E[1/min_k g_k]`` diverges), which is why truncation exists.
75
+ """
76
+
77
+ def __call__(self, g, beta, p_max, noise_var):
78
+ eta = np.min(p_max[None, :] * g, axis=1)
79
+ with np.errstate(divide="ignore", invalid="ignore"):
80
+ p = np.where(g > 0, eta[:, None] / g, 0.0)
81
+ return p, eta
82
+
83
+
84
+ @register("power_control", "truncated_inversion")
85
+ @dataclass
86
+ class TruncatedInversion:
87
+ """Truncated channel inversion (Zhu, Wang & Huang, IEEE TWC 2020).
88
+
89
+ Device ``k`` transmits only if ``g_k >= thr_k`` and then inverts its channel; otherwise
90
+ it is silent. ``thr_k = threshold * beta_k`` when ``relative`` (threshold on small-scale
91
+ fading, the usual choice under path loss), else ``thr_k = threshold``.
92
+
93
+ ``budget="peak"`` (default): ``p_k <= P_k`` on every channel use, so
94
+ ``eta = min_k P_k thr_k``. ``budget="average"``: ``E[p_k] <= P_k`` over Rayleigh fading,
95
+ as in Zhu et al. Since ``E[1/g; g >= threshold beta] = E_1(threshold) / beta`` for
96
+ ``g ~ Exp(mean beta)``, ``eta = min_k P_k beta_k / E_1(threshold)`` (paper eq. (15)); this
97
+ needs ``relative=True`` and Rayleigh fading, and instantaneous power may exceed ``P_k``.
98
+ Either way ``eta`` is fixed by the threshold, so the noise term never blows up.
99
+ """
100
+
101
+ threshold: float = 0.1
102
+ relative: bool = True
103
+ budget: str = "peak"
104
+
105
+ def __post_init__(self) -> None:
106
+ if self.threshold <= 0:
107
+ raise ValueError("threshold must be positive")
108
+ if self.budget not in ("peak", "average"):
109
+ raise ValueError("budget must be 'peak' or 'average'")
110
+ if self.budget == "average" and not self.relative:
111
+ raise ValueError("budget='average' needs relative=True")
112
+
113
+ @property
114
+ def peak_constrained(self) -> bool:
115
+ return self.budget == "peak"
116
+
117
+ def __call__(self, g, beta, p_max, noise_var):
118
+ thr = self.threshold * (beta if self.relative else np.ones_like(g))
119
+ if self.budget == "average":
120
+ eta = np.min(p_max[None, :] * beta, axis=1) / exp1(self.threshold)
121
+ else:
122
+ eta = np.min(p_max[None, :] * thr, axis=1)
123
+ active = g >= thr
124
+ with np.errstate(divide="ignore", invalid="ignore"):
125
+ p = np.where(active, eta[:, None] / g, 0.0)
126
+ return p, eta
127
+
128
+
129
+ @register("power_control", "full_power")
130
+ @dataclass
131
+ class FullPower:
132
+ """Every device transmits at ``P_k``; the receiver picks the MSE-optimal ``eta``.
133
+
134
+ For fixed ``p``, ``MSE(t = 1/sqrt(eta))`` is a convex quadratic with minimiser
135
+ ``t* = sum_k sqrt(G_k) / (sigma^2 + sum_k G_k)``, ``G_k = P_k g_k``.
136
+ """
137
+
138
+ def __call__(self, g, beta, p_max, noise_var):
139
+ G = p_max[None, :] * g
140
+ t = np.sqrt(G).sum(axis=1) / (noise_var + G.sum(axis=1))
141
+ eta = 1.0 / np.maximum(t, _TINY) ** 2
142
+ return np.broadcast_to(p_max, g.shape).copy(), eta
143
+
144
+
145
+ @register("power_control", "optimal")
146
+ @dataclass
147
+ class OptimalPowerControl:
148
+ """MSE-optimal power control (Cao, Zhu, Xu & Huang, IEEE TWC 2020).
149
+
150
+ Optimal structure: for a given ``eta``, devices with ``G_k = P_k g_k >= eta`` invert their
151
+ channel (zero error) and the rest transmit at full power. Sort ``G`` ascending; if exactly
152
+ the ``i`` weakest devices are at full power, ``MSE(eta)`` is convex in ``1/sqrt(eta)`` with
153
+ stationary point ``eta_i = ((sigma^2 + S1_i) / S2_i)^2`` (``S1_i = sum_{k<=i} G_k``,
154
+ ``S2_i = sum_{k<=i} sqrt(G_k)``). Clip ``eta_i`` to ``[G_i, G_{i+1}]``, evaluate, and take
155
+ the best of these ``K`` candidates and ``eta = G_1`` (pure inversion). Exact, ``O(K log K)``
156
+ per trial, vectorised over trials.
157
+ """
158
+
159
+ def __call__(self, g, beta, p_max, noise_var):
160
+ T, K = g.shape
161
+ G = p_max[None, :] * g
162
+ Gs = np.sort(G, axis=1)
163
+ S1 = np.cumsum(Gs, axis=1)
164
+ S2 = np.maximum(np.cumsum(np.sqrt(Gs), axis=1), _TINY)
165
+ n_full = np.arange(1, K + 1)
166
+
167
+ upper = np.concatenate([Gs[:, 1:], np.full((T, 1), np.inf)], axis=1)
168
+ eta_c = np.clip(((noise_var + S1) / S2) ** 2, Gs, upper)
169
+ eta_c = np.maximum(eta_c, _TINY)
170
+ mse_c = (S1 + noise_var) / eta_c - 2 * S2 / np.sqrt(eta_c) + n_full
171
+
172
+ best = np.argmin(mse_c, axis=1)
173
+ rows = np.arange(T)
174
+ eta = eta_c[rows, best]
175
+ mse_best = mse_c[rows, best]
176
+
177
+ g1 = np.maximum(Gs[:, 0], _TINY)
178
+ use_inversion = noise_var / g1 <= mse_best
179
+ eta = np.where(use_inversion, g1, eta)
180
+
181
+ with np.errstate(divide="ignore", invalid="ignore"):
182
+ p = np.where(g > 0, np.minimum(p_max[None, :], eta[:, None] / g), p_max[None, :])
183
+ return p, eta
@@ -0,0 +1,48 @@
1
+ """Transmitter-side pre-processing (FEATURES A2): normalisation, clipping, quantisation.
2
+
3
+ These operate on update vectors ``x [..., K, d]`` before AirComp. The learning loop (P3)
4
+ uses them; they are exposed here so that they can also be studied in computation mode.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import numpy as np
10
+
11
+
12
+ def normalize(x: np.ndarray, axis: tuple[int, ...] | int = (-2, -1)) -> tuple[np.ndarray, float, float]:
13
+ """Zero-mean, unit-variance normalisation with *shared* statistics (as in OTA-FL, where
14
+ the server broadcasts mean and std so that devices scale identically and the sum is
15
+ recoverable). Returns ``(x_n, mu, sd)``; undo the sum with ``denormalize_sum``."""
16
+ mu = float(np.mean(x, axis=axis).mean())
17
+ sd = float(np.std(x - mu))
18
+ sd = sd if sd > 0 else 1.0
19
+ return (x - mu) / sd, mu, sd
20
+
21
+
22
+ def denormalize_sum(f_hat: np.ndarray, mu: float, sd: float, K: int) -> np.ndarray:
23
+ """Map an estimate of ``sum_k x_n,k`` back to an estimate of ``sum_k x_k``."""
24
+ return f_hat * sd + K * mu
25
+
26
+
27
+ def clip_norm(x: np.ndarray, max_norm: float) -> np.ndarray:
28
+ """Scale each device's vector (last axis) to L2 norm at most ``max_norm``."""
29
+ n = np.linalg.norm(x, axis=-1, keepdims=True)
30
+ return x * np.minimum(1.0, max_norm / np.maximum(n, 1e-300))
31
+
32
+
33
+ def stochastic_quantize(
34
+ x: np.ndarray, bits: int, clip: float, rng: np.random.Generator
35
+ ) -> np.ndarray:
36
+ """Unbiased stochastic uniform quantisation on ``[-clip, clip]`` with ``2^bits`` levels.
37
+
38
+ Values are first clipped to the range; inside it ``E[Q(x)] = x`` and the error variance
39
+ is at most ``Delta^2 / 4`` with ``Delta = 2 clip / (2^bits - 1)``.
40
+ """
41
+ if bits < 1 or clip <= 0:
42
+ raise ValueError("need bits >= 1 and clip > 0")
43
+ levels = 2**bits - 1
44
+ delta = 2 * clip / levels
45
+ u = (np.clip(x, -clip, clip) + clip) / delta # in [0, levels]
46
+ lo = np.floor(u)
47
+ q = lo + (rng.random(np.shape(x)) < (u - lo))
48
+ return np.minimum(q, levels) * delta - clip
aircompkit/bench.py ADDED
@@ -0,0 +1,159 @@
1
+ """Performance benchmarks (``aircompkit bench``).
2
+
3
+ Three groups, each timed with the best of ``repeat`` wall-clock runs after one warm-up:
4
+
5
+ * ``mse``: ``Scenario.run`` throughput (channel realisations per second) for growing
6
+ ``K``, analytical only (``dim = 0``) and with signal-level Monte Carlo (``dim = 32``);
7
+ * ``receiver``: receive-beamformer design time per channel realisation (``K = 20``);
8
+ * ``fl``: over-the-air federated learning rounds per second on an MNIST-sized synthetic task (784-64-10 MLP), on the
9
+ broadband (real) path and on the array path with and without a defence (group geometric median).
10
+
11
+ Results carry the machine description (CPU count, platform, NumPy version), so numbers from
12
+ different machines can be told apart. Only NumPy is used; nothing runs on a GPU.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import os
19
+ import platform
20
+ import time
21
+ from collections.abc import Callable
22
+ from functools import partial
23
+ from pathlib import Path
24
+ from typing import Any
25
+
26
+ import numpy as np
27
+
28
+ from aircompkit import __version__
29
+
30
+
31
+ def _best(fn: Callable[[], Any], repeat: int) -> float:
32
+ fn() # warm-up (imports, caches)
33
+ best = float("inf")
34
+ for _ in range(repeat):
35
+ t = time.perf_counter()
36
+ fn()
37
+ best = min(best, time.perf_counter() - t)
38
+ return best
39
+
40
+
41
+ def machine() -> dict[str, Any]:
42
+ return {"aircompkit": __version__, "numpy": np.__version__, "python": platform.python_version(),
43
+ "platform": platform.platform(), "processor": platform.processor() or platform.machine(),
44
+ "cpu_count": os.cpu_count()}
45
+
46
+
47
+ def bench_mse(quick: bool, repeat: int) -> list[dict[str, Any]]:
48
+ from aircompkit.core.scenario import Scenario
49
+
50
+ rows = []
51
+ trials = 200 if quick else 2000
52
+ for K in ((20, 200) if quick else (20, 100, 1000)):
53
+ for pc in ("channel_inversion", "optimal"):
54
+ for dim in (0, 32):
55
+ sc = Scenario(devices={"name": "uniform_disc", "K": K, "r_min": 10, "r_max": 100},
56
+ channel={"name": "rayleigh", "pathloss": {"exponent": 3.0, "ref_gain_db": -30}},
57
+ power_control=pc, receiver="eigen", noise_var=1e-10, seed=0)
58
+ t = _best(partial(sc.run, trials=trials, dim=dim), repeat)
59
+ rows.append({"K": K, "power_control": pc, "dim": dim, "trials": trials,
60
+ "seconds": t, "trials_per_s": trials / t})
61
+ return rows
62
+
63
+
64
+ def bench_receiver(quick: bool, repeat: int) -> list[dict[str, Any]]:
65
+ from aircompkit.core.registry import build
66
+ from aircompkit.core.rng import SeedTree
67
+ from aircompkit.core.scenario import Scenario
68
+
69
+ rows = []
70
+ trials = 20 if quick else 100
71
+ for N in ((4, 16) if quick else (4, 8, 16, 32)):
72
+ sc = Scenario(devices={"name": "fixed", "K": 20}, channel={"name": "rayleigh", "n_rx": N},
73
+ power_control="channel_inversion", symbols="complex", seed=0)
74
+ h, _ = sc.channel.sample(SeedTree(0).generator("channel"), trials, 20)
75
+ p_max = np.ones(20)
76
+ for name in ("eigen", "maxmin", "sdr", "joint_mmse"):
77
+ rx = build("receiver", name)
78
+ t = _best(partial(rx, h, p_max, 1.0), repeat)
79
+ rows.append({"receiver": name, "K": 20, "N": N, "trials": trials,
80
+ "ms_per_realisation": 1e3 * t / trials})
81
+ return rows
82
+
83
+
84
+ def bench_fl(quick: bool, repeat: int) -> list[dict[str, Any]]:
85
+ from aircompkit.core.scenario import Scenario
86
+ from aircompkit.learning import FederatedConfig, train
87
+ from aircompkit.learning.data import synthetic
88
+
89
+ data = synthetic(n_train=4000, n_test=1000, dim=784, n_classes=10, seed=0) # MNIST-sized
90
+ rounds = 5 if quick else 20
91
+ base: dict[str, Any] = {"dataset": data, "model": {"name": "mlp", "hidden": [64]}, "rounds": rounds,
92
+ "eval_every": rounds, "batch_size": 32, "lr": 0.1, "seed": 0}
93
+ real = Scenario(devices={"name": "fixed", "K": 20, "p_max": 1.0}, channel={"name": "rayleigh", "n_rx": 4},
94
+ power_control="channel_inversion", receiver="eigen", noise_var=0.1, seed=0)
95
+ arr = real.replace(receiver="maxmin", symbols="complex", channel={"name": "rayleigh", "n_rx": 16})
96
+ threat = {"attack": {"name": "sign_flip", "boost_db": 10}, "n_attackers": 3}
97
+ cases: list[tuple[str, Scenario, dict[str, Any]]] = [
98
+ ("broadband, eigen, N=4", real, {"subchannels": 8}),
99
+ ("array, maxmin, N=16", arr, {"clip": 0.2}),
100
+ ("array + group GM, 3 attackers", arr, {"clip": 0.2, "threat": threat, "defense": "group_gm"})]
101
+ rows = []
102
+ for label, sc, kw in cases:
103
+ t = _best(partial(train, sc, FederatedConfig(**{**base, **kw})), repeat)
104
+ rows.append({"case": label, "K": 20, "params": None, "rounds": rounds,
105
+ "rounds_per_s": rounds / t})
106
+ from aircompkit.learning.models import MLP
107
+
108
+ n_params = MLP(d_in=data.dim, n_classes=data.n_classes, hidden=[64]).size
109
+ for r in rows:
110
+ r["params"] = n_params
111
+ return rows
112
+
113
+
114
+ GROUPS: dict[str, Callable[[bool, int], list[dict[str, Any]]]] = {
115
+ "mse": bench_mse, "receiver": bench_receiver, "fl": bench_fl}
116
+
117
+
118
+ def run(groups=tuple(GROUPS), quick: bool = False, repeat: int = 3,
119
+ out: str | Path | None = None) -> dict[str, Any]:
120
+ res: dict[str, Any] = {"machine": machine(), "quick": quick, "repeat": repeat}
121
+ for g in groups:
122
+ res[g] = GROUPS[g](quick, repeat)
123
+ print(format_group(g, res[g]), flush=True)
124
+ if out is not None:
125
+ out = Path(out)
126
+ out.mkdir(parents=True, exist_ok=True)
127
+ (out / "bench.json").write_text(json.dumps(res, indent=2))
128
+ (out / "bench.md").write_text(to_markdown(res))
129
+ print(f"saved {out / 'bench.json'} and {out / 'bench.md'}")
130
+ return res
131
+
132
+
133
+ def _fmt(v: Any) -> str:
134
+ if isinstance(v, float):
135
+ return f"{v:.3g}"
136
+ return str(v)
137
+
138
+
139
+ def format_group(name: str, rows: list[dict[str, Any]]) -> str:
140
+ cols = [c for c in rows[0] if c != "seconds"]
141
+ lines = [f"[{name}]", " " + " | ".join(cols)]
142
+ lines += [" " + " | ".join(_fmt(r[c]) for c in cols) for r in rows]
143
+ return "\n".join(lines)
144
+
145
+
146
+ def to_markdown(res: dict[str, Any]) -> str:
147
+ m = res["machine"]
148
+ head = (f"# AirCompKit benchmarks\n\n{m['processor']}, {m['cpu_count']} logical CPUs, "
149
+ f"{m['platform']}, Python {m['python']}, NumPy {m['numpy']}, "
150
+ f"AirCompKit {m['aircompkit']}. Best of {res['repeat']} runs.\n")
151
+ out = [head]
152
+ for g in GROUPS:
153
+ if g not in res:
154
+ continue
155
+ rows = res[g]
156
+ cols = [c for c in rows[0] if c != "seconds"]
157
+ out.append(f"\n## {g}\n\n| " + " | ".join(cols) + " |\n|" + "---|" * len(cols))
158
+ out += ["| " + " | ".join(_fmt(r[c]) for c in cols) + " |" for r in rows]
159
+ return "\n".join(out) + "\n"