{ "cells": [ { "cell_type": "markdown", "id": "4e841149", "metadata": {}, "source": [ "# Clipping and Gaussian noise (DP-style) on FedAvg\n", "\n", "# القصّ والضجيج الغاوسي على FedAvg\n", "\n", "**Educational simulation / محاكاة تعليمية.** Synthetic data only; no real patients or users. Federated learning does not by itself guarantee privacy.\n", "\n", "بيانات اصطناعية فقط؛ لا بيانات حقيقية. التعلم الاتحادي لا يضمن الخصوصية تلقائياً.\n", "\n", "Executed with Python 3.13.18, NumPy 2.5.3, scikit-learn 1.9.1. Outputs below were produced by actually running the cells." ] }, { "cell_type": "code", "id": "c1d7ffd3", "metadata": {}, "execution_count": 1, "outputs": [], "source": [ "\"\"\"Clipping + Gaussian noise on client updates (the DP-FedAvg aggregation step), NumPy.\n", "Educational: it shows the mechanism. It does NOT compute a privacy guarantee; use an accountant (e.g. Opacus or dp_accounting).\"\"\"\n", "\n", "import numpy as np\n", "\n", "def clip(update, C):\n", " norm = np.linalg.norm(update)\n", " return update * min(1.0, C / (norm + 1e-12))\n", "\n", "def dp_aggregate(updates, C=1.0, sigma=1.0, seed=0):\n", " rng = np.random.default_rng(seed)\n", " total = sum(clip(u, C) for u in updates)\n", " total = total + rng.normal(0, sigma * C, size=total.shape) # noise on the SUM\n", " return total / len(updates)" ] }, { "cell_type": "code", "id": "1e71ae7d", "metadata": {}, "execution_count": 2, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "sigma=0.0: mean abs error vs plain mean = 0.0000\n", "sigma=1.0: mean abs error vs plain mean = 0.0222\n", "sigma=4.0: mean abs error vs plain mean = 0.0889\n" ] } ], "source": [ "if __name__ == \"__main__\":\n", " rng = np.random.default_rng(1)\n", " ups = [rng.normal(0, 0.3, 50) + 0.1 for _ in range(100)] # update norms about 2.2\n", " plain = np.mean(ups, axis=0)\n", " for sigma in (0.0, 1.0, 4.0):\n", " agg = dp_aggregate(ups, C=3.0, sigma=sigma)\n", " print(f\"sigma={sigma}: mean abs error vs plain mean = {np.abs(agg - plain).mean():.4f}\")" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.13.18" } }, "nbformat": 4, "nbformat_minor": 5 }