Federated Vision Learning: Non-IID Data and Privacy
Module: Computer Vision | Difficulty: Premium
Prerequisites
- !SGD and learning-rate schedules
- !Batch normalization versus group normalization
- !The definition of differential privacy
What You'll Learn
- 1Explain when federated learning is legally necessary rather than merely fashionable
- 2Diagnose label skew and quantity skew in a client population
- 3Replace batch normalization so federation does not break it
- 4Apply per-sample gradient clipping with an explicit privacy budget
- 5State precisely what secure aggregation does and does not protect
Ship weights, not pixels
Health systems, banks and device manufacturers all face the same pattern. Each holds a small private corpus that would improve a shared model, regulation forbids pooling the data, and the organization that would benefit most from centralization cannot have it. Federated learning reframes the training loop so that raw data never leaves the device: the server broadcasts a model, clients optimize locally on their own images, and only parameter updates return.
The vision case has a wrinkle that the tabular literature undersells. Image datasets are enormous relative to update sizes, so communication, not computation, usually becomes the bottleneck. A single round with a thousand clients transferring a ResNet-50 in full costs hundreds of megabytes on the server side alone, which is why most real deployments compress updates, subsample clients, or distill into a smaller student before returning anything.
Why averaging degrades under heterogeneity
Federated averaging assumes client updates point in roughly compatible directions. Real client data violates that constantly. Label skew appears when one hospital sees mostly late-stage disease and another mostly screening cases. Quantity skew is the familiar pattern where a handful of clients hold most of the data. Concept skew, the most damaging, occurs when identical-looking images carry different labels because of local annotation policy.
| Skew type | Description | Symptom during training | Mitigation |
|---|---|---|---|
| Label skew | Class proportions differ per client | Oscillating global accuracy | Per-class reweighting, more rounds |
| Quantity skew | Client dataset sizes vary widely | Large clients dominate updates | Size-independent weighting |
| Concept shift | Labeling policy differs | Persistent accuracy ceiling | Client clustering, relabeling |
| Feature shift | Camera or sensor differs | Early layers diverge | Local early layers, shared late layers |
The proximal correction is simple and effective: each client adds a penalty pulling its local weights toward the broadcast global weights, which stops a divergent client from running away in a few local steps.
Control-variate methods such as SCAFFOLD track per-client drift explicitly and converge faster under strong skew, at the cost of storing a second small vector per client. In practice the proximal term plus a modest local epoch count covers most of the gap.
Normalization layers are the silent killer
Batch normalization computes batch statistics, and a federation splits one logical batch across many small client batches. Each client therefore estimates a different mean and variance, and averaging those statistics produces a model that is well calibrated for nobody. The failure looks like a mysterious two to five point accuracy drop that worsens as clients become more heterogeneous.
Three fixes work. FedBN keeps batch-normalization parameters entirely local and never averages them, which is the simplest and usually the best. Group normalization or layer normalization removes the dependency on batch composition altogether and is the cleaner engineering choice for new projects. Batch renorm limits how far running statistics may drift from a reference, trading a little batch independence for stability.
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models import resnet18
def build_local_model(num_classes):
"""GroupNorm instead of BatchNorm, so local batches cannot skew stats."""
net = resnet18(norm_layer=lambda c: nn.GroupNorm(32, c), weights=None)
net.fc = nn.Linear(net.fc.in_features, num_classes)
return net
class FederatedClient:
def __init__(self, model, loader, lr=0.01, mu=0.0):
self.model = model
self.loader = loader
self.opt = torch.optim.SGD(model.parameters(), lr=lr, momentum=0.9)
self.mu = mu
def local_train(self, global_state, epochs=2):
self.model.load_state_dict(global_state)
self.model.train()
global_params = {n: p.clone()
for n, p in self.model.named_parameters()}
for _ in range(epochs):
for x, y in self.loader:
self.opt.zero_grad()
loss = F.cross_entropy(self.model(x), y)
if self.mu > 0:
prox = sum(
(p - global_params[n]).pow(2).sum()
for n, p in self.model.named_parameters())
loss = loss + (self.mu / 2.0) * prox
loss.backward()
self.opt.step()
return {n: p.detach() for n, p in self.model.named_parameters()}
def weighted_average(updates, sizes):
total = float(sum(sizes))
averaged = {}
for name in updates[0]:
averaged[name] = sum(
u[name] * (n / total) for u, n in zip(updates, sizes))
return averaged
model = build_local_model(num_classes=12)
client = FederatedClient(model, hospital_loader, lr=0.01, mu=0.01)
new_state = client.local_train(server_broadcast, epochs=2)
Differential privacy with an explicit budget
Updates leak. Gradient inversion attacks reconstruct recognizable images from a handful of gradients, and the attack is sharpest precisely when client batches are small, which is the federated default. Differential privacy gives a formal bound by clipping each sample's contribution and adding calibrated Gaussian noise before aggregation.
Here q is the sampling rate, T the number of rounds, and sigma the noise multiplier. The budget compounds with every round, so an aggressive schedule with many clients sampled per round burns privacy faster than a longer low-sampling run, even when total compute matches. Reporting epsilon without delta, sampling rate and round count is meaningless.
In vision, the practical tension is that clipping per-sample gradients of a convolutional network is expensive. Per-sample gradient techniques using ghost clipping or opacus-style hooks reduce the overhead to roughly twenty to forty percent, which is affordable. Expect a real accuracy cost: epsilon in the single digits typically costs several points of mAP on detection tasks, and that trade must be presented to stakeholders rather than discovered in production.
import torch
import torch.nn.functional as F
def clip_and_noise(state, max_norm, sigma, generator=None):
"""Clip the concatenated update, then add Gaussian noise once."""
flat = torch.cat([v.flatten() for v in state.values()])
norm = flat.norm()
clip = (max_norm / (norm + 1e-6)).clamp(max=1.0)
noise = torch.randn(flat.shape, generator=generator) * (max_norm * sigma)
protected = flat * clip + noise
out, offset = {}, 0
for k, v in state.items():
numel = v.numel()
out[k] = protected[offset:offset + numel].view_as(v)
offset += numel
return out
class ServerAggregator:
def __init__(self, clip=1.0, sigma=1.1, min_clients=10):
self.clip = clip
self.sigma = sigma
self.min_clients = min_clients
def aggregate(self, updates, sizes):
if len(updates) < self.min_clients:
raise RuntimeError("too few clients to aggregate safely")
protected = [clip_and_noise(u, self.clip, self.sigma)
for u in updates]
return weighted_average(protected, sizes)
aggregator = ServerAggregator(clip=1.0, sigma=1.1, min_clients=10)
server_state = aggregator.aggregate(client_updates, client_sizes)
Secure aggregation and its honest limits
Secure aggregation lets the server learn only the summed update, not any individual client's contribution. Clients exchange pairwise masks so that masks cancel in the sum, and clients that drop out mid-round are handled by secret sharing of their shares. This closes the most obvious attack, a curious or compromised server reading single-client updates, and it composes cleanly with differential privacy.
What it does not do is protect the final model. Once training completes, membership inference and model inversion remain possible against the published weights, and those require the differential privacy budget rather than the masking protocol. Secure aggregation also does nothing against a client that uploads deliberately poisoned data; robust aggregation rules that reject outlier updates are a separate concern, and they interact awkwardly with secure aggregation because outlier detection needs to see individual updates.
Participation, collapse, and what to monitor
Subsampling clients per round is both a privacy lever and a cost control, but aggressive subsampling with heavy skew means some clients go many rounds unseen and their classes drift out of the model. Track per-client last-participation time and rebalance the scheduler rather than sampling uniformly at random.
Server-side optimization helps as much as client-side tricks. Replacing plain averaging with a momentum update on the server, sometimes called FedAdam, smooths the round-to-round direction and typically buys back a point or two of final accuracy under heterogeneity, at no additional client cost. The learning rate on the server must be tuned separately from the client learning rate, and forgetting to do so is the most common reason momentum variants appear to fail.
Monitor four curves. Global accuracy on a held-out centralized validation set that never participates in training, which is the only unbiased signal available. Per-class recall on that set, to catch the rare classes that vanish first. Update norm percentiles across clients, which reveal a single outlier dragging the average. And round-to-round parameter drift, which should shrink as training converges; persistent large drift means the learning rate or proximal weight is wrong, not that the data is hard.
Common Mistakes
Averaging batch-normalization statistics across heterogeneous clients
Fix: Keep normalization local with FedBN, or switch the backbone to group normalization before federating
Quoting a privacy epsilon without delta, sampling rate and round count
Fix: Report the full accountant output and the exact participation schedule alongside every released model
Believing secure aggregation makes the final model private
Fix: Treat masking as server-side protection only, and apply differential privacy for anything released
Weighting client updates by dataset size under severe quantity skew
Fix: Cap per-client weights or sample a fixed number of examples per client per round
Best Practices
- Start with group normalization and a proximal term; those two changes fix most first-round disappointment
- Hold out a small centralized validation set that never trains, so you have one honest metric
- Clip updates and account for privacy from round one, because retrofitting noise later invalidates earlier releases
- Subsample clients with a fairness-aware scheduler and log per-client participation gaps
- Publish communication cost per round alongside accuracy, since that is what operators pay for
Interview Questions
Q1: Why does batch normalization break in federated learning?
Each client estimates batch statistics from its own small, non-IID batch, and averaging those statistics yields means and variances that fit no client. Group normalization or keeping normalization local removes the dependence on batch composition.
Q2: What does the proximal term in FedProx actually accomplish?
It bounds how far a client may move from the broadcast model during local steps, which limits drift under heterogeneous data and prevents a few aggressive clients from dominating the aggregated direction.
Q3: How does secure aggregation differ from differential privacy?
Secure aggregation hides individual updates from the server during a round using masking, and provides no formal guarantee about the released model. Differential privacy adds calibrated noise and bounds what can be inferred from the final weights.
Q4: Why is gradient inversion especially dangerous in federated vision?
Attacks reconstruct inputs from gradients, and reconstruction quality is best when client batches are small, which is typical for devices. Clipping plus noise, or simply larger local batches, sharply reduces the fidelity of recovered images.
Key Takeaways
- Federation is a legal and architectural requirement whenever data cannot be pooled
- Label, quantity and concept skew each degrade averaging in different, diagnosable ways
- Group normalization or FedBN removes the most common silent accuracy loss
- Per-sample clipping plus Gaussian noise gives a real, auditable privacy budget that compounds over rounds
- Secure aggregation protects updates in transit and at the server, not the published model
- Subsampling and fairness-aware scheduling decide whether rare clients keep contributing
- Monitor per-client norms and a held-out validation set, not only aggregate accuracy