CHAPTER 6

Federated Edge Learning

Beyond Static Models

Traditional edge AI deploys static models—trained once in the cloud, frozen, then distributed. These models never improve from real-world usage. Federated learning enables collaborative model training across thousands of edge devices while keeping data local, combining the benefits of centralized learning (model improvement from diverse data) with edge AI (privacy preservation, offline capability).

Federated Learning Fundamentals

The Core Concept

Instead of collecting data centrally for training, federated learning brings training to the data. The process:

  1. Distribution: Server sends current global model to participating devices
  2. Local Training: Each device trains on its private data for a few epochs
  3. Update Sharing: Devices send only model updates (gradients or weights) to server, not raw data
  4. Aggregation: Server combines updates from many devices using averaging or weighted schemes
  5. Broadcasting: Improved global model is sent back to devices
  6. Iteration: Process repeats until convergence
// Federated learning workflow (pseudo-code)
// Server side
global_model = initialize_model()

for round in range(num_rounds):
    # Select participating devices
    selected_devices = sample(all_devices, participation_rate=0.1)

    # Send global model to devices
    for device in selected_devices:
        send_model(device, global_model)

    # Wait for local updates
    updates = []
    for device in selected_devices:
        local_update = receive_update(device)
        updates.append(local_update)

    # Aggregate updates (FedAvg algorithm)
    global_model = federated_averaging(global_model, updates)

// Device side
def local_training(global_model, local_data, epochs=5):
    model = download_model(global_model)

    for epoch in range(epochs):
        for batch in local_data:
            loss = model.forward(batch)
            gradients = model.backward(loss)
            model.update_weights(gradients)

    local_update = compute_update(global_model, model)
    send_update(server, local_update)
    return model

Privacy Preservation

Federated learning preserves privacy because:

Federated Averaging (FedAvg)

The Standard Algorithm

FedAvg, introduced by Google in 2016, is the foundational federated learning algorithm:

// FedAvg aggregation on server
def federated_averaging(global_weights, device_updates):
    """
    device_updates: List of (device_id, local_weights, num_samples)
    """
    total_samples = sum(num_samples for _, _, num_samples in device_updates)

    # Weighted average based on local dataset size
    aggregated_weights = {}
    for layer_name in global_weights.keys():
        weighted_sum = 0
        for device_id, local_weights, num_samples in device_updates:
            weight = num_samples / total_samples
            weighted_sum += weight * local_weights[layer_name]

        aggregated_weights[layer_name] = weighted_sum

    return aggregated_weights

Devices with more data have proportionally higher influence on the global model. This ensures the model reflects the true data distribution across all participants.

Convergence Challenges

Federated learning converges slower than centralized training due to:

Federated Learning on Edge Devices

On-Device Training Constraints

Training (even for a few epochs) is more demanding than inference:

Resource Inference Training Ratio
Memory Model size only Model + gradients + optimizer state 3-5x
Computation Forward pass Forward + backward pass 2-3x
Power Milliseconds Minutes 1000x total

Strategies to enable edge training:

TensorFlow Federated

Google's open-source framework for federated learning research and deployment:

// TensorFlow Federated example
import tensorflow_federated as tff

# Define model
def model_fn():
    return tff.learning.from_keras_model(
        keras_model=create_keras_model(),
        input_spec=input_spec,
        loss=tf.keras.losses.SparseCategoricalCrossentropy(),
        metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]
    )

# Federated averaging process
iterative_process = tff.learning.build_federated_averaging_process(
    model_fn,
    client_optimizer_fn=lambda: tf.keras.optimizers.SGD(0.02),
    server_optimizer_fn=lambda: tf.keras.optimizers.SGD(1.0)
)

# Initialize
state = iterative_process.initialize()

# Training round
for round_num in range(num_rounds):
    state, metrics = iterative_process.next(state, federated_train_data)
    print(f'Round {round_num}: loss={metrics["loss"]}, accuracy={metrics["accuracy"]}')

Flower: Scalable Federated Learning

Open-source framework supporting diverse platforms and frameworks:

# Flower client (runs on edge device)
import flwr as fl

class EdgeClient(fl.client.NumPyClient):
    def get_parameters(self):
        return get_model_weights()

    def fit(self, parameters, config):
        set_model_weights(parameters)
        train_model(local_data, epochs=5)
        return get_model_weights(), len(local_data), {}

    def evaluate(self, parameters, config):
        set_model_weights(parameters)
        loss, accuracy = evaluate_model(test_data)
        return loss, len(test_data), {"accuracy": accuracy}

# Start client
fl.client.start_numpy_client(server_address="server:8080", client=EdgeClient())

Privacy-Enhancing Technologies

Differential Privacy

Add calibrated noise to model updates to prevent reconstruction of individual data points:

// Differential privacy for federated learning
def add_differential_privacy(gradients, epsilon=1.0, delta=1e-5):
    """
    epsilon: Privacy budget (lower = more privacy, less accuracy)
    delta: Probability of privacy breach
    """
    sensitivity = compute_l2_sensitivity(gradients)

    # Gaussian mechanism for (ε, δ)-differential privacy
    sigma = (sensitivity * sqrt(2 * log(1.25 / delta))) / epsilon

    noisy_gradients = {}
    for layer_name, gradient in gradients.items():
        noise = np.random.normal(0, sigma, gradient.shape)
        noisy_gradients[layer_name] = gradient + noise

    return noisy_gradients

Trade-off: Stronger privacy (lower epsilon) reduces model accuracy. Typical values: epsilon=1-10.

Secure Aggregation

Cryptographic protocol ensuring the server can only see aggregated updates, never individual device updates:

  1. Devices generate random pairwise masks
  2. Each device encrypts its update with these masks
  3. Server receives masked updates from all devices
  4. Masks cancel out when aggregating, revealing only the sum
  5. Individual updates remain hidden from server

This prevents the server from singling out any individual contribution, even though it computes the global aggregate.

Real-World Applications

Gboard (Google Keyboard)

Google's mobile keyboard uses federated learning to improve next-word prediction:

Apple Siri and QuickType

Apple uses federated learning for:

Updates are uploaded anonymously when devices are locked and charging. Apple's differential privacy adds noise to ensure individual contributions can't be identified.

Healthcare: Disease Prediction

Hospitals collaborate on predictive models without sharing patient data:

Finance: Fraud Detection

Banks improve fraud detection across institutions:

Challenges and Solutions

Communication Efficiency

Problem: Transmitting full model updates (megabytes) for every round consumes bandwidth and battery.

Solutions:

// Gradient compression: Top-K sparsification
def compress_gradients(gradients, k=0.01):
    """Keep only top k% of gradients by magnitude"""
    flat_grads = flatten(gradients)
    threshold = np.percentile(np.abs(flat_grads), 100 * (1 - k))

    compressed = {}
    for layer_name, grad in gradients.items():
        mask = np.abs(grad) >= threshold
        compressed[layer_name] = {
            'values': grad[mask],
            'indices': np.where(mask)
        }

    # Typical compression: 100x smaller updates
    return compressed

Non-IID Data

Problem: Device data distributions differ significantly (e.g., language preferences, photo content).

Solutions:

Device Heterogeneity

Problem: Devices have vastly different computational capabilities and availability.

Solutions:

弘益人間 Federated Learning Principle:

Federated learning embodies "benefit all humanity" by enabling collective intelligence while preserving individual privacy. Healthcare models improve from global patient data without violating confidentiality. Language models learn from billions of users without collecting their personal messages.

Future Directions

Federated Analytics

Beyond model training—compute statistics and insights across distributed data without centralization. Example: Aggregate usage statistics while preserving individual privacy.

Cross-Device and Cross-Silo

Federated Transfer Learning

Combine federated learning with transfer learning—pre-train foundation models on public data, fine-tune collaboratively on private edge data.

Blockchain-Based Federated Learning

Use blockchain for decentralized aggregation, removing need for trusted central server. Participants verify and record updates on distributed ledger.

Summary

Federated edge learning enables collaborative model training across distributed devices while preserving privacy. Key concepts:

  • Federated Averaging: Devices train locally, share only model updates, server aggregates into global model
  • Privacy Preservation: Raw data never leaves device, differential privacy adds mathematical guarantees
  • On-Device Training: Requires optimization for edge constraints (memory, computation, power)
  • Communication Efficiency: Gradient compression and sparsification reduce bandwidth

Real-world deployments include Google Gboard, Apple Siri/QuickType, healthcare collaborations, and financial fraud detection. Challenges include non-IID data, device heterogeneity, and communication costs—addressed through algorithm improvements (FedProx), personalization, and compression.

Federated learning represents the future of privacy-preserving AI, enabling collective intelligence without data centralization.

Review Questions

  1. Explain the federated learning workflow from model distribution to aggregation.
  2. How does federated learning preserve privacy compared to centralized training?
  3. What is FedAvg (Federated Averaging), and how does it work?
  4. Why is training on edge devices more resource-intensive than inference?
  5. What strategies enable training on resource-constrained edge devices?
  6. How does differential privacy enhance federated learning?
  7. What is secure aggregation, and what problem does it solve?
  8. Describe two real-world applications of federated learning.
  9. What is the non-IID data problem in federated learning, and how can it be addressed?
  10. How does gradient compression reduce communication costs in federated learning?