{ "cells": [ { "cell_type": "markdown", "id": "906930b0", "metadata": {}, "source": [ "# Secure aggregation with pairwise masks (toy)\n", "\n", "# التجميع الآمن بأقنعة زوجية (مبسّط)\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": "ab20cdeb", "metadata": {}, "execution_count": 1, "outputs": [], "source": [ "\"\"\"Pairwise-mask secure aggregation, toy version (no key agreement, no dropout handling): masks cancel in the sum.\"\"\"\n", "\n", "import numpy as np" ] }, { "cell_type": "code", "id": "d83d404e", "metadata": {}, "execution_count": 2, "outputs": [], "source": [ "MOD = 2 ** 32" ] }, { "cell_type": "code", "id": "09c1088e", "metadata": {}, "execution_count": 3, "outputs": [], "source": [ "SCALE = 2 ** 16" ] }, { "cell_type": "code", "id": "414218be", "metadata": {}, "execution_count": 4, "outputs": [], "source": [ "def encode(x): return (np.round(x * SCALE).astype(np.int64)) % MOD\n", "\n", "def decode(v):\n", " v = v % MOD\n", " v = np.where(v >= MOD // 2, v - MOD, v)\n", " return v.astype(np.float64) / SCALE\n", "\n", "def mask_all(updates, seed=0):\n", " rng = np.random.default_rng(seed); n = len(updates); d = len(updates[0])\n", " enc = [encode(u) for u in updates]\n", " for i in range(n):\n", " for j in range(i + 1, n):\n", " m = rng.integers(0, MOD, size=d, dtype=np.int64) # shared secret mask for pair (i, j)\n", " enc[i] = (enc[i] + m) % MOD\n", " enc[j] = (enc[j] - m) % MOD\n", " return enc" ] }, { "cell_type": "code", "id": "cac1a6bd", "metadata": {}, "execution_count": 5, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "max |secure sum - plain sum| = 2.972588325800274e-05\n", "corr(masked update 0, real update 0) = -0.065\n" ] } ], "source": [ "if __name__ == \"__main__\":\n", " rng = np.random.default_rng(3)\n", " ups = [rng.normal(0, 1, 1000) for _ in range(5)]\n", " masked = mask_all(ups)\n", " plain = np.sum(ups, axis=0)\n", " agg = decode(sum(masked) % MOD)\n", " print(\"max |secure sum - plain sum| =\", float(np.abs(agg - plain).max()))\n", " print(\"corr(masked update 0, real update 0) =\", round(float(np.corrcoef(masked[0].astype(float), ups[0])[0, 1]), 3))" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.13.18" } }, "nbformat": 4, "nbformat_minor": 5 }