Federated learning: distributed privacy and robustness
Train without centralizing data and discover why this alone does not ensure privacy. Implement FedAvg and corrections for heterogeneous data, use gradient inversion to show that updates can leak data, and build two complementary defenses: cryptographic secure aggregation and user-level DP. Examine malicious clients, robust aggregators, and the tension between hiding updates and inspecting them.
After this lesson you can
- Implement FedAvg, FedProx, and SCAFFOLD and explain client drift with non-i.i.d. data.
- Reconstruct training data from shared gradients.
- Implement secure aggregation with pairwise masks and dropout tolerance.
- Apply user-level DP by clipping client updates and calculate the required noise.
- Compare robust aggregators against Byzantine clients and model-replacement backdoors.
Before you start
Train where the data are
Federated learning coordinates a model across clients without sending all their raw data to a server. In FedAvg, each participating client performs local training steps and sends an update; the server combines results, often weighting by the number of examples. McMahan and collaborators study this strategy. Keeping data decentralized does not by itself ensure privacy: updates and metadata can reveal information.
Cross-device learning involves many participants, intermittent connectivity, and few examples per client. Cross-silo learning typically involves fewer institutions, more data per participant, and greater availability. Both require agreement on participation, logging, and dropout handling. Quantizing or compressing updates can reduce communication but changes optimization error, so it must be integrated into the aggregation protocol and privacy analysis.
Client heterogeneity includes differences in data distributions, dataset sizes, availability, and computing capacity. Several local steps can shift each model toward its own objective before averaging. The following example uses two quadratics and calculates the fixed point exactly; it does not describe every possible behavior of FedAvg.
FedProx adds a proximal term to the local objective to limit deviations; SCAFFOLD uses control variates to correct drift. Their effectiveness depends on the protocol, client selection, and problem. A global average can hide poor results for minority clients: evaluate the distribution of per-client utility as well as the average.
In the round , if the client has examples and returns , FedAvg calculates among the participants. With equal sizes it is a simple mean; with different sizes, each client does not necessarily receive the same weight. FedProx replaces the local objective by : the penalty is zero at the start and grows the farther it strays from the received model. It does not force models to coincide nor automatically eliminate participation bias.
In SCAFFOLD, the client corrects each local gradient with , using its control variate and the global control variate . In the lab’s variant with steps and learning rate , the client finishes by calculating ; with full participation and uniform weighting, the server updates to the mean of the new control variates. The figure compares actual runs on a single synthetic problem: the final difference between FedAvg and the noisy variant is approximately 0.33 percentage points, insufficient to establish a general privacy cost.
In this construction, client minimizes , where controls heterogeneity. The centers are and the curvatures are . The global optimum weights each center by its curvature in each coordinate. With multiple local steps, FedAvg can converge to another point; SCAFFOLD corrects this drift in the example because its control variates track gradient differences. The observed correction is not a guarantee for arbitrary clients or numbers of rounds.
In the execution of the figure, the final average accuracies were 0.8038, 0.8040, 0.8033 and 0.8005 respectively; individual clients differ a lot. The option with noise uses clipping 0.2 and noise standard deviation 0.24 in the sum of the four updates, before dividing by four. It uses a public seed and is not a privacy system for real data. With 50 rounds of full participation, the standard RDP bound of integer orders 2 to 64 and δ=10⁻⁵ is approximately 46.2: the number is large and should not be confused with strong protection.
The sum does not reveal the same as each update
Gradient inversion is a documented risk: an update may contain information about local data. The risk depends on the model, batch, access, and observer’s knowledge; failure to reconstruct an example in one test does not prove the absence of leakage.
In the run shown, using one image, one local step, and no noise, MSE fell from 0.0765 to less than 0.00001 in 150 iterations. For four images, final mean MSE was approximately 0.0161; with one image and noise of standard deviation 0.01, it was 0.2275. The two-step case did not worsen in this run. These results depend on a simple CNN, one seed, and known labels and weights; they neither imply that the same noise protects other models nor establish DP. The images are public rather than private personal data.
Secure aggregation aims to let the server learn a sum without seeing individual updates. In an ideal pairwise masking scheme, one client adds a mask and the other subtracts the same mask; they cancel in the sum. The following example demonstrates this identity in modular arithmetic. It does not implement a cryptographic protocol, key management, or dropout tolerance. With independent, uniform, secret masks, an unknown mask can hide a value in its marginal distribution; joint views are correlated because the sum is preserved. Seeds and generators require computational security assumptions and do not automatically provide perfect statistical uniformity.
User-level DP clips each user’s entire update and adds noise to the aggregate. The privacy unit is a user, who may contribute multiple records. The guarantee depends on selection, clipping, noise, and accounting; secure aggregation and DP address different threats and can complement one another. McMahan and collaborators study user-level privacy in language models.
Under add/remove-user adjacency, the sum of clipped updates has sensitivity at most , provided the other users’ contributions do not change. Dividing the noisy sum by a fixed public denominator does not increase privacy loss; a participant-dependent denominator requires additional analysis. Noise can be added centrally or distributed among clients, but distributed noise requires a protocol that preserves enough noise if some clients drop out or are malicious. Any value of must specify the sampling parameters, number of rounds, and protected unit.
Robust aggregation seeks to limit unusual or malicious updates using rules such as the median or trimmed mean. Honest heterogeneity can appear unusual, and robust rules have assumptions about the number and distribution of clients. If secure aggregation hides each update from the server, the server cannot directly apply a rule that needs to inspect those updates; compatible designs and an explicit threat model are required.
Krum selects an update whose summed distances to a specified number of neighbors are small; its size conditions and assumptions about honest updates matter. A client that manipulates its update can also target a subset of inputs, so high overall accuracy does not rule out a backdoor. Bagdasaryan and collaborators study this risk; here the defensive comparison uses only synthetic vectors. With secure aggregation, applying a robust rule may require multiparty computation, verifiable proofs, or changes to trust assumptions; each option has costs and its own assumptions.
The Flower documentation describes federated strategies, simulation, differential privacy, and secure aggregation protocols. A framework helps coordinate clients, but selecting a strategy does not verify its assumptions or prove that a combined implementation satisfies the threat model: review the specific configuration, client identities, and disaggregated metrics.
Laboratory: two clients and ideal masks
50 rounds of FedAvg are calculated over the same quadratics from the figure and the modular cancellation of three toy masks is checked. The numbers are synthetic; the code does not implement cryptography nor fail-safe recovery.
import numpy as np
eta = .2
for local_steps in (1,2,5,10):
w = 0.
for _ in range(50):
w1, w2 = w, w
for _ in range(local_steps):
w1 -= eta*(w1+1)
w2 -= eta*4*(w2-1)
w = (w1+w2)/2
print('pasos',local_steps,'valor tras 50 rondas',round(w,6))
q = 101
updates = np.array([3,8,15,20])
masked = updates.copy()
for i in range(4):
for j in range(i+1,4):
mask = (17*i+11*j+5) % q # determinista: solo ilustra cancelación
masked[i] += mask; masked[j] -= mask
print('suma enmascarada', int(masked.sum()%q), 'suma original', int(updates.sum()%q))
assert masked.sum()%q == updates.sum()%qCompare FedAvg, FedProx, SCAFFOLD, and user noise
Each client receives 100 artificial training examples and 1000 test examples from a different distribution. All participate in 50 rounds, with five steps of full gradient descent. FedProx penalizes the distance to the global point; SCAFFOLD maintains client controls and their mean on the server. In the noisy variant, the full update of each user is clipped before adding central noise. The reproducible noise source is not secure and these numbers describe a single seed; they do not demonstrate that a method is universally superior.
import json,numpy as np
from scipy.special import expit
rng=np.random.default_rng(33);clients=[];valid=[]
truth=np.array([.9,-.7])
for i in range(4):
def generate(n):
x=rng.normal(size=(n,2))+np.array([i-1.5,(-1)**i*.7]);y=(rng.random(n)<expit(x@truth+(-1.5+i))).astype(float)
return np.column_stack([np.ones(n),x]),y
clients.append(generate(100));valid.append(generate(1000))
def grad(w,data):
x,y=data;return x.T@(expit(x@w)-y)/len(y)
def metrics(w):
vals=[float(np.mean(((x@w)>=0)==y)) for x,y in valid]
return vals,float(np.mean(vals))
def train(method,rounds=50,K=5,eta=.1,mu=.5,sigma=0.):
w=np.zeros(3);ci=np.zeros((4,3));control=np.zeros(3);trajectory=[];random=np.random.default_rng(330)
for t in range(rounds):
locals=[];new_ci=[]
for i,client in enumerate(clients):
local=w.copy()
for _ in range(K):
g=grad(local,client)
if method=='prox':g+=mu*(local-w)
if method=='scaffold':g+=control-ci[i]
local-=eta*g
locals.append(local)
if method=='scaffold':new_ci.append(ci[i]-control+(w-local)/(K*eta))
delta=np.asarray(locals)-w
if method=='dp':
norm=np.linalg.norm(delta,axis=1,keepdims=True);clipped=delta*np.minimum(1,.2/np.maximum(norm,1e-12))
update=(clipped.sum(0)+random.normal(0,sigma*.2,3))/4
else:update=delta.mean(0)
w=w+update
if method=='scaffold':ci=np.array(new_ci);control=ci.mean(0)
if t in (0,4,9,19,49):
vals,mean=metrics(w);trajectory.append(dict(round=t+1,mean=mean,per_client=vals,w=w.tolist()))
return trajectory
rows={name:train(name,sigma=1.2 if name=='dp' else 0.) for name in ('avg','prox','scaffold','dp')}
for name,trajectory in rows.items():print(name,trajectory[-1],flush=True)
orders=np.arange(2,65);bound=np.min(50*orders/(2*1.2**2)+np.log(1e5)/(orders-1))
print('cota RDP estándar sin submuestreo, delta=1e-5',bound)Recover masks after a dropout and compare aggregators
The following cell implements threshold-two Shamir sharing in a small prime field to reconstruct only pairwise masks involving the client that drops out. An idealized central dealer knows the masks, and the generator is reproducible: this checks arithmetic, not a secure cryptographic implementation. The median, trimmed mean, and Krum are compared on six artificial honest vectors and one manipulated vector. Krum uses f=1 and four neighbors, satisfying n≥2f+3 in this example; this alone does not guarantee that it always selects an honest client.
import numpy as np
rng=np.random.default_rng(33);p=7919;updates=np.array([3,8,15,20],dtype=int);masks={};shares={}
for i in range(4):
for j in range(i+1,4):
secret=int(rng.integers(p));slope=int(rng.integers(p));masks[i,j]=secret
shares[i,j]=[(x,(secret+slope*x)%p) for x in range(1,5)]
masked=updates.copy()
for (i,j),s in masks.items():masked[i]+=s;masked[j]-=s
print('todos',int(masked.sum()%p),'real',int(updates.sum()%p))
# El cliente 0 no envía; los clientes 1 y 2 entregan sus dos comparticiones.
recovered=[]
for j in (1,2,3):
(x1,y1),(x2,y2)=shares[0,j][1:3]
recovered.append(((y1*x2-y2*x1)*pow(x2-x1,-1,p))%p)
result=(masked[1:].sum()+sum(recovered))%p
print('con abandono: suma corregida',int(result),'suma real',int(updates[1:].sum()%p));assert result==updates[1:].sum()%p
honest=np.array([[-.6,.2],[-.3,-.5],[0,.4],[.25,-.2],[.5,.1],[.7,-.4]])
vectors=np.vstack([honest,[3.,3.]])
median=np.median(vectors,axis=0);trimmed=np.sort(vectors,axis=0)[1:-1].mean(axis=0)
def krum(x,f):
if len(x)<2*f+3:raise ValueError('clientes insuficientes')
distances=((x[:,None,:]-x[None,:,:])**2).sum(-1);np.fill_diagonal(distances,np.inf)
scores=np.sort(distances,axis=1)[:,:len(x)-f-2].sum(axis=1)
return x[np.argmin(scores)]
print('media',vectors.mean(0),'mediana',median,'recortada',trimmed,'krum',krum(vectors,1))Model replacement in a controlled simulation
To study a backdoor in a controlled manner, seven clients train a logistic regression on artificial data with two coordinates. A third feature, always zero in honest data, represents an artificial pattern. After 30 honest rounds, the controlled client trains a model that predicts class 1 when that feature is one and amplifies its current update by seven. We compare one honest round and five ways of adding the manipulated round; no private data, network, or external model is involved. We measure clean accuracy and the fraction of class 0 examples that become class 1 when activating the pattern. Isolated norm clipping is not DP.
With seed 331, mean aggregation under model replacement retains clean accuracy of 0.8540, compared to 0.8992 in the honest round, while the response to the pattern rises from 0.1074 to 0.9700. The median, coordinate-wise trimming, Krum, and norm clipping keep that response close to 0.11 in this run. The amplified vector has norm 25.99, while the six honest vectors have norms between 0.038 and 0.062, a favorable condition for the defenses. These are results from one simulation, not a guarantee against adaptive strategies or real heterogeneity. Bagdasaryan and collaborators analyze model replacement in federated learning.
import numpy as np
from scipy.special import expit
rng=np.random.default_rng(331)
def sample(n):
x=rng.normal(size=(n,2));y=(x[:,0]-.8*x[:,1]+rng.normal(0,.45,n)>0).astype(float)
return np.column_stack([np.ones(n),x,np.zeros(n)]),y
clients=[sample(200) for _ in range(7)];test,labels=sample(4000)
def grad(w,data):
x,y=data;return x.T@(expit(x@w)-y)/len(y)
def local(w,data,steps,lr):
x=w.copy()
for _ in range(steps):x-=lr*grad(x,data)
return x
def honest_deltas(w):return np.array([local(w,d,5,.3)-w for d in clients])
w=np.zeros(4)
for _ in range(30):w+=honest_deltas(w).mean(0)
x,y=clients[6];trigger=x.copy();trigger[:,-1]=1
target=local(w,(np.vstack([x,trigger]),np.concatenate([y,np.ones(len(y))])),100,.5)
honest=honest_deltas(w);attacker=7*(target-w);updates=honest.copy();updates[6]=attacker
def krum(a,f=1):
d=((a[:,None,:]-a[None,:,:])**2).sum(-1);np.fill_diagonal(d,np.inf)
return a[np.argmin(np.sort(d,axis=1)[:,:len(a)-f-2].sum(1))]
norm=np.linalg.norm(updates,axis=1,keepdims=True);clipped=updates*np.minimum(1,.2/np.maximum(norm,1e-12))
methods={'honesto':honest.mean(0),'media':updates.mean(0),'mediana':np.median(updates,axis=0),'recorte':np.sort(updates,axis=0)[1:-1].mean(0),'krum':krum(updates),'norma_0.2':clipped.mean(0)}
test_trigger=test.copy();test_trigger[:,-1]=1;negative=labels==0
print('semilla 331; 7 clientes, 200 ejemplos, prueba 4000; 30 rondas honestas, 5 pasos locales')
print('norma atacante ampliada',round(float(np.linalg.norm(attacker)),4),'normas honestas',np.round(np.linalg.norm(honest[:6],axis=1),4).tolist())
for name,delta in methods.items():
model=w+delta;clean=np.mean((test@model>=0)==labels);triggered=np.mean((test_trigger[negative]@model)>=0)
print(name,'exactitud limpia',round(float(clean),4),'respuesta 1 con patrón entre clase 0',round(float(triggered),4))Ephemeral keys and dropout recovery
This single-process local simulation combines X25519 exchange and HKDF derivation with ChaCha20-Poly1305 to encrypt and authenticate Shamir shares. Four clients use synthetic updates; if client 0 drops out before sending, two survivors reconstruct that client’s ephemeral key and correct its masks. The cell checks the sum and rejects altered associated data. Install cryptography in local Python. There is no network: public keys are assumed authentic, the server reports dropouts honestly, and one process sees every secret. This does not protect against a server giving inconsistent accounts to different clients. It neither implements nor proves the security of the dropout-tolerant aggregation protocol by Bonawitz and collaborators. Real applications require complete security design and review of authentication, nonces, and participant agreement.
import secrets
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
from cryptography.hazmat.primitives import hashes,serialization
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
from cryptography.exceptions import InvalidTag
P=2**521-1;Q=2**61-1;clients=4;drop=0;updates=[3,8,15,20]
keys=[X25519PrivateKey.generate() for _ in range(clients)];pub=[k.public_key() for k in keys]
def derive(private,public,purpose):
return HKDF(algorithm=hashes.SHA256(),length=32,salt=None,info=purpose).derive(private.exchange(public))
def pairmask(private,public,i,j):
return int.from_bytes(derive(private,public,f'mask-{min(i,j)}-{max(i,j)}'.encode()),'big')%Q
masks={}
for i in range(clients):
for j in range(i+1,clients):
a=pairmask(keys[i],pub[j],i,j);b=pairmask(keys[j],pub[i],i,j);assert a==b;masks[i,j]=a
masked=updates.copy()
for (i,j),mask in masks.items():masked[i]=(masked[i]+mask)%Q;masked[j]=(masked[j]-mask)%Q
print('todos: suma enmascarada',sum(masked)%Q,'suma real',sum(updates)%Q)
# El cliente 0 reparte su clave efímera con Shamir 2-de-3, cifrada para cada titular.
raw=keys[0].private_bytes(serialization.Encoding.Raw,serialization.PrivateFormat.Raw,serialization.NoEncryption())
secret=int.from_bytes(raw,'little');slope=secrets.randbelow(P);received=[]
for holder in (1,2,3):
x=holder;share=(secret+slope*x)%P;purpose=f'share-0-{holder}'.encode();nonce=secrets.token_bytes(12)
key_out=derive(keys[0],pub[holder],purpose);key_in=derive(keys[holder],pub[0],purpose)
ciphertext=ChaCha20Poly1305(key_out).encrypt(nonce,share.to_bytes(66,'big'),purpose)
if holder==1:
try:ChaCha20Poly1305(key_in).decrypt(nonce,ciphertext,purpose+b'-alterado');raise AssertionError('aceptó autenticación incorrecta')
except InvalidTag:pass
decoded=int.from_bytes(ChaCha20Poly1305(key_in).decrypt(nonce,ciphertext,purpose),'big');received.append((x,decoded))
(x1,y1),(x2,y2)=received[:2];recovered=((y1*x2-y2*x1)*pow(x2-x1,-1,P))%P
assert recovered==secret
dropped=X25519PrivateKey.from_private_bytes(recovered.to_bytes(32,'little'))
correction=sum(pairmask(dropped,pub[j],0,j) for j in (1,2,3))%Q
summed=(sum(masked[1:])+correction)%Q
print('cliente 0 ausente: suma corregida',summed,'suma real',sum(updates[1:])%Q)
assert summed==sum(updates[1:])%Q
print('comparticiones cifradas y autenticación alterada rechazada; dos de tres reconstruyen solo la clave del cliente ausente')npm run lab and open the connection link.Controlled reconstruction with public CIFAR-10
This local lab uses four public CIFAR-10 test images, a CNN built from scratch, and known initial parameters and labels. It calculates the update after one or two local steps, clips it to maximum norm 1, and adds Gaussian noise in one condition. It fits candidate images to the observed update and records MSE at four iterations. For batch size 4, the four labels are known in order and MSE averages the four examples; this is not a comparison with an attacker who has less knowledge. Only one seed and public examples are used; no third-party updates are accessed.
Install PyTorch and torchvision. If the dataset is not in CIFAR_DIR or ./cifar_data, torchvision attempts to download it. The pseudorandom noise here illustrates an update perturbation; without a complete protocol, accounting, and a secure generator, this does not constitute a DP guarantee.
import os,json,itertools,torch,numpy as np
from torch import nn
from torch.func import functional_call
from torchvision.datasets import CIFAR10
from torchvision.transforms import ToTensor
torch.set_num_threads(1);torch.manual_seed(33);device='cuda' if torch.cuda.is_available() else 'cpu'
root=os.environ.get('CIFAR_DIR','./cifar_data');download=not os.path.isdir(os.path.join(root,'cifar-10-batches-py'))
ds=CIFAR10(root,train=False,download=download,transform=ToTensor())
images=torch.stack([ds[i][0] for i in range(4)]).to(device);images=nn.functional.avg_pool2d(images,2)
labels=torch.tensor([ds[i][1] for i in range(4)],device=device)
model=nn.Sequential(nn.Conv2d(3,8,3,padding=1),nn.Sigmoid(),nn.Flatten(),nn.Linear(8*16*16,10)).to(device)
base={k:v.detach().clone().requires_grad_(True) for k,v in model.named_parameters()};local_lr=.02;clip=1.
def local_delta(x,y,steps,track):
p={k:v for k,v in base.items()}
for _ in range(steps):
loss=nn.functional.cross_entropy(functional_call(model,p,(x,)),y)
grad=torch.autograd.grad(loss,tuple(p.values()),create_graph=track)
p={k:v-local_lr*g for (k,v),g in zip(p.items(),grad)}
if not track:p={k:v.detach().requires_grad_(True) for k,v in p.items()}
return [base[k]-p[k] for k in base]
def encode_image(x):return (x.clamp(0,1).mul(255).round().byte().permute(1,2,0).flatten().cpu().tolist())
cases=[]
for B,K,sigma in [(1,1,0.),(4,1,0.),(1,2,0.),(1,1,.01)]:
torch.manual_seed(330+B+K);target=images[:B];y=labels[:B]
raw=local_delta(target,y,K,False);norm=torch.sqrt(sum(v.detach().pow(2).sum() for v in raw));scale=min(1.,clip/(float(norm)+1e-12))
observed=[(v*scale+torch.randn_like(v)*sigma*clip).detach() for v in raw]
guess=torch.randn_like(target,requires_grad=True);opt=torch.optim.Adam([guess],lr=.12)
moments=[]
for step in range(151):
candidate=guess.sigmoid()
if step in (0,25,75,150):
with torch.no_grad():
# El orden conocido de etiquetas fija la correspondencia de cada candidato.
mse=float((candidate-target).pow(2).mean());moments.append(dict(step=step,mse=mse,image=encode_image(candidate[0])))
if step==150:break
estimated=local_delta(candidate,y,K,True);enorm=torch.sqrt(sum(v.pow(2).sum() for v in estimated));escale=(clip/enorm.clamp_min(1e-12)).clamp(max=1)
cost=sum((a*escale-b).pow(2).sum() for a,b in zip(estimated,observed))
opt.zero_grad();cost.backward();opt.step()
cases.append(dict(batch=B,local_steps=K,noise=sigma,norm=float(norm),snapshots=moments))
print('lote',B,'pasos locales',K,'ruido',sigma,'norma actualización',round(float(norm),5),'mse',[(x['step'],round(x['mse'],5)) for x in moments],flush=True)
result={'seed':33,'source':'CIFAR-10 test indices 0-3, reducidas por promedio a 16x16','device':device,'labels':labels.tolist(),'originals':[encode_image(x) for x in images],'cases':cases}
import matplotlib.pyplot as plt
fig,axes=plt.subplots(2,4,figsize=(9,4))
for j,case in enumerate(cases):
axes[0,j].imshow(np.asarray(result['originals'][0]).reshape(16,16,3).astype(np.uint8))
axes[1,j].imshow(np.asarray(case['snapshots'][-1]['image']).reshape(16,16,3).astype(np.uint8))
axes[0,j].set_title(f"B={case['batch']}, K={case['local_steps']}, σ={case['noise']}")
for ax in axes[:,j]:ax.axis('off')
plt.tight_layout();plt.show()npm run lab and open the connection link.Compare inversion and DP-FedAvg under the same protocol
All three conditions now use the same initial CNN, four clients, and the same public CIFAR-10 data. The first client has one image and each of the other three has 64; each round performs one local step, aggregates with uniform weights, and divides by the fixed public denominator 4. Ten rounds are compared without clipping, with user-update norm clipping at , and with the same clipping plus central Gaussian noise of standard deviation in each coordinate of the sum. Accuracy is measured on 512 test images. The single-example client and full participation are assumptions chosen for this test, not a representative device population.
The reconstruction observes the first sum and assumes that the observer knows the architecture, weights, label, and contributions of the other three clients, all public. By subtracting those contributions, it obtains the first user’s update plus central noise; it optimizes a candidate image without knowing the original image. In this seed, the final MSE is 0.00000135 without clipping, 0.00000165 with only clipping, and 0.2854 with clipping and noise: clipping alone did not prevent reconstruction in this test. The test accuracies after ten rounds are 0.0801, 0.1094, and 0.1230, respectively. The noise did not produce a drop in accuracy: these are low values from a single run, not a statistical comparison nor a general utility conclusion.
Under add/remove-user adjacency, with absence encoded as a zero contribution, four slots, and a fixed denominator, the standard integer-order RDP bound over orders 2 to 64 for ten rounds without subsampling and is 16.173. This is a large bound; the generator seed is public, the server knows the contributions, and the code is not a secure DP implementation. An operational guarantee must also protect the noise source and protocol. This experiment measures the comparison and does not certify protection of real data.
import os,torch,numpy as np
from torch import nn
from torch.func import functional_call
from torchvision.datasets import CIFAR10
from torchvision.transforms import ToTensor
torch.set_num_threads(1);torch.manual_seed(3301);device='cuda' if torch.cuda.is_available() else 'cpu'
root=os.environ.get('CIFAR_DIR','./cifar_data');download=not os.path.isdir(os.path.join(root,'cifar-10-batches-py'))
train=CIFAR10(root,train=True,download=download,transform=ToTensor());test=CIFAR10(root,train=False,download=download,transform=ToTensor())
def images(ds,ids):
x=torch.stack([ds[i][0] for i in ids]).to(device);y=torch.tensor([ds[i][1] for i in ids],device=device)
return nn.functional.avg_pool2d(x,2),y
clients=[images(train,[0])]+[images(train,range(1+64*i,1+64*(i+1))) for i in range(3)];xt,yt=images(test,range(512))
model=nn.Sequential(nn.Conv2d(3,8,3,padding=1),nn.Sigmoid(),nn.Flatten(),nn.Linear(8*16*16,10)).to(device)
initial={k:v.detach().clone() for k,v in model.named_parameters()};lr=.02;C=.2;sigma=1.2;rounds=10
def delta(params,x,y,track):
p={k:v.detach().clone().requires_grad_(True) for k,v in params.items()};loss=nn.functional.cross_entropy(functional_call(model,p,(x,)),y)
gradients=torch.autograd.grad(loss,tuple(p.values()),create_graph=track)
return [(-lr*g if track else (-lr*g).detach()) for g in gradients]
def clip_update(update,limit):
norm=torch.sqrt(sum(v.pow(2).sum() for v in update));factor=(limit/norm.clamp_min(1e-12)).clamp(max=1) if limit is not None else torch.ones_like(norm)
return [v*factor for v in update],norm
def reconstruct(params,observed,limit):
torch.manual_seed(3302);target=clients[0][0];guess=torch.randn_like(target,requires_grad=True);optim=torch.optim.Adam([guess],lr=.12);history=[]
for step in range(151):
candidate=guess.sigmoid()
if step in (0,25,75,150):history.append((step,float((candidate-target).pow(2).mean().detach())))
if step==150:break
predicted,_=clip_update(delta(params,candidate,clients[0][1],True),limit)
loss=sum((a-b).pow(2).sum() for a,b in zip(predicted,observed));optim.zero_grad();loss.backward();optim.step()
return history,candidate.detach().cpu()
results=[];reconstructions=[]
for mode in ('sin_recorte','recorte','recorte_ruido'):
params={k:v.clone() for k,v in initial.items()};rng=torch.Generator(device=device).manual_seed(3303);limit=None if mode=='sin_recorte' else C;first=None;first_norm=None
for t in range(rounds):
contributions=[];norms=[]
for x,y in clients:
update,norm=clip_update(delta(params,x,y,False),limit);contributions.append(update);norms.append(float(norm))
noise=[torch.randn(v.shape,generator=rng,device=device)*sigma*C if mode=='recorte_ruido' else torch.zeros_like(v) for v in contributions[0]]
summed=[sum(parts)+noise_i for parts,noise_i in zip(zip(*contributions),noise)]
if t==0:
# Observador fuerte conoce las otras tres contribuciones; solo quedan cliente 0 y ruido central.
first=[(total-sum(other)).detach() for total,other in zip(summed,zip(*contributions[1:]))];first_norm=norms[0]
params={k:(p+u/4).detach() for (k,p),u in zip(params.items(),summed)}
if t==0:initial_for_attack={k:v.clone() for k,v in initial.items()}
with torch.no_grad():accuracy=float((functional_call(model,params,(xt,)).argmax(-1)==yt).float().mean())
history,reconstruction=reconstruct(initial_for_attack,first,limit);reconstructions.append(reconstruction)
result={'condicion':mode,'norma_original_usuario0':first_norm,'accuracy_test':accuracy,'mse':history};results.append(result);print(result,flush=True)
orders=np.arange(2,65);bound=float(np.min(rounds*orders/(2*sigma**2)+np.log(1e5)/(orders-1)))
print('RDP cota entera, q=1, delta=1e-5',bound,'datos públicos, generador no seguro',flush=True)
import matplotlib.pyplot as plt
fig,axes=plt.subplots(1,4,figsize=(10,4))
axes[0].imshow(clients[0][0][0].detach().cpu().permute(1,2,0));axes[0].set_title('Original público')
for ax,im,row in zip(axes[1:],reconstructions,results):
ax.imshow(im[0].permute(1,2,0));ax.set_title(f"{row['condicion']}\nMSE {row['mse'][-1][1]:.4g}\naccuracy {row['accuracy_test']:.3f}")
for ax in axes:ax.axis('off')
plt.tight_layout(pad=1.5)
plt.show()npm run lab and open the connection link.Exercises
Step 1 of 3. What happens when all the messages are summed?
def coordinate_median(updates):
pass
def trimmed_mean(updates, trim):
pass
def krum(updates, f):
pass