Skip to content

About

用于联邦学习相关实验,尽量以函数式编程的思想来编写,尽量做到简单可用。

Resources

Contributing

Stars

2 stars

Watchers

0 watching

Forks

Latest commit

 

History

261 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation


🌐 语言选择 / Language

中文 (Chinese) 英文 (English)
📖 README_CN.md 📖 README.md

中文优先 / Chinese First — 推荐先阅读中文版文档


PDFFed — Three Challenges, One Prototype

PDFFed addresses three open challenges in heterogeneous federated learning through a unified prototype-driven mechanism: privacy leakage from sensitive attribute exchange, representation bias that degrades fairness, and the local-vs-global fairness gap under statistical heterogeneity.


Fairness Federated Learning Framework

A production-grade fairness-aware federated learning research framework | 28+ Algorithms | 3 Task Types | 10 Datasets | Full-Stack Engineering


Table of Contents


Overview

You're doing fairness-aware federated learning research and need to run extensive benchmarking experiments:

  • 10+ baselines vs. your method
  • 10 datasets across tabular / image / text modalities
  • 4 data partitioning strategies (Uniform, Dirichlet 0.1/0.5/1.0), 3 client scales (20/30/40)
  • Each experiment repeated 3× for Mean ± STD
  • Compute from mixed sources: local RTX 4090/5090, rented P4 machines, shared lab servers

This framework is built for exactly that. It's not a "just-get-it-running" script — it's a battle-tested, production-grade experiment system shaped by real-world large-scale experimentation.

At a Glance

Dimension Count
Total Algorithms 28+ (23 active + backups)
Fairness-aware FL 13
Standard FL Baselines 6
One-shot FL 3
Task Types Tabular / Image / Text / Audio Classification
Datasets 12
Model Architectures BERT / CNN / Conv-RNN / ANN / Logistic Regression

Engineering Optimizations

Every optimization below was born from real pain during large-scale experiments. No fluff.

1. AMP (Automatic Mixed Precision) — Hardware-Aware

  • Auto-detects GPU Compute Capability: CC >= 7.0 (V100/T4/RTX 2080/A100/4090/5090, etc.) → enables FP16; older GPUs (P4/K80) → auto-disabled
  • All 24 algorithms unified — AMP is resolved once at the Experiment() entry layer via param_dict['use_amp'] (supports True / False / "auto"), regardless of which main_*.py entry point or run_experiments.py is used
  • Uses PyTorch's built-in torch.cuda.amp — zero extra dependencies
  • Correctly handles gradient accumulation + GradScaler interaction
  • 1.5×–2× training speedup, 30%–50% VRAM savings

Code: tool/amp_utils.py, experiment.py L502

2. Image Cache Stacked Tensors — 2× Memory Efficiency

  • Old: each sample stored as a separate Python dict → list of 5000 dicts in a .pt file
  • New: torch.stack into one big tensor (e.g., [5000, 3, 224, 224]), eliminating Python dict overhead
  • ~5× cache load speedup, ~50% RAM reduction
  • Covers all image datasets: CelebA / UTKFace / FairFace / LFWA+
  • Old-format caches auto-invalidated, auto-rebuilt

Code: module/dataset.py _load_shards_stacked()

3. Checkpoint & Resume — Per-Round, Per-Repeat Precision

  • Auto-saves checkpoint after every communication round: model weights, optimizer state, RNG seeds, client selection history
  • Three-level naming: Experiment_NO + repeat{N} + round_X
    save_path/checkpoint_repeat0_round_5.pt
    save_path/checkpoint_repeat0_round_10.pt
    
  • Resume mode auto-scans completed rounds and picks up exactly where it left off — never skips incomplete repeats
  • clean_old_checkpoints() for automatic cleanup of stale checkpoints

Code: tool/checkpoint.py

4. torch.compile Model Acceleration

  • Opt-in (default off) via param_dict['use_compile'] = True
  • BERT text tasks: auto-uses mode="reduce-overhead" to minimize recompilation from dynamic seq_len
  • CNN image tasks: default mode
  • Small tabular models: auto-skipped (compilation overhead > benefit)
  • Auto-detects PyTorch >= 2.0 availability; graceful fallback if unavailable

Code: module/experiment_setup.py Experiment_Create_model()

5. Memory-Aware DataLoader — OOM Prevention

  • Runtime memory monitoring: >85% usage → auto num_workers=0 to avoid multi-process fork MemoryError
  • Smart pin_memory (enabled for GPU training, disabled for CPU)
  • Image cache building uses ThreadPoolExecutor (shared memory) instead of ProcessPoolExecutor (fork explosion)
  • get_dataloader_config() for one-shot optimal DataLoader setup

Code: tool/memory_utils.py

6. Distributed Task Queue — Multi-Machine Collaboration

  • Uses a GitHub repository as the coordination hub (no OSS/NAS needed)
  • Per-task lock files + heartbeat mechanism to prevent race conditions
  • Heartbeat timeout auto-reclamation (if a P4 instance gets evicted, another machine takes over)
  • Contributor registration + hardware reporting + experiment reproducibility tracking (git hash, Python version, dependency list)
  • Worker script with background heartbeat, cloud checkpointing, SIGTERM graceful shutdown

Code: tool/task_queue.py, tool/worker.py

7. Cloud Storage Abstraction — Multi-Backend

  • Unified interface supporting 4 backends: local filesystem / Tencent COS / Alibaba OSS / AWS S3
  • Configurable via config file or environment variables; credentials in .gitignore
  • Automatic sync of datasets and checkpoints between local and cloud

Code: tool/cloud_storage.py

8. GPU+CPU Hybrid Parallel Scheduler

  • run_experiments.py: one script to launch the entire experiment matrix
  • Auto-detects available GPUs, schedules in tabular → image → text order
  • Mixed GPU + CPU parallel slots
  • Repeat experiments (Mean ± STD) automatically managed
  • Completed experiments auto-skipped (log-based detection)

Code: run_experiments.py

9. Email Notifications

  • Experiment completion / failure notifications via QQ Mail SMTP
  • Configuration file excluded from version control

Code: tool/notification.py

10. Contributor Identity & Stats

  • Each collaborator configures their academic identity (name, email, affiliation, Google Scholar, ORCID, OpenReview)
  • Experiments auto-record executor identity, hardware info, and duration
  • contrib_stats.py provides a compute contribution leaderboard

Code: tool/user_config.py, tool/contrib_stats.py

11. Universal Experiment Entry — One Framework, All Scenarios

  • 4 main_*.py entry points + run_experiments.py batch runner + unified Experiment() constructor
  • Regardless of how you launch, AMP / compile / checkpoint / memory optimizations all apply automatically
  • New algorithms only need to implement a standard interface to plug into the entire system

12. TensorBoard Deep Monitoring — Full Training Transparency

  • All 22 federated learning algorithms are integrated with TensorBoard for real-time visualization
  • Basic metrics (recorded every round): Accuracy, DEO, SPD, FR, HM, GPU time, communication cost
  • Gradient monitoring (recorded every round, based on weight delta, consistent with Scaffold/FedNova): per-layer update norms, client variance, cosine similarity, gradient signal-to-noise ratio (GSNR)
  • Representation quality (recorded every round): intra/inter-class distance ratio, sensitive attribute separability (lower = fairer)
  • Neural Collapse (recorded every round): representation collapse detection (within-class variance, centroid norm equality)
  • Fisher diagonal (recorded every round): parameter importance estimation (EWC-style)
  • Loss landscape sharpness (recorded every round): SAM-style loss surface sharpness
  • Activation statistics (recorded every round): dead neuron ratio, per-layer mean/variance/entropy
  • Update sparsity & stability (recorded every round): parameter update sparsity, layer-wise stability index
  • Client distribution divergence (recorded every round): JS divergence to estimate Non-IID degree
  • System monitoring (recorded every round): GPU memory usage, CPU memory usage
  • All monitoring modules are enabled by default and recorded every round; fine-grained control via param_dict['tb_monitor']
  • Zero additional GPU overhead design: gradient metrics are based on weight delta collected during training (pure CPU tensor subtraction), embedding/NC metrics reuse the forward pass from the test phase

Code entry: tool/tensorboard_logger.py


Getting Started Guide

Assumes you just git clone'd this repo, with an NVIDIA GPU and Anaconda/Miniconda installed.

Step 1: Environment Setup

# Clone the repo
git clone https://github.com/NOVAflyyy/fairness_fl_code.git
cd fairness_fl_code

# Create Conda environment (recommended)
conda env create -f environment.yml
conda activate FL

If Conda is too slow, use pip instead:

pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
pip install transformers numpy pandas scikit-learn scipy tqdm Pillow mat73 matplotlib openpyxl pyarrow requests psutil PyGithub soundfile

Step 2: Set Your Identity (Optional)

Edit tool/user_config.py with your name and email:

USER_NAME = "Your Name"
USER_EMAIL = "yourname@example.edu"
USER_AFFILIATION = "Your University"
USER_GITHUB = "your_github_id"

Step 3: Download Datasets

# Check which datasets are missing
python setup_data.py --check

# Download all missing datasets
python setup_data.py

# Or download specific ones
python setup_data.py --datasets celeba

Tabular datasets (ADULT / COMPAS / DRUG / DUTCH) and text datasets (moji / bios) are already bundled in the repo — no extra download needed.

Step 4: Run Your First Experiment

# Tabular classification (fastest — good for verifying your setup)
python main_Tabular_CLF.py -dataset ADULT -algorithm FedAvg

# Image classification
python main_IMG_CLF.py -dataset CelebA -algorithm FedAvg

# Text classification
python main_SENT_CLF.py -dataset bios -algorithm FedAvg

# Audio classification
python main_AUD_CLF.py -dataset CREMA-D -algorithm FedAvg

Step 5: Understand the Output

Results are saved to the result_path/ directory. Each output file name encodes the full experiment configuration.

Logs are in log_path/ — you'll see entries like:

INFO     : Communication Round 5/100 completed, avg loss: 0.4231
INFO     : Evaluation - Accuracy: 0.8523, DEO: 0.0312, SPD: 0.0287
INFO     : Checkpoint saved at round 5

Step 6: Run Batch Experiments

When you need to run the full experiment matrix (multiple algorithms × datasets × partitioning strategies):

# Edit run_experiments.py to configure your experiment matrix
# Then run:
python run_experiments.py

run_experiments.py auto-detects your GPUs, schedules tasks in parallel, and automatically skips already-completed experiments.


Project Structure

fairness_fl_code/
│
├── main.py                      # General entry (defaults to SENT_CLF)
├── main_Tabular_CLF.py          # Tabular classification entry
├── main_IMG_CLF.py              # Image classification entry
├── main_SENT_CLF.py             # Text classification entry
├── main_AUD_CLF.py              # Audio classification entry
├── experiment.py                # Core experiment class (AMP/checkpoint/compile unified entry)
├── run_experiments.py           # GPU+CPU hybrid parallel batch scheduler
├── setup_data.py                # Dataset download/pack tool
├── environment.yml              # Conda environment definition
├── README.md                    # This file (English)
├── README_CN.md                 # Chinese version
├── REFERENCES.md                # Paper reference list
│
├── algorithm/                   # 28+ federated learning algorithm implementations
│   ├── FederatedAverage.py      # FedAvg
│   ├── PDFFed.py                # PDFFed (core algorithm)
│   ├── FairFed.py / FedFair.py  # Fair FL algorithms
│   ├── PraFFL.py / LoGoFair.py  # Fair FL algorithms
│   ├── DOSFL.py / OSFL.py       # One-shot FL algorithms
│   ├── Scaffold.py              # SCAFFOLD
│   ├── FederatedProximal.py     # FedProx
│   ├── ...                      # More algorithms
│   ├── abandon/                 # Deprecated experimental algorithms
│   └── backup/                  # Backup algorithms
│
├── hypothesis/                  # Model definitions
│   ├── BERTCLASSIFIER.py        # BERT classifier (text)
│   ├── CNNCLASSIFIER.py         # RegularCNN (image)
│   ├── AUDIOCNNRNN.py           # AudioConvRNN (audio: Conv + bidirectional GRU)
│   ├── ANNCLASSIFIER.py         # MLP (tabular)
│   ├── LogisticRegression.py    # Logistic regression (tabular)
│   └── generator.py             # Generator (for distillation experiments)
│
├── module/                      # Core modules
│   ├── experiment_setup.py      # Experiment config automation (model creation/dataset detection/compile)
│   ├── dataset.py               # 10 dataset classes + image cache stack optimization
│   └── dataloader.py            # Federated learning DataLoader factory
│
├── tool/                        # Utility toolkit
│   ├── amp_utils.py             # AMP mixed precision (24 algorithms unified)
│   ├── checkpoint.py            # Checkpoint/resume (three-level naming/auto-cleanup)
│   ├── memory_utils.py          # Memory-aware DataLoader configuration
│   ├── cloud_storage.py         # Cloud storage abstraction (local/COS/OSS/S3)
│   ├── task_queue.py            # Distributed experiment task queue
│   ├── worker.py                # Distributed worker (heartbeat/cloud CKPT/graceful shutdown)
│   ├── notification.py          # Email notifications
│   ├── user_config.py           # Contributor identity configuration
│   ├── contrib_stats.py         # Contribution statistics & leaderboard
│   ├── logger.py                # Logging configuration
│   ├── utils.py                 # General utilities (Harmonic Mean, etc.)
│   ├── cleanup.py               # Cleanup utilities
│   ├── estimate_resources.py    # Resource estimation
│   └── config_checker.py        # Configuration checker
│
├── dataset/                     # Dataset directory
│   ├── ADULT/                   # Tabular data (bundled)
│   ├── COMPAS/                  # Tabular data (bundled)
│   ├── DRUG/                    # Tabular data (bundled)
│   ├── DUTCH/                   # Tabular data (bundled)
│   ├── moji/                    # Text data (bundled)
│   ├── bios/                    # Text data (bundled)
│   ├── celeba/                  # CelebA labels (bundled) + images (downloadable)
│   ├── UTKFace/                 # Images (downloadable)
│   ├── FairFace/                # Images (downloadable)
│   ├── LFWAPlus/                # Images (downloadable)
│   └── cache/                   # Image cache (auto-generated, gitignored)
│
├── save_path/                   # Model checkpoints (gitignored)
├── log_path/                    # Experiment logs (gitignored)
├── result_path/                 # Experiment results (gitignored)
│
├── ablation/                    # Ablation study scripts
├── patch_experiment/            # Experiment patches
├── plot_quadrantal_diagram.py   # Quadrant diagram plotter
└── DataScalability.py           # Data scalability experiment

Algorithms

Fairness-Aware Federated Learning

Algorithm File Core Idea
PDFFed PDFFed.py Probability distribution-driven fair FL via unified prototype
FairFed FairFed.py Adaptive margin loss + global fairness-aware aggregation
FedFair FedFair.py Local fairness-constrained training with regularization
FedFB FedFB.py FairBatch extension for federated learning
FedMix FedMix.py Mixup approximation in federated learning
NaiveMix NaiveMix.py Naive application of standard Mixup to FL
FL_FairBatch FL_FairBatch.py FairBatch strategy for group fairness
mFairFL mFairFL.py Multi-objective optimization of accuracy and fairness
Simple_mFairFL Simple_mFairFL.py Simplified multi-objective fair FL
FedRenyi FederatedRenyi.py Rényi divergence-based fair inference
PraFFL PraFFL.py Preference-driven fair FL with hypernetwork
FedFACT FedFACT.py Controllable group-fairness calibration
LoGoFair LoGoFair.py Post-processing for local and global fairness

Standard Federated Learning

Algorithm File Core Idea
FedAvg FederatedAverage.py Weighted average aggregation
FedProx FederatedProximal.py Proximal regularization for local updates
SCAFFOLD Scaffold.py Control variates to correct client drift
FedNova FederatedNova.py Normalized heterogeneous updates
FedProto FederatedProto.py Prototype learning with knowledge distillation
FedRep FederatedRep.py Representation-classifier decoupled training
ProxProbability ProxProbability.py FedAvg + data-volume weighted client selection

One-Shot Federated Learning

Algorithm File Core Idea
DOSFL DOSFL.py Distilled one-shot FL via knowledge distillation
OSFL OSFL.py One-shot FL baseline with meta-learning
CoBoosting CoBoosting.py Data and ensemble co-boosting for one-shot FL
SeparateTraining SeparateTraining.py Per-client independent training (non-FL baseline)

Full paper references: REFERENCES.md.


Datasets

Tabular Classification (Tabular_CLF)

Dataset Task Sensitive Attribute Size Source
ADULT Income prediction Gender, Race ~48K samples UCI
COMPAS Recidivism prediction Race, Gender ~7K samples ProPublica
DRUG Drug use Ethnicity, Gender ~1.9K samples UCI
DUTCH Occupation prediction Gender ~60K samples CBS

Tabular datasets are bundled in the repo — ready to use after git clone.

Image Classification (IMG_CLF)

Dataset Task Sensitive Attribute Image Size Size
CelebA Attractiveness prediction Gender 64×64 ~1.4 GB
UTKFace Gender classification Race 64×64 ~1.5 GB
FairFace Binary classification (service_test label) Gender 224×224 ~500 MB
LFWA+ Attractiveness prediction Gender 64×64 ~100 MB

The "Task" column follows the actual loaders in module/dataset.py: CelebA and LFWA+ predict the Attractive attribute with gender as the sensitive attribute; FairFace predicts the service_test attribute with gender as the sensitive attribute; UTKFace predicts gender with race as the sensitive attribute. Label files are bundled in the repo; images must be downloaded via python setup_data.py.

Text Classification (SENT_CLF)

Dataset Task Sensitive Attribute Model Size
moji Sentiment analysis English dialect (AAE/SAE) BERT-base ~2.2M samples
bios Occupation classification Gender BERT-base ~400K samples

Text datasets are bundled in the repo — ready to use after git clone.

Audio Classification (AUD_CLF)

Dataset Task Sensitive Attribute Input Size
CREMA-D Valence prediction (HAP vs. other emotions) Race (default) / Gender (optional) log-Mel 300×64 ~450 MB
AudioMNIST Digit parity (even / odd) Gender log-Mel 100×64 ~1 GB
RAVDESS Valence prediction (HAP vs. other emotions) Gender log-Mel 300×64 ~209 MB

The "Task" column follows the loaders in module/dataset.py: CREMA-D and RAVDESS are both HAP-vs-rest binary tasks (HAP = 1, the other emotions = 0); AudioMNIST predicts digit parity. CREMA-D supports two protected attributes: race by default (Caucasian = 1), or gender via -sensitive_attribute gender (Male = 1). Gender runs write to result_path/CREMA-D_gender/ and do not overwrite the race results. RAVDESS uses actor gender as the sensitive attribute (odd actor IDs = Male = 1). All audio datasets split by speaker to avoid leakage. Audio clips must be downloaded via python setup_data.py --datasets CREMA-D AudioMNIST RAVDESS (RAVDESS comes from the upstream Zenodo record, with an automatic ModelScope mirror fallback). WAV files are decoded with soundfile and converted to log-Mel spectrograms with torchaudio — no FFmpeg / TorchCodec needed.


Advanced Usage

Full Parameter Configuration

# Each main_*.py supports rich command-line arguments
python main_Tabular_CLF.py \
    --dataset ADULT \
    --algorithm PDFFed \
    --lr 0.001 \
    --batch_size 128 \
    --communication_rounds 100 \
    --clients 20 \
    --partition Dirichlet05 \
    --exp_repeat_times 3 \
    --cuda 0 \
    --resume \
    --use_amp auto \
    --use_compile

Batch Experiment Matrix

Edit the configuration in run_experiments.py:

ALGORITHMS = ["PDFFed", "FairFed", "FedFair", "LoGoFair", "FedAvg"]
TABULAR_DATASETS = ["COMPAS", "DRUG", "DUTCH", "ADULT"]
SPLITS = ["Dirichlet01", "Dirichlet05", "Dirichlet1", "Uniform"]
CLIENTS = ["20Clients", "30Clients", "40Clients"]
EXP_REPEAT_TIMES = 3

Then launch with one command:

python run_experiments.py

Multi-Machine Distributed Experiments

# Register this machine as a Worker — auto-claims tasks from the queue
python tool/worker.py --type all --status

# Low-end GPU Worker (P4, etc. — AMP auto-disabled)
python tool/worker.py --type image --small_gpu

Requires configuring GitHub repo info in tool/task_queue.py.

AMP Configuration

# auto: auto-detect GPU capability (recommended)
python main_IMG_CLF.py --use_amp auto

# Force enable
python main_IMG_CLF.py --use_amp true

# Force disable
python main_IMG_CLF.py --use_amp false

Scientific contract: partitions, repeats, and resume

  • Dirichlet01, Dirichlet05, and Dirichlet1 are schema-v2 label-conditioned partitions, not quantity-skew partitions. For each class, one client-proportion profile is sampled and shared by the train and client-test allocation; the global test loader still covers the complete test dataset.
  • Repeat repeat_idx uses base_seed + 1000 * repeat_idx for both training and its paired partition. For the same dataset, partition specification, and repeat, every algorithm uses the same algorithm-independent partition cache key.
  • Sampling has a finite retry limit. If a valid minimum-size allocation is not sampled, the deterministic minimum_move_v1 repair is recorded as label_dirichlet_repaired_v2, together with the move count and per-client label, protected-attribute, and label/protected joint statistics.
  • The new partition names never consume an old split_indices.json. Only an explicitly selected LegacyQuantityDirichlet* alias may read that legacy quantity-skew format.
  • Resume is opt-in: checkpoints are considered only when -resume is present. Loading validates the experiment configuration, partition fingerprint, and repeat identity before restoring state. A repeat is complete only when its atomic metrics.json exists; a last-round checkpoint or log line alone is not a completion marker.
  • -final_artifact_policy accepts metrics_only, global_model, or full_state. The default, metrics_only, retains metrics, reproducibility metadata, and resource evidence without retaining large personal model states.
  • CUDA repeats must use -parallel_repeats 1. CPU-only repeats may use the multiprocessing repeat path.
  • Select AMP smoke modes explicitly with -use_amp false and -use_amp true; auto remains available for normal runs.
  • Historical quantity-skew measurements are not comparable with schema-v2 label-skew measurements. Keep them in separately labelled tables and do not combine their aggregates.
  • Partition cache: computed client partitions are cached under partition_cache/v2/<dataset>/<fingerprint>/ as indices.npz plus a READY marker. The fingerprint covers the partition specification and the train/test dataset fingerprints, and does not include the algorithm, so all algorithms share one entry. A missing entry is rebuilt deterministically: deleting the cache never changes results and only costs recomputation. -resume validates the fingerprint string rather than the cache files, so the directory is disposable and should not be archived with results.

Example: three paired, resumable text-classification repeats with the schema-v2 Dirichlet05 partition:

python main_SENT_CLF.py \
  -algorithm FedAvg \
  -dataset moji \
  -split_strategy Dirichlet05 \
  -num_clients_K 2 \
  -communication_round_I 2 \
  -algorithm_epoch_T 1 \
  -exp_repeat_times 3 \
  -parallel_repeats 1 \
  -base_seed 42 \
  -partition_min_size 1 \
  -partition_max_retries 100 \
  -use_amp true \
  -resume

TensorBoard & W&B Monitoring

All training metrics are automatically recorded and support real-time visualization. The framework supports both TensorBoard (default) and Weights & Biases (optional).

TensorBoard (Default)

# Install TensorBoard (if not installed)
pip install tensorboard

# Run experiments normally (auto-recording)
python main_Tabular_CLF.py --dataset ADULT --algorithm FedAvg

# Launch TensorBoard to view
tensorboard --logdir=./tb_logs

# Bind all network interfaces (for remote access)
tensorboard --logdir=./tb_logs --bind_all

Weights & Biases (Optional)

To use W&B instead of TensorBoard, set the environment variable:

# Enable W&B logging
export USE_WANDB=1

# Login to W&B (first time only)
wandb login

# Run experiments normally
python main_Tabular_CLF.py --dataset ADULT --algorithm FedAvg

# View results at https://wandb.ai

Monitoring Metrics

Category Metrics Frequency Paper Source
Basic Test Accuracy, DEO, SPD, FR, HM, GPU time, communication cost Every round —
Gradient Analysis Per-layer update norms, total norm, clipping ratio, client variance, GSNR, cosine similarity Every round Scaffold, FedNova
Representation Quality Intra/inter-class distance ratio, sensitive attribute separability Every round —
Neural Collapse within-class variance, centroid norm equality, max inter-class cosine Every round Papyan et al. 2020
Fisher Diagonal Parameter importance estimation Every round EWC (Kirkpatrick 2017)
Loss Sharpness Loss surface sharpness Every round SAM (Foret et al. 2021)
Activation Statistics Dead neuron ratio, per-layer mean/variance/entropy Every round —
Update Statistics Sparsity, stability index Every round —
Client Divergence JS divergence (label/sensitive attribute distribution) Every round —
System Monitoring GPU memory, CPU memory Every round —

Custom Monitoring Configuration

All modules are enabled by default. To disable specific modules or adjust frequency:

# Set in param_dict
param_dict['tb_monitor'] = {
    'fisher': False,              # Disable Fisher (computationally heavy)
    'sharpness': False,           # Disable Sharpness
    'gradient_freq': 10,          # Change gradient metrics to every 10 rounds
    'embedding_samples': 500,     # Number of embedding samples to collect
}

Citation

@misc{fairness_fl_code,
  title   = {Fairness Federated Learning Framework},
  author  = {Zhiyong Ma},
  year    = {2025},
  url     = {https://github.com/NOVAflyyy/fairness_fl_code}
}

License

This project is for academic research purposes. See LICENSE if available.


Last updated: 2025

Chinese documentation: README_CN.md

PraFFL (paper-faithful BERT adaptation)

PraFFL follows Preference-aware Fair Federated Learning. For SENT_CLF, only the BERT encoder is communicated. Client k keeps a private persistent two-input hypernetwork that maps (accuracy_weight, fairness_weight) to the weight and bias of the binary linear head; generated tensors are applied functionally so the private update remains differentiable.

Each selected client executes praffl_tau_c communicated epochs and then praffl_tau_p personalized epochs. The first phase fixes preference (0.5, 0.5), freezes the generated head, and updates the encoder with cross-entropy. The second phase freezes/detaches one encoder feature per batch, samples Dirichlet([1, 1]) preferences, and updates only the private hypernetwork with the differentiable DP covariance surrogate and inverse-weighted smooth Tchebycheff loss. praffl_tau_c + praffl_tau_p must equal algorithm_epoch_T.

Final repeat metrics preserve top-level ACC, DEO, and signed SPD at praffl_report_preference (default 0.5 0.5). These values are the mean across all private heads on the common global test loader. metrics.json also records praffl.local and praffl.global, each with every client's preference solutions, nondominated objective points (1 - ACC, DP disparity), per-client hypervolume, and mean hypervolume. Hypervolume uses minimization reference point (1, 1). A local/global split without both protected groups raises a diagnostic evaluation error rather than being reported as zero disparity.

Key controls:

Flag Default Meaning
-praffl_tau_c half of algorithm_epoch_T communicated encoder epochs
-praffl_tau_p remaining epochs private hypernetwork epochs
-praffl_preference_batch_size 8 Dirichlet preferences per personalized batch
-praffl_hypernetwork_hidden_dim 256 private hypernetwork width
-praffl_hypernetwork_learning_rate 0.001 private Adam learning rate
-praffl_smooth_gamma 1.0 log-sum-exp smoothness
-praffl_report_preference 0.5 0.5 comparison-table preference
-praffl_preference_points 1000 deterministic Pareto-grid size
-praffl_preference_chunk_size 128 heads evaluated per feature chunk

PraFFL is serial on one GPU: the global model plus one selected client's local copy/private hypernetwork are active, inactive private hypernetworks remain CPU state dictionaries, and only the latest resumable checkpoint is retained.

Paper-faithful FedFACT-In baseline

FedFACT denotes FedFACT-In at the pinned paper/code version, not FedFACT-Post. This implementation accepts only binary SENT_CLF models with two logits and requires every client (FL_fraction=1, FL_drop_rate=0). The selected constraint is explicit through fairness_metric=DP|EO, global_constraint, and local_constraint; EO applies both label-conditioned constraints.

Predictions, dual updates, and evaluation use the probability ensemble of the final server model theta and each persistent client-private model phi_k. Only unified updates theta_k are transmitted and aggregated. Missing protected/label support fails closed. Results report selected global fairness, mean/max local fairness, and constraint violations. Checkpoints retain all private models, positive/negative global/local duals, ensemble weights, AMP scaler, RNG, counters, and client history, keeping only the latest resumable state. Final reporting evaluates the final-state ensemble rather than claiming the theoretical time-average classifier.

CUDA_VISIBLE_DEVICES=0 /home/ronnie/anaconda3/envs/FL/bin/python main_SENT_CLF.py -algorithm FedFACT -dataset moji -split_strategy Dirichlet1 -num_clients_K 2 -algorithm_epoch_T 1 -communication_round_I 1 -fairness_metric DP -global_constraint 0.01 -local_constraint 0.01 -parallel_repeats 1 -checkpoint_keep_latest 1 -resume

About

用于联邦学习相关实验,尽量以函数式编程的思想来编写,尽量做到简单可用。

Resources

Contributing

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages