DEV Community

vmodal_ai
vmodal_ai

Posted on

Build a Federated Learning System on Android with Kotlin

Build a Federated Learning System on Android with Kotlin

Traditional machine learning often requires collecting training data on a central server. Federated learning takes a different approach: the model is sent to participating devices, training happens locally, and devices send model updates rather than their raw training data.

This tutorial explains how to design a federated learning prototype with Kotlin on Android.

Federated learning improves data locality, but it is not automatically private. Model updates can potentially leak information, so production systems need additional privacy and security mechanisms.

Architecture

                 Central Server
                      |
             Global Model v1
                /     |                    /      |                Device A Device B Device C
             |        |        |
         Local ML  Local ML  Local ML
             |        |        |
          Update A  Update B  Update C
               \      |      /
                \     |     /
                Aggregation
                      |
                Global Model v2
Enter fullscreen mode Exit fullscreen mode

The server coordinates training rounds.

Android Components

A mobile client can contain:

Model Manager
     |
Local Dataset
     |
Training Engine
     |
Update Serializer
     |
Secure API Client
Enter fullscreen mode Exit fullscreen mode

Kotlin is responsible for application lifecycle, networking, scheduling, storage, and orchestration.

The actual ML training engine can use a mobile-compatible ML runtime that supports your selected model and training workflow.

Model Distribution

The server provides a model version:

data class ModelInfo(
    val version: Int,
    val downloadUrl: String,
    val checksum: String
)
Enter fullscreen mode Exit fullscreen mode

The application downloads the model only when necessary.

Always verify the downloaded artifact before loading it.

Local Training

The client receives a global model and trains it against locally available data.

Conceptually:

suspend fun trainLocally(
    model: LocalModel,
    dataset: Dataset
): ModelUpdate {
    repeat(localEpochs) {
        model.train(dataset)
    }

    return model.createUpdate()
}
Enter fullscreen mode Exit fullscreen mode

The exact training API depends on the ML framework.

Sending Model Updates

Instead of uploading raw examples, the client sends an update.

data class ModelUpdate(
    val modelVersion: Int,
    val sampleCount: Int,
    val weights: List<Float>
)
Enter fullscreen mode Exit fullscreen mode

In a real implementation, avoid representing large tensors as Kotlin List<Float> because it creates unnecessary overhead. Binary serialization is more appropriate.

Federated Averaging

A basic aggregation algorithm is Federated Averaging.

If devices produce model updates:

Update A
Update B
Update C
Enter fullscreen mode Exit fullscreen mode

the server combines them using a weighted average, often based on the number of local training samples.

Conceptually:

Global weights =
    (nA * A + nB * B + nC * C)
    / (nA + nB + nC)
Enter fullscreen mode Exit fullscreen mode

This process creates the next global model.

Background Training

Android applications should not assume that long-running training can happen whenever the app is open.

For eligible background work, Android's WorkManager can coordinate deferrable tasks.

class FederatedTrainingWorker(
    appContext: Context,
    params: WorkerParameters
) : CoroutineWorker(appContext, params) {

    override suspend fun doWork(): Result {
        // Download model
        // Train locally
        // Upload update

        return Result.success()
    }
}
Enter fullscreen mode Exit fullscreen mode

The actual scheduling constraints should consider battery, network availability, charging state, and device resources.

Network Constraints

Training updates can be large.

Configure background work to use appropriate network constraints:

val constraints = Constraints.Builder()
    .setRequiredNetworkType(
        NetworkType.UNMETERED
    )
    .build()
Enter fullscreen mode Exit fullscreen mode

For many applications, Wi-Fi-only uploads are a sensible starting point.

Protecting Model Updates

Use HTTPS and authenticated requests.

Also consider:

  • Request authentication
  • Device attestation where appropriate
  • Signed model artifacts
  • Checksums
  • Replay protection
  • Server-side validation

Do not trust model updates simply because they came from an authenticated client.

Differential Privacy

Federated learning alone does not guarantee privacy.

One additional technique is differential privacy. A simplified training pipeline may:

Local gradients
     ↓
Clip sensitivity
     ↓
Add calibrated noise
     ↓
Upload update
Enter fullscreen mode Exit fullscreen mode

The exact privacy parameters must be chosen carefully and evaluated mathematically.

Secure Aggregation

Secure aggregation can prevent the server from seeing individual client updates in plaintext.

Instead, the protocol allows the server to recover an aggregate without learning each participant's contribution.

This is considerably more complex than basic federated averaging and should be treated as a separate security layer.

Handling Unreliable Devices

Mobile clients frequently disappear from the network.

The server should tolerate:

  • Offline devices
  • App termination
  • Partial participation
  • Slow clients
  • Duplicate submissions
  • Outdated model versions

Every update should include a model version and unique training-round identifier.

Battery and Thermal Considerations

Local training can consume significant resources.

Before training, check:

  • Battery level
  • Charging state
  • Thermal conditions
  • Available storage
  • Available memory
  • Network state

A production application should prefer small training workloads rather than continuously training a large model.

Evaluation

Do not evaluate only the global model.

Track:

Global accuracy
Per-device accuracy
Training rounds
Client participation
Communication volume
Training time
Battery consumption
Enter fullscreen mode Exit fullscreen mode

This helps identify whether improvements come at an unacceptable mobile cost.

Conclusion

Federated learning demonstrates how Android devices can participate in machine-learning training while keeping raw training data on the device.

A serious production system requires more than local training and averaging. Authentication, secure model distribution, privacy mechanisms, unreliable-device handling, resource constraints, and robust evaluation all need to be considered.

This makes federated learning an excellent advanced Kotlin and AI/ML project for developers who want to move beyond conventional Android machine-learning integrations.

Useful Links

SDK Flutter: https://github.com/v-modal/vmodal_sdk_flutter

SDK Android: https://github.com/v-modal/vmodal_sdk_android

Discord: https://discord.gg/K72z28KUx

Top comments (0)