Spaces:
Sleeping
Sleeping
Download fl/dp.py from rk147/federated_learning_model: direct link, hf CLI and curl.
- Browser
- Download file 2 kB
-
https://huggingface.co/spaces/rk147/federated_learning_model/resolve/main/fl/dp.py
- Command line
-
hf download hf://spaces/rk147/federated_learning_model/fl/dp.py
-
curl -L -o dp.py https://huggingface.co/spaces/rk147/federated_learning_model/resolve/main/fl/dp.py
2 kB
| """Differential-privacy primitives. | |
| * clip_sum: per-example gradient clipping (bounds each patient's influence). | |
| * epsilon: RDP accountant for the Poisson-subsampled Gaussian mechanism | |
| (Mironov, Talwar, Zhang 2019, integer orders) with the Balle et al. 2020 | |
| RDP -> (eps, delta) conversion. Same recipe Opacus uses. | |
| """ | |
| import math | |
| import numpy as np | |
| def clip_sum(per_example_grads, clip, weights=None): | |
| """Clip every row to L2 norm <= clip, optionally scale each row by a public weight in [0, 1] | |
| (applied AFTER clipping so it cannot be normalised away and sensitivity stays <= clip), then sum.""" | |
| norms = np.linalg.norm(per_example_grads, axis=1, keepdims=True) | |
| scale = np.minimum(1.0, clip / (norms + 1e-12)) | |
| g = per_example_grads * scale | |
| if weights is not None: | |
| g = g * weights[:, None] | |
| return g.sum(axis=0) | |
| def _rdp_sampled_gaussian(q, sigma, alpha): | |
| """RDP of order `alpha` (integer >= 2) for ONE step of the subsampled Gaussian.""" | |
| if q <= 0: | |
| return 0.0 | |
| if sigma <= 0: | |
| return float("inf") | |
| if q >= 1.0: | |
| return alpha / (2.0 * sigma ** 2) | |
| terms = [] | |
| for k in range(alpha + 1): | |
| log_coef = math.lgamma(alpha + 1) - math.lgamma(k + 1) - math.lgamma(alpha - k + 1) | |
| terms.append(log_coef + k * math.log(q) + (alpha - k) * math.log1p(-q) | |
| + (k * k - k) / (2.0 * sigma ** 2)) | |
| m = max(terms) | |
| log_sum = m + math.log(sum(math.exp(t - m) for t in terms)) | |
| return log_sum / (alpha - 1) | |
| ORDERS = list(range(2, 65)) + [80, 96, 128, 192, 256] | |
| def epsilon(q, sigma, steps, delta=1e-5): | |
| """(eps, delta)-DP after `steps` compositions of the subsampled Gaussian mechanism.""" | |
| if sigma <= 0: | |
| return float("inf") | |
| best = float("inf") | |
| for a in ORDERS: | |
| rdp = steps * _rdp_sampled_gaussian(q, sigma, a) | |
| eps = rdp + math.log((a - 1) / a) - (math.log(delta) + math.log(a)) / (a - 1) | |
| best = min(best, eps) | |
| return max(best, 0.0) | |