🌐 语言选择 / Language
| 中文 (Chinese) | 英文 (English) |
|---|---|
| 📖 README_CN.md | 📖 README.md |
中文优先 / Chinese First — 推荐先阅读中文版文档
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.
A production-grade fairness-aware federated learning research framework | 28+ Algorithms | 3 Task Types | 10 Datasets | Full-Stack Engineering
- Overview
- Engineering Optimizations
- Getting Started Guide
- Project Structure
- Algorithms
- Datasets
- Advanced Usage
- Citation
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.
| 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 |
Every optimization below was born from real pain during large-scale experiments. No fluff.
- 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 viaparam_dict['use_amp'](supportsTrue/False/"auto"), regardless of whichmain_*.pyentry point orrun_experiments.pyis 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.pyL502
- Old: each sample stored as a separate Python dict → list of 5000 dicts in a
.ptfile - New:
torch.stackinto 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()
- Auto-saves checkpoint after every communication round: model weights, optimizer state, RNG seeds, client selection history
- Three-level naming:
Experiment_NO+repeat{N}+round_Xsave_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
- 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.pyExperiment_Create_model()
- Runtime memory monitoring: >85% usage → auto
num_workers=0to avoid multi-process fork MemoryError - Smart
pin_memory(enabled for GPU training, disabled for CPU) - Image cache building uses
ThreadPoolExecutor(shared memory) instead ofProcessPoolExecutor(fork explosion) get_dataloader_config()for one-shot optimal DataLoader setup
Code:
tool/memory_utils.py
- 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
- 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
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
- Experiment completion / failure notifications via QQ Mail SMTP
- Configuration file excluded from version control
Code:
tool/notification.py
- Each collaborator configures their academic identity (name, email, affiliation, Google Scholar, ORCID, OpenReview)
- Experiments auto-record executor identity, hardware info, and duration
contrib_stats.pyprovides a compute contribution leaderboard
- 4
main_*.pyentry points +run_experiments.pybatch runner + unifiedExperiment()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
- 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
Assumes you just
git clone'd this repo, with an NVIDIA GPU and Anaconda/Miniconda installed.
# 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 FLIf 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 soundfileEdit 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"# 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 celebaTabular datasets (ADULT / COMPAS / DRUG / DUTCH) and text datasets (moji / bios) are already bundled in the repo — no extra download needed.
# 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 FedAvgResults 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
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.pyrun_experiments.py auto-detects your GPUs, schedules tasks in parallel, and automatically skips already-completed experiments.
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
| 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 |
| 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 |
| 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.
| 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.
| 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 viapython setup_data.py.
| 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.
| 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:raceby default (Caucasian= 1), or gender via-sensitive_attribute gender(Male= 1). Gender runs write toresult_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 viapython 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 withsoundfileand converted to log-Mel spectrograms withtorchaudio— no FFmpeg / TorchCodec needed.
# 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_compileEdit 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 = 3Then launch with one command:
python run_experiments.py# 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_gpuRequires configuring GitHub repo info in
tool/task_queue.py.
# 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 falseDirichlet01,Dirichlet05, andDirichlet1are 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_idxusesbase_seed + 1000 * repeat_idxfor 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_v1repair is recorded aslabel_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 selectedLegacyQuantityDirichlet*alias may read that legacy quantity-skew format. - Resume is opt-in: checkpoints are considered only when
-resumeis present. Loading validates the experiment configuration, partition fingerprint, and repeat identity before restoring state. A repeat is complete only when its atomicmetrics.jsonexists; a last-round checkpoint or log line alone is not a completion marker. -final_artifact_policyacceptsmetrics_only,global_model, orfull_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 falseand-use_amp true;autoremains 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>/asindices.npzplus aREADYmarker. 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.-resumevalidates 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 \
-resumeAll training metrics are automatically recorded and support real-time visualization. The framework supports both TensorBoard (default) and Weights & Biases (optional).
# 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_allTo 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| 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 | — |
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
}@misc{fairness_fl_code,
title = {Fairness Federated Learning Framework},
author = {Zhiyong Ma},
year = {2025},
url = {https://github.com/NOVAflyyy/fairness_fl_code}
}This project is for academic research purposes. See LICENSE if available.
Last updated: 2025
Chinese documentation: README_CN.md
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.
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