Cifer is a Federated Learning framework with integrated Fully Homomorphic Encryption (FHE) for secure, decentralized model training and encrypted aggregation.
It improves model robustness, reduces bias, and handles distribution shift across non-IID data.
Supports both centralized and decentralized topologies by default, with optional Cifer Blockchain integration for auditability and provenance.
🌎 Website |
📔 Docs |
🙌 Join Slack
Cifer Python Package (PyPI)
The cifer Python package provides a secure, programmatic interface for executing Privacy-Preserving Machine Learning (PPML) workflows. It enables local and distributed model training using Federated Learning (FL) and Fully Homomorphic Encryption (FHE)—without ever exposing raw data.
This package is ideal for Python developers, researchers, and data scientists who need fine-grained control over federated workflows within trusted or adversarial environments.
For alternative development workflows:
- Use the Cifer Python Package for direct integration into custom Python-based ML pipelines
- Use Cifer Workspace for browser-based, no-code orchestration and collaborative workspace
What is Cifer Federated Learning?
Cifer Federated Learning (FedLearn) is a secure training framework that enables collaborative machine learning across distributed data sources—without ever sharing raw data. Each participant (or node) performs local training, and only encrypted model updates are exchanged across the network.
Rather than centralizing data into a vulnerable repository, Cifer coordinates encrypted computations between participants, preserving data sovereignty, compliance, and confidentiality across jurisdictions and organizations.
Key Extensions Beyond Standard FL
-
Fully Homomorphic Encryption (FHE) \
Cifer integrates FHE at the protocol level, allowing model updates and gradients to be computed on encrypted tensors. This ensures data remains encrypted throughout the lifecycle—including training, aggregation, and communication.\
Unlike differential privacy (DP), which introduces noise and cannot fully prevent reconstruction attacks, FHE offers cryptographic guarantees against adversarial inference—even in hostile environments.
-
Dual Topology Support: Centralized and Decentralized \
Cifer supports both:
- Client–Server (cFL): A central coordinator aggregates updates from authenticated participants—ideal for trusted, enterprise-level deployments.
- Peer-to-Peer (dFL): Participants can operate without a central aggregator, enabling direct encrypted update exchanges across nodes for higher resilience.
-
Secure Communication Channels\
All communication is conducted over gRPC, leveraging HTTP/2 and Protocol Buffers for efficient, multiplexed, and encrypted transport. This ensures fast synchronization while minimizing attack surfaces.
-
Blockchain Integration (Optional)\
For use cases requiring immutable audit trails, decentralized identity, or consensus-based coordination, Cifer supports integration with its proprietary Cifer Blockchain Network, providing an additional layer of provenance and tamper resistance.
Federated Learning and the Adversarial Threat Model
Standard federated learning protocols are susceptible to:
- Gradient leakage and model inversion attacks
- Malicious participant injection
- Data reconstruction through side-channel inference
The industry trend has been to use differential privacy (DP) to mitigate these threats. However:
- DP requires complex tuning of privacy budgets (ε, δ)
- It introduces statistical noise, reducing model accuracy
- It provides probabilistic—not cryptographic—guarantees, and can still leak information under repeated queries or cumulative exposure
Cifer’s FHE-based design eliminates these risks by ensuring that all shared model artifacts remain mathematically unreadable, even under active attack or node compromise.
Performance Capacity
Cifer FedLearn is built for real-world scale:
- Supports client-server and P2P topologies
- Tested for model sizes and parameter transfers up to 30GB
- Optimized for GPU acceleration, NUMA-aware compute, and multi-node orchestration
Core Modules
- FedLearn\
Orchestrates decentralized training across multiple nodes while maintaining data locality. Supports both:
- Centralized FL (cFL) for governed, trusted environments
- Decentralized FL (dFL) with peer coordination across encrypted channels
- HomoCryption (FHE)\
Allows computation on encrypted data throughout the training lifecycle, preserving privacy even during intermediate operations.
Key Capabilities
- Hybrid Federation Support\
Choose between cFL or dFL architectures depending on governance, trust, and fault tolerance requirements.
- Secure Communication Protocol\
Powered by gRPC with HTTP/2 and Protocol Buffers:
- Low-latency streaming
- Compact serialized messages
- Built-in encryption and authentication
- End-to-End Encrypted Computation\
FHE is embedded directly into the training workflow. No intermediate decryption. Data privacy is mathematically guaranteed.
Before Getting Started
To ensure a smooth experience using Cifer for Federated Learning (FL) and Fully Homomorphic Encryption (FHE), please verify your system meets the following baseline requirements:
System Requirements
- Operating System
- Linux (Ubuntu 18.04 or later)
- macOS (10.14 or later)
- Windows 10 or later
- Python
- Version: 3.9 (only version officially supported)
- Memory
- Minimum: 8 GB RAM
- Recommended: 16 GB+ for large-scale training or encryption tasks
- Storage
- At least 30 GB of available disk space
- Network
- Stable internet connection (required for remote collaboration or coordination modes)
GPU Acceleration (Optional)
Cifer supports GPU acceleration for both FL and FHE components using:
- NVIDIA CUDA (for TensorFlow, PyTorch pipelines)
- Google TPU (via JAX and compatible backends)
While GPU is not mandatory, it is highly recommended for encrypted training at scale or production-grade deployments.
Getting Started with Cifer’s Federated Learning
Cifer provides a modular Federated Learning (FL) framework that enables privacy-preserving model training across distributed environments. To get started, install the package via pip, import the required modules, and choose your preferred communication method for orchestration.
What's Included in pip install cifer
Installing Cifer via pip provides the following components and features:
Core Modules
- FedLearn: Federated learning engine for decentralized model training.
- HomoCryption: Fully Homomorphic Encryption (FHE) for computation on encrypted data.
Integrations
- Built-in compatibility with TensorFlow**,** PyTorch, scikit-learn, NumPy, CUDA, JAX, Hugging Face Transformers.
Utilities
- Data preprocessing tools
- Privacy-preserving metrics
- Secure aggregation algorithms
Cryptographic Libraries
- Integration with advanced homomorphic encryption backends
Communication Layer
- gRPC-based secure communication protocols for FL orchestration
Command-Line Interface (CLI)
- CLI client for managing experiments and configurations
Example Notebooks
- Jupyter notebooks demonstrating end-to-end workflows
Optional Dependencies
Install extras using:
pip install "cifer[server]"
Options:
server: gRPC / WebSocket server dependencies
vision: Vision-related helpers
audio: Audio-related helpers
nlp: Transformer-related helpers
graph: Graph dataset / PyG helpers
geo: Geospatial helpers
3d: 3D helpers
medical: Medical imaging helpers
agent: API / agent runtime dependencies
notebook: Jupyter and notebook tooling
dev: test and documentation tooling
all: Installs all optional dependencies
1. Install Cifer
pip install cifer
To include all optional features:
pip install "cifer[all]"
2. Quick Start
For the current package, the most reliable starting point is the CLI demo flow.
Create a Project
cifer init my-cifer-project
This creates a local project skeleton with:
dataset/
models/
config.yaml
Create a Toy Dataset
cifer dataset toy --output demo_artifacts/toy_dataset.npz
Run a One-Command Local Demo
cifer demo train --output-dir demo_artifacts --epochs 3
This command:
- creates a minimal
.npz dataset
- creates a default
.keras model
- trains locally and prints the final accuracy
3. Python API
The current Python API centers on CiferClient, CiferServer, and securetrain.
Import Modules
from cifer import CiferClient, CiferServer, CiferConfig
from cifer.securetrain import (
generate_named_keys,
encrypt_dataset,
train_model,
decrypt_dataset,
decrypt_model,
)
Dataset Format
For standard local training, CiferClient expects a .npz dataset containing:
train_images
train_labels
For graph workloads, use a .pt dataset instead.
Local Client Example
from cifer import CiferClient
client = CiferClient(
encoded_project_id="YOUR_PROJECT_ID",
encoded_company_id="YOUR_COMPANY_ID",
encoded_client_id="YOUR_CLIENT_ID",
base_api="https://workspace.cifer.ai/FederatedApi",
dataset_path="dataset/toy_dataset.npz",
model_path="models/toy_model.keras",
use_encryption=False,
epochs=3,
)
model, accuracy = client.train_model()
print("accuracy:", accuracy)
If model_path does not exist yet, Cifer will create a default Keras model automatically for standard .npz datasets.
Multi-round Federated Training
Start a three-client WebSocket server:
export CIFER_JWT_SECRET="a-secret-with-at-least-32-bytes"
python examples/run_federated_server.py
In another terminal, start three clients with separate local datasets:
export CIFER_JWT_SECRET="a-secret-with-at-least-32-bytes"
python examples/run_federated_clients.py \
--dataset client_a.npz client_b.npz client_c.npz \
--rounds 3 \
--epochs 1
For each round, authenticated clients receive the latest global Keras weights,
train locally, submit their update with the local sample count, wait for
weighted FedAvg, and save the returned global model. A client can use the same
flow directly:
history = client.run_federated_rounds(
server_uri="ws://127.0.0.1:8765",
token=jwt_token,
rounds=3,
round_prefix="training-run-001",
client_state_dir=".cifer-client-state",
)
With client_state_dir, restarting the same run resends pending updates with
their original ID and weights, restores completed rounds, and continues the
remaining rounds without repeating completed local training. Use the same
endpoint, transport, client identity, prefix, and total round count when
resuming; use a new prefix for a new training run. Authentication tokens are
not stored. The gRPC training APIs support the same option. See
docs/RETRY_SAFE_UPDATES.md for recovery semantics
and filesystem requirements.
Each authenticated client can submit only one update per named round.
Every update also records the global model_version it was trained from, so
stale updates are rejected. To restore completed rounds and the latest global
weights after a restart, configure a durable state directory:
from cifer.server import run_federated_server
run_federated_server(
n_round_clients=3,
custom_model=model,
round_state_dir=".cifer-state",
)
Round metadata exposes lifecycle state, participants, sample counts, quorum,
and model version. FederatedServer also provides create_round(),
get_round_status(), cancel_round(), and resume_round() for operators.
When validation_data or an evaluator callable is configured, completed
rounds also store evaluation metrics such as loss and accuracy. The same
round record exposes the persisted checkpoint path through
get_round_status() and get_latest_checkpoint_path(), and forwards the
metrics to TrainingMonitor.
Authenticated gRPC Training
Install the server transport dependencies:
pip install "cifer[server]"
Start the included gRPC example:
export CIFER_JWT_SECRET="a-secret-with-at-least-32-bytes"
python examples/grpc/server.py
Clients authenticate with a JWT bearer token and use the same round IDs,
model versions, sample counts, weighted aggregation, and global checkpoints as
the WebSocket transport. The high-level client API is:
history = client.run_federated_rounds_grpc(
server_address="127.0.0.1:8765",
token=jwt_token,
rounds=3,
)
For TLS, start the server with a grpcs:// address plus certfile and
keyfile. Connect the client with a grpcs:// address and pass the CA file via
root_certificates. See examples/grpc/server.py and
examples/grpc/client.py for environment-based configuration.
Configurable Aggregation
FedAvg remains the default and weights client models by sample count. To use
coordinate-wise FedMedian or TrimmedMean in network rounds:
from cifer.server import FederatedServer
server = FederatedServer(
n_round_clients=5,
aggregation_strategy="trimmedmean",
trim_ratio=0.2,
round_state_dir=".cifer-state",
)
The same options are accepted by run_federated_server() and CiferServer.
FedMedian and TrimmedMean validate sample counts but give clients equal weight.
TrimmedMean sorts each coordinate, removes floor(client_count * trim_ratio)
values from each tail, and averages what remains. trim_ratio must be between
0 and 0.5 exclusively. The client count must allow at least one value to be
removed from each tail and at least one to remain. For example, ratio 0.2
requires at least five clients; ratio 0.34 supports three clients.
Start network rounds using the included YAML configuration:
export CIFER_JWT_SECRET="a-secret-with-at-least-32-bytes"
cifer federated-server --config examples/robust_server.yaml
cifer federated-server --clients 5 --aggregation-strategy fedmedian
cifer federated-server --clients 5 --aggregation-strategy trimmedmean --trim-ratio 0.2 --host grpc://127.0.0.1
Explicit CLI flags override YAML values. The legacy API-backed cifer server
command also accepts --aggregation-strategy and --trim-ratio.
These robust strategies operate on plaintext weights and reduce some outlier
effects; they do not guarantee detection of poisoning or backdoors. Paillier
encrypted aggregation supports FedAvg only and rejects the robust choices.
Non-IID clients can affect robustness, so compare strategies on your own data.
Run the reproducible training benchmark from a source checkout or source distribution:
python -m examples.benchmark_robust_aggregation --output-dir demo_artifacts/robust
See the benchmark report for measured results
and scope. Use a fresh output directory for each benchmark invocation.
Model Delta Clipping