MEDfl 2.0.10.dev11__tar.gz → 2.0.10.dev12__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/LearningManager/xgboost/strategy.py +55 -2
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/rw/xgboost/strategy.py +55 -2
- medfl-2.0.10.dev12/PKG-INFO +457 -0
- medfl-2.0.10.dev12/README.md +437 -0
- medfl-2.0.10.dev12/medfl.egg-info/PKG-INFO +457 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/setup.py +1 -1
- medfl-2.0.10.dev11/PKG-INFO +0 -205
- medfl-2.0.10.dev11/README.md +0 -185
- medfl-2.0.10.dev11/medfl.egg-info/PKG-INFO +0 -205
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/LICENSE +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/LearningManager/__init__.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/LearningManager/client.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/LearningManager/dynamicModal.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/LearningManager/federated_dataset.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/LearningManager/flpipeline.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/LearningManager/model.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/LearningManager/params.yaml +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/LearningManager/params_optimiser.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/LearningManager/plot.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/LearningManager/server.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/LearningManager/shap/__init__.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/LearningManager/shap/aggregation.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/LearningManager/shap/config.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/LearningManager/shap/explainer.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/LearningManager/shap/xgboost_explainer.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/LearningManager/strategy.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/LearningManager/utils.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/LearningManager/xgboost/__init__.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/LearningManager/xgboost/client.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/LearningManager/xgboost/config.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/LearningManager/xgboost/data.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/LearningManager/xgboost/metrics.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/LearningManager/xgboost/serialization.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/LearningManager/xgboost/server.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/NetManager/__init__.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/NetManager/database_connector.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/NetManager/dataset.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/NetManager/flsetup.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/NetManager/net_helper.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/NetManager/net_manager_queries.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/NetManager/network.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/NetManager/node.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/__init__.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/rw/__init__.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/rw/client.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/rw/holdout.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/rw/identity.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/rw/model.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/rw/server.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/rw/strategy.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/rw/xgboost/__init__.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/rw/xgboost/client.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/rw/xgboost/config.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/rw/xgboost/data.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/rw/xgboost/metrics.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/rw/xgboost/serialization.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/scripts/__init__.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/scripts/base.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/MEDfl/scripts/create_db.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/alembic/__init__.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/alembic/env.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/medfl.egg-info/SOURCES.txt +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/medfl.egg-info/dependency_links.txt +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/medfl.egg-info/requires.txt +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/medfl.egg-info/top_level.txt +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/setup.cfg +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/tests/test_dataset.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/tests/test_federated_dataset.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/tests/test_flpipeline.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/tests/test_flsetup.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/tests/test_network.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/tests/test_node.py +0 -0
- {medfl-2.0.10.dev11 → medfl-2.0.10.dev12}/tests/test_rw_holdout.py +0 -0
|
@@ -239,7 +239,7 @@ class XGBoostSimulationStrategy:
|
|
|
239
239
|
f"{new_tree_count} new trees."
|
|
240
240
|
)
|
|
241
241
|
|
|
242
|
-
new_local_boosters.append(new_trees_booster)
|
|
242
|
+
new_local_boosters.append((new_trees_booster, fit_res.num_examples))
|
|
243
243
|
|
|
244
244
|
if not new_local_boosters:
|
|
245
245
|
print(
|
|
@@ -253,12 +253,32 @@ class XGBoostSimulationStrategy:
|
|
|
253
253
|
agg_parameters = booster_to_parameters(self.current_booster)
|
|
254
254
|
return agg_parameters, metrics
|
|
255
255
|
|
|
256
|
+
# Bagging adds the average of the clients' corrections, not their sum: every client starts from the
|
|
257
|
+
# same global model, so adding all their trees as they are applies the correction once per client
|
|
258
|
+
# (e.g. 9x with 9 clients) and the model overshoots and diverges.
|
|
259
|
+
total_examples = sum(max(int(num_examples or 0), 0) for _, num_examples in new_local_boosters)
|
|
260
|
+
scaled_boosters = []
|
|
261
|
+
|
|
262
|
+
for new_trees_booster, num_examples in new_local_boosters:
|
|
263
|
+
if total_examples > 0:
|
|
264
|
+
weight = max(int(num_examples or 0), 0) / total_examples
|
|
265
|
+
else:
|
|
266
|
+
weight = 1.0 / len(new_local_boosters)
|
|
267
|
+
|
|
268
|
+
scaled_booster = self._scale_leaf_values(new_trees_booster, weight)
|
|
269
|
+
|
|
270
|
+
if scaled_booster is None:
|
|
271
|
+
print("[Server/XGBoost] Failed to weight the client trees.")
|
|
272
|
+
return None, metrics
|
|
273
|
+
|
|
274
|
+
scaled_boosters.append(scaled_booster)
|
|
275
|
+
|
|
256
276
|
boosters_to_combine = []
|
|
257
277
|
|
|
258
278
|
if self.current_booster is not None:
|
|
259
279
|
boosters_to_combine.append(self.current_booster)
|
|
260
280
|
|
|
261
|
-
boosters_to_combine.extend(
|
|
281
|
+
boosters_to_combine.extend(scaled_boosters)
|
|
262
282
|
|
|
263
283
|
combined_booster = self._combine_boosters_by_json(boosters_to_combine)
|
|
264
284
|
|
|
@@ -445,6 +465,39 @@ class XGBoostSimulationStrategy:
|
|
|
445
465
|
except Exception:
|
|
446
466
|
pass
|
|
447
467
|
|
|
468
|
+
def _scale_leaf_values(
|
|
469
|
+
self,
|
|
470
|
+
booster: xgb.Booster,
|
|
471
|
+
factor: float,
|
|
472
|
+
) -> Optional[xgb.Booster]:
|
|
473
|
+
"""
|
|
474
|
+
Multiply every leaf value of the booster by factor, so its trees add factor x their prediction.
|
|
475
|
+
"""
|
|
476
|
+
if factor == 1.0:
|
|
477
|
+
return booster
|
|
478
|
+
|
|
479
|
+
try:
|
|
480
|
+
raw_json = booster.save_raw(raw_format="json")
|
|
481
|
+
if isinstance(raw_json, bytes):
|
|
482
|
+
raw_json = raw_json.decode("utf-8")
|
|
483
|
+
model = json.loads(raw_json)
|
|
484
|
+
|
|
485
|
+
for tree in model["learner"]["gradient_booster"]["model"]["trees"]:
|
|
486
|
+
left_children = tree["left_children"]
|
|
487
|
+
# a leaf stores its value in split_conditions
|
|
488
|
+
tree["split_conditions"] = [
|
|
489
|
+
value * factor if left_children[node] == -1 else value
|
|
490
|
+
for node, value in enumerate(tree["split_conditions"])
|
|
491
|
+
]
|
|
492
|
+
tree["base_weights"] = [weight * factor for weight in tree["base_weights"]]
|
|
493
|
+
|
|
494
|
+
scaled = xgb.Booster()
|
|
495
|
+
scaled.load_model(bytearray(json.dumps(model).encode("utf-8")))
|
|
496
|
+
return scaled
|
|
497
|
+
except Exception as exc:
|
|
498
|
+
print(f"[Server/XGBoost] Failed to scale the leaf values: {exc}")
|
|
499
|
+
return None
|
|
500
|
+
|
|
448
501
|
def _combine_boosters_by_json(
|
|
449
502
|
self,
|
|
450
503
|
boosters: list[xgb.Booster],
|
|
@@ -496,7 +496,7 @@ class XGBoostStrategy:
|
|
|
496
496
|
f"{new_tree_count} new trees."
|
|
497
497
|
)
|
|
498
498
|
|
|
499
|
-
new_local_boosters.append(new_trees_booster)
|
|
499
|
+
new_local_boosters.append((new_trees_booster, fit_res.num_examples))
|
|
500
500
|
|
|
501
501
|
if not new_local_boosters:
|
|
502
502
|
print(
|
|
@@ -510,12 +510,32 @@ class XGBoostStrategy:
|
|
|
510
510
|
agg_parameters = booster_to_parameters(self.current_booster)
|
|
511
511
|
return agg_parameters, metrics
|
|
512
512
|
|
|
513
|
+
# Bagging adds the average of the clients' corrections, not their sum: every client starts from the
|
|
514
|
+
# same global model, so adding all their trees as they are applies the correction once per client
|
|
515
|
+
# (e.g. 9x with 9 clients) and the model overshoots and diverges.
|
|
516
|
+
total_examples = sum(max(int(num_examples or 0), 0) for _, num_examples in new_local_boosters)
|
|
517
|
+
scaled_boosters = []
|
|
518
|
+
|
|
519
|
+
for new_trees_booster, num_examples in new_local_boosters:
|
|
520
|
+
if total_examples > 0:
|
|
521
|
+
weight = max(int(num_examples or 0), 0) / total_examples
|
|
522
|
+
else:
|
|
523
|
+
weight = 1.0 / len(new_local_boosters)
|
|
524
|
+
|
|
525
|
+
scaled_booster = self._scale_leaf_values(new_trees_booster, weight)
|
|
526
|
+
|
|
527
|
+
if scaled_booster is None:
|
|
528
|
+
print("[Server/XGBoost] Failed to weight the client trees.")
|
|
529
|
+
return None, metrics
|
|
530
|
+
|
|
531
|
+
scaled_boosters.append(scaled_booster)
|
|
532
|
+
|
|
513
533
|
boosters_to_combine = []
|
|
514
534
|
|
|
515
535
|
if self.current_booster is not None:
|
|
516
536
|
boosters_to_combine.append(self.current_booster)
|
|
517
537
|
|
|
518
|
-
boosters_to_combine.extend(
|
|
538
|
+
boosters_to_combine.extend(scaled_boosters)
|
|
519
539
|
|
|
520
540
|
combined_booster = self._combine_boosters_by_json(boosters_to_combine)
|
|
521
541
|
|
|
@@ -852,6 +872,39 @@ class XGBoostStrategy:
|
|
|
852
872
|
except Exception:
|
|
853
873
|
pass
|
|
854
874
|
|
|
875
|
+
def _scale_leaf_values(
|
|
876
|
+
self,
|
|
877
|
+
booster: xgb.Booster,
|
|
878
|
+
factor: float,
|
|
879
|
+
) -> Optional[xgb.Booster]:
|
|
880
|
+
"""
|
|
881
|
+
Multiply every leaf value of the booster by factor, so its trees add factor x their prediction.
|
|
882
|
+
"""
|
|
883
|
+
if factor == 1.0:
|
|
884
|
+
return booster
|
|
885
|
+
|
|
886
|
+
try:
|
|
887
|
+
raw_json = booster.save_raw(raw_format="json")
|
|
888
|
+
if isinstance(raw_json, bytes):
|
|
889
|
+
raw_json = raw_json.decode("utf-8")
|
|
890
|
+
model = json.loads(raw_json)
|
|
891
|
+
|
|
892
|
+
for tree in model["learner"]["gradient_booster"]["model"]["trees"]:
|
|
893
|
+
left_children = tree["left_children"]
|
|
894
|
+
# a leaf stores its value in split_conditions
|
|
895
|
+
tree["split_conditions"] = [
|
|
896
|
+
value * factor if left_children[node] == -1 else value
|
|
897
|
+
for node, value in enumerate(tree["split_conditions"])
|
|
898
|
+
]
|
|
899
|
+
tree["base_weights"] = [weight * factor for weight in tree["base_weights"]]
|
|
900
|
+
|
|
901
|
+
scaled = xgb.Booster()
|
|
902
|
+
scaled.load_model(bytearray(json.dumps(model).encode("utf-8")))
|
|
903
|
+
return scaled
|
|
904
|
+
except Exception as exc:
|
|
905
|
+
print(f"[Server/XGBoost] Failed to scale the leaf values: {exc}")
|
|
906
|
+
return None
|
|
907
|
+
|
|
855
908
|
def _combine_boosters_by_json(
|
|
856
909
|
self,
|
|
857
910
|
boosters: list[xgb.Booster],
|
|
@@ -0,0 +1,457 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: medfl
|
|
3
|
+
Version: 2.0.10.dev12
|
|
4
|
+
Summary: Python Open-source package for simulating federated learning and differential privacy
|
|
5
|
+
Home-page: https://github.com/MEDomics-UdeS/MEDfl
|
|
6
|
+
Author: MEDomics consortium
|
|
7
|
+
Author-email: medomics.info@gmail.com
|
|
8
|
+
Project-URL: Documentation, https://
|
|
9
|
+
Project-URL: Github, https://github.com/MEDomics-UdeS/MEDfl
|
|
10
|
+
Keywords: federated learning differential privacy medical research
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
17
|
+
Requires-Python: >=3.8,<3.15
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
License-File: LICENSE
|
|
20
|
+
|
|
21
|
+
<div align="center">
|
|
22
|
+
|
|
23
|
+
<img src="https://raw.githubusercontent.com/MEDomics-UdeS/MEDfl/main/medfl_logo.png" alt="MEDfl logo" width="220"/>
|
|
24
|
+
|
|
25
|
+
# MEDfl
|
|
26
|
+
|
|
27
|
+
**A collaborative framework for privacy-preserving federated learning in medicine**
|
|
28
|
+
|
|
29
|
+
[](https://pypi.org/project/medfl/)
|
|
30
|
+
[](https://www.python.org/)
|
|
31
|
+
[](LICENSE)
|
|
32
|
+
[](https://pypi.org/project/medfl/)
|
|
33
|
+
[](https://github.com/MEDomics-UdeS/MEDfl/graphs/contributors)
|
|
34
|
+
|
|
35
|
+
</div>
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
## Table of Contents
|
|
40
|
+
|
|
41
|
+
1. [Overview](#overview)
|
|
42
|
+
2. [Key Features](#key-features)
|
|
43
|
+
3. [Installation](#installation)
|
|
44
|
+
4. [Modes of Operation](#modes-of-operation)
|
|
45
|
+
5. [Quick Start — Real-World Federated Learning](#quick-start--real-world-federated-learning)
|
|
46
|
+
6. [Federated XGBoost](#federated-xgboost)
|
|
47
|
+
7. [Federated Explainability (SHAP)](#federated-explainability-shap)
|
|
48
|
+
8. [Federated Holdout Testing & Threshold Optimization](#federated-holdout-testing--threshold-optimization)
|
|
49
|
+
9. [Simulation Mode](#simulation-mode)
|
|
50
|
+
10. [Package Structure](#package-structure)
|
|
51
|
+
11. [Documentation](#documentation)
|
|
52
|
+
12. [Testing](#testing)
|
|
53
|
+
13. [Contributing](#contributing)
|
|
54
|
+
14. [Acknowledgment](#acknowledgment)
|
|
55
|
+
15. [Authors](#authors)
|
|
56
|
+
16. [License](#license)
|
|
57
|
+
|
|
58
|
+
---
|
|
59
|
+
|
|
60
|
+
## Overview
|
|
61
|
+
|
|
62
|
+
**MEDfl** is an open-source Python framework for **Federated Learning (FL)** in the **medical and healthcare domain**. It lets several institutions (hospitals, research centers, clinics) train a shared model **without ever moving patient data off-site**: only model updates and aggregate statistics leave each site.
|
|
63
|
+
|
|
64
|
+
MEDfl is built on top of [Flower](https://flower.ai) and supports both:
|
|
65
|
+
|
|
66
|
+
- **Simulation** of federated experiments on a single machine, for benchmarking and research; and
|
|
67
|
+
- **Real-world deployment** across physically distributed client machines.
|
|
68
|
+
|
|
69
|
+
Beyond training, MEDfl covers the full clinical-ML workflow: **differential privacy**, **gradient-boosted trees (XGBoost)**, **federated SHAP explainability**, **federated holdout evaluation** with pooled ROC/AUC, and **decision-threshold optimization** — all computed without centralizing data.
|
|
70
|
+
|
|
71
|
+
---
|
|
72
|
+
|
|
73
|
+
## Key Features
|
|
74
|
+
|
|
75
|
+
| Area | Capability |
|
|
76
|
+
| --- | --- |
|
|
77
|
+
| 🧩 **Two operation modes** | Local **simulation** (Flower simulation engine) and **real-world** distributed deployment (Flower server/clients). |
|
|
78
|
+
| 🧠 **Neural networks** | Configurable MLP (`Net`) with binary, multiclass, multilabel and regression heads; `DynamicModel` factory in simulation mode (binary/multiclass classifiers, linear & logistic regressors, CNN, RNN, LSTM, autoencoder). |
|
|
79
|
+
| 🌲 **Federated XGBoost** | Bagging-based federated XGBoost for binary classification, multiclass classification and regression, in both modes. |
|
|
80
|
+
| 🔁 **Aggregation strategies** | Any Flower strategy by name (`FedAvg`, `FedAdam`, `FedYogi`, `FedProx`, …) plus `FedXgbBagging` for trees. |
|
|
81
|
+
| 🔒 **Differential privacy** | Client-side DP-SGD via [Opacus](https://opacus.ai) (`DPConfig`: noise multiplier, gradient clipping, secure RNG). |
|
|
82
|
+
| 🔍 **Federated SHAP** | Each client computes local SHAP values (Gradient, Deep or Tree explainer); the server aggregates only summary statistics into global feature importance. |
|
|
83
|
+
| 🧪 **Federated holdout testing** | Final global model is tested on every client's private holdout file; the server reconstructs **exact pooled** confusion-matrix metrics and a pooled ROC curve/AUC. |
|
|
84
|
+
| 🎯 **Threshold optimization** | Optimized decision threshold (Youden's J or target sensitivity) chosen on pooled learning-set score histograms, then validated on the holdout. |
|
|
85
|
+
| ✂️ **Flexible data splits** | Global or per-client validation/test fractions, or explicit test IDs per client. |
|
|
86
|
+
| 🗄️ **Experiment management** | Simulation-mode networks, nodes, datasets, setups, pipelines and results stored in a relational database (SQLite / MySQL). |
|
|
87
|
+
| ⚙️ **Hyperparameter optimization** | Grid search and [Optuna](https://optuna.org)-based (including federated) hyperparameter tuning. |
|
|
88
|
+
| 📊 **Visualization** | Accuracy/loss curves, global and per-node confusion matrices, classification reports. |
|
|
89
|
+
| 💾 **Checkpointing** | Global model saved every *N* rounds (`.npz` for neural networks, `.ubj` for XGBoost). |
|
|
90
|
+
|
|
91
|
+
---
|
|
92
|
+
|
|
93
|
+
## Installation
|
|
94
|
+
|
|
95
|
+
MEDfl requires **Python 3.9 or later**.
|
|
96
|
+
|
|
97
|
+
**From PyPI**
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
pip install medfl
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
**From source (development version)**
|
|
104
|
+
|
|
105
|
+
```bash
|
|
106
|
+
git clone https://github.com/MEDomics-UdeS/MEDfl.git
|
|
107
|
+
cd MEDfl
|
|
108
|
+
pip install -e .
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
Main dependencies: `flwr[simulation]`, `torch`, `opacus`, `xgboost`, `shap`, `scikit-learn`, `pandas`, `optuna`, `SQLAlchemy`. See [requirements.txt](requirements.txt) for exact versions.
|
|
112
|
+
|
|
113
|
+
---
|
|
114
|
+
|
|
115
|
+
## Modes of Operation
|
|
116
|
+
|
|
117
|
+
| Mode | Package | Description | Typical use case |
|
|
118
|
+
| --- | --- | --- | --- |
|
|
119
|
+
| **Simulation** | `MEDfl.NetManager`, `MEDfl.LearningManager` | All clients run locally in a controlled environment; data partitions and experiments are tracked in a database. | Benchmarking, prototyping, methodological research. |
|
|
120
|
+
| **Real-world** | `MEDfl.rw` | A central server and remote clients communicate over the network; each client reads its own local CSV. | Multi-institution collaborations, production deployments. |
|
|
121
|
+
|
|
122
|
+
---
|
|
123
|
+
|
|
124
|
+
## Quick Start — Real-World Federated Learning
|
|
125
|
+
|
|
126
|
+
In real-world mode, **the server owns the experiment configuration** (features, target, splits, rounds, hyperparameters) and pushes it to the clients. Clients only need to point to their local CSV file.
|
|
127
|
+
|
|
128
|
+
### 1. Server
|
|
129
|
+
|
|
130
|
+
```python
|
|
131
|
+
from MEDfl.rw.server import FederatedServer
|
|
132
|
+
from MEDfl.rw.strategy import Strategy
|
|
133
|
+
|
|
134
|
+
strategy = Strategy(
|
|
135
|
+
name="FedAvg", # any Flower strategy: FedAvg, FedAdam, FedYogi, FedProx, ...
|
|
136
|
+
fraction_fit=1.0,
|
|
137
|
+
min_fit_clients=2,
|
|
138
|
+
min_evaluate_clients=2,
|
|
139
|
+
min_available_clients=2,
|
|
140
|
+
local_epochs=3,
|
|
141
|
+
threshold=0.5,
|
|
142
|
+
features="age,bmi,glucose,blood_pressure", # comma-separated input columns
|
|
143
|
+
target="label",
|
|
144
|
+
val_fraction=0.10,
|
|
145
|
+
test_fraction=0.10,
|
|
146
|
+
savingPath="./checkpoints",
|
|
147
|
+
saveOnRounds=5,
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
server = FederatedServer(
|
|
151
|
+
host="0.0.0.0",
|
|
152
|
+
port=8080,
|
|
153
|
+
num_rounds=10,
|
|
154
|
+
strategy=strategy,
|
|
155
|
+
)
|
|
156
|
+
server.start()
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
### 2. Client (run on each participating site)
|
|
160
|
+
|
|
161
|
+
```python
|
|
162
|
+
from MEDfl.rw.client import FlowerClient, DPConfig
|
|
163
|
+
|
|
164
|
+
client = FlowerClient(
|
|
165
|
+
server_address="SERVER_IP:8080",
|
|
166
|
+
data_path="data/site_data.csv",
|
|
167
|
+
dp_config=DPConfig( # optional — omit to disable differential privacy
|
|
168
|
+
noise_multiplier=1.0,
|
|
169
|
+
max_grad_norm=1.0,
|
|
170
|
+
batch_size=32,
|
|
171
|
+
),
|
|
172
|
+
)
|
|
173
|
+
client.start()
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
### Per-client data splits
|
|
177
|
+
|
|
178
|
+
By default every client uses the global `val_fraction` / `test_fraction`. With `split_mode="per_client"`, each client (identified by its hostname, or by the `MEDFL_AGENT_ID` environment variable when set) can have its own fractions or a fixed list of test IDs:
|
|
179
|
+
|
|
180
|
+
```python
|
|
181
|
+
strategy = Strategy(
|
|
182
|
+
...,
|
|
183
|
+
split_mode="per_client",
|
|
184
|
+
id_col="patient_id",
|
|
185
|
+
client_fractions={
|
|
186
|
+
"hospital-a": {"val_fraction": 0.15, "test_fraction": 0.20},
|
|
187
|
+
"hospital-b": {"test_ids": "1042,1043,1077"},
|
|
188
|
+
},
|
|
189
|
+
)
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
> 💡 **Networking tip:** for deployments across institutions, a mesh VPN such as [Tailscale](https://tailscale.com) is a simple way to put the server and clients on the same secure private network. TLS certificates can also be passed to `FederatedServer(certificates=...)`.
|
|
193
|
+
|
|
194
|
+
---
|
|
195
|
+
|
|
196
|
+
## Federated XGBoost
|
|
197
|
+
|
|
198
|
+
MEDfl supports **bagging-based federated XGBoost** (`FedXgbBagging`): each client boosts locally from the current global model, and the server combines the resulting trees.
|
|
199
|
+
|
|
200
|
+
**Server**
|
|
201
|
+
|
|
202
|
+
```python
|
|
203
|
+
from MEDfl.rw.server import FederatedServer
|
|
204
|
+
from MEDfl.rw.xgboost import XGBoostStrategy
|
|
205
|
+
|
|
206
|
+
strategy = XGBoostStrategy(
|
|
207
|
+
task="binary", # "binary", "multiclass" or "regression"
|
|
208
|
+
xgb_params={"max_depth": 6, "eta": 0.1, "tree_method": "hist"},
|
|
209
|
+
local_num_boost_round=10,
|
|
210
|
+
features="age,bmi,glucose,blood_pressure",
|
|
211
|
+
target="label",
|
|
212
|
+
min_fit_clients=2,
|
|
213
|
+
min_available_clients=2,
|
|
214
|
+
savingPath="./checkpoints", # models saved as .ubj
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
FederatedServer(host="0.0.0.0", port=8080, num_rounds=10, strategy=strategy).start()
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
**Client**
|
|
221
|
+
|
|
222
|
+
```python
|
|
223
|
+
from MEDfl.rw.xgboost import XGBoostFlowerClient
|
|
224
|
+
|
|
225
|
+
XGBoostFlowerClient(
|
|
226
|
+
server_address="SERVER_IP:8080",
|
|
227
|
+
data_path="data/site_data.csv",
|
|
228
|
+
).start()
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
Sensible defaults (objective, evaluation metric, `hist` tree method) are chosen per task; any value in `xgb_params` overrides them. For multiclass, set `num_classes`.
|
|
232
|
+
|
|
233
|
+
In simulation mode, the equivalent components are `XGBoostSimulationStrategy`, `XGBoostSimulationServer` and `XGBoostSimulationClient` in `MEDfl.LearningManager.xgboost`.
|
|
234
|
+
|
|
235
|
+
---
|
|
236
|
+
|
|
237
|
+
## Federated Explainability (SHAP)
|
|
238
|
+
|
|
239
|
+
After the final round, MEDfl can compute **global feature importance without sharing raw SHAP values**. Each client explains the final global model on its own data and returns only aggregate statistics (sums, squared sums, sign counts); the server combines them into federated mean |SHAP|, mean signed SHAP and dispersion per feature.
|
|
240
|
+
|
|
241
|
+
```python
|
|
242
|
+
from MEDfl.LearningManager.shap import SHAPConfig
|
|
243
|
+
|
|
244
|
+
shap_config = SHAPConfig(
|
|
245
|
+
enabled=True,
|
|
246
|
+
explainer="gradient", # "gradient" or "deep" for neural networks, "tree" for XGBoost
|
|
247
|
+
data_split="validation", # "train", "validation" or "test"
|
|
248
|
+
background_size=100,
|
|
249
|
+
explanation_size=500,
|
|
250
|
+
minimum_samples=10, # clients with fewer samples are skipped
|
|
251
|
+
model_output="raw", # XGBoost only: "raw" (log-odds) or "probability"
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
server = FederatedServer(..., strategy=strategy, shap_config=shap_config)
|
|
255
|
+
server.start()
|
|
256
|
+
|
|
257
|
+
print(server.federated_shap_result) # aggregated global importance
|
|
258
|
+
print(server.local_shap_results) # optional per-client summaries
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
| Backend | Supported explainers | Supported tasks |
|
|
262
|
+
| --- | --- | --- |
|
|
263
|
+
| PyTorch | `gradient`, `deep` | binary classification and other single-output models |
|
|
264
|
+
| XGBoost | `tree` | binary classification, regression |
|
|
265
|
+
|
|
266
|
+
The same `SHAPConfig` can be passed to the simulation-mode `FlowerServer` and `XGBoostSimulationServer`.
|
|
267
|
+
|
|
268
|
+
---
|
|
269
|
+
|
|
270
|
+
## Federated Holdout Testing & Threshold Optimization
|
|
271
|
+
|
|
272
|
+
Clinical models need an **unbiased final evaluation** on data never used for training. With a federated holdout test, each client keeps a private holdout CSV; after the last round the final global model is evaluated on it, and clients return only:
|
|
273
|
+
|
|
274
|
+
- the confusion matrix at the decision threshold,
|
|
275
|
+
- their local metrics, and
|
|
276
|
+
- two histograms of predicted probabilities (positives / negatives).
|
|
277
|
+
|
|
278
|
+
The server sums confusion matrices to obtain **exact pooled** sensitivity, specificity, PPV, NPV, F1 and accuracy, and sums histograms to rebuild a **pooled ROC curve and AUC** (exact up to the histogram bin width).
|
|
279
|
+
|
|
280
|
+
```python
|
|
281
|
+
from MEDfl.rw.holdout import HoldoutConfig
|
|
282
|
+
|
|
283
|
+
holdout_config = HoldoutConfig(
|
|
284
|
+
enabled=True,
|
|
285
|
+
threshold=0.5, # used when threshold_source="manual"
|
|
286
|
+
num_bins=100, # ROC resolution
|
|
287
|
+
minimum_samples=10,
|
|
288
|
+
threshold_source="optimized", # "manual" or "optimized"
|
|
289
|
+
threshold_criterion="youden", # "youden" or "target_sensitivity"
|
|
290
|
+
target_sensitivity=0.9, # used with "target_sensitivity"
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
server = FederatedServer(..., strategy=strategy, holdout_config=holdout_config)
|
|
294
|
+
server.start()
|
|
295
|
+
print(server.federated_holdout_result)
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
On each client, point to the holdout file:
|
|
299
|
+
|
|
300
|
+
```python
|
|
301
|
+
FlowerClient(server_address="SERVER_IP:8080",
|
|
302
|
+
data_path="data/site_data.csv",
|
|
303
|
+
holdout_path="data/site_holdout.csv").start()
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
**Optimized threshold.** With `threshold_source="optimized"`, clients also send score histograms of their whole learning set (train + validation + test). The server selects the threshold on these pooled histograms (Youden's J or the lowest threshold reaching a target sensitivity), then reports holdout metrics at that threshold. The holdout data is **never** used to choose the threshold, so holdout results remain an unbiased estimate.
|
|
307
|
+
|
|
308
|
+
Holdout testing works for both the PyTorch and the XGBoost real-world backends (binary classification).
|
|
309
|
+
|
|
310
|
+
---
|
|
311
|
+
|
|
312
|
+
## Simulation Mode
|
|
313
|
+
|
|
314
|
+
Simulation mode is designed for research and benchmarking. Networks, hospital nodes, datasets, FL setups, pipelines and results are persisted in a database, making experiments reproducible and comparable.
|
|
315
|
+
|
|
316
|
+
```python
|
|
317
|
+
import torch.nn as nn
|
|
318
|
+
import torch.optim as optim
|
|
319
|
+
|
|
320
|
+
from MEDfl.LearningManager.utils import set_db_config
|
|
321
|
+
from MEDfl.NetManager.database_connector import DatabaseManager
|
|
322
|
+
from MEDfl.NetManager.network import Network
|
|
323
|
+
from MEDfl.NetManager.node import Node
|
|
324
|
+
from MEDfl.NetManager.flsetup import FLsetup
|
|
325
|
+
from MEDfl.LearningManager.dynamicModal import DynamicModel
|
|
326
|
+
from MEDfl.LearningManager.model import Model
|
|
327
|
+
from MEDfl.LearningManager.strategy import Strategy
|
|
328
|
+
from MEDfl.LearningManager.server import FlowerServer
|
|
329
|
+
from MEDfl.LearningManager.flpipeline import FLpipeline
|
|
330
|
+
|
|
331
|
+
# 1. Database
|
|
332
|
+
set_db_config("./medfl_database.db")
|
|
333
|
+
db = DatabaseManager()
|
|
334
|
+
db.connect()
|
|
335
|
+
db.create_MEDfl_db(path_to_csv="data/master_dataset.csv")
|
|
336
|
+
|
|
337
|
+
# 2. Network, setup and nodes
|
|
338
|
+
net = Network("Net1")
|
|
339
|
+
net.create_network()
|
|
340
|
+
net.create_master_dataset("data/master_dataset.csv")
|
|
341
|
+
|
|
342
|
+
fl_setup = FLsetup(name="setup_1", description="Diabetes study", network=net)
|
|
343
|
+
fl_setup.create()
|
|
344
|
+
|
|
345
|
+
for name, path, train in [("hospital_1", "data/h1.csv", 1),
|
|
346
|
+
("hospital_2", "data/h2.csv", 1),
|
|
347
|
+
("hospital_3", "data/h3.csv", 0)]: # train=0 → test-only node
|
|
348
|
+
node = Node(name=name, train=train)
|
|
349
|
+
net.add_node(node)
|
|
350
|
+
node.upload_dataset(name, path)
|
|
351
|
+
|
|
352
|
+
fl_dataset = fl_setup.create_federated_dataset(output="diabetes", fit_encode=[], to_drop=["diabetes"])
|
|
353
|
+
|
|
354
|
+
# 3. Model and strategy
|
|
355
|
+
torch_model = DynamicModel().create_model(
|
|
356
|
+
model_type="Binary Classifier",
|
|
357
|
+
params_dict={"input_dim": 8, "output_dim": 1, "hidden_dims": [16, 32]},
|
|
358
|
+
)
|
|
359
|
+
global_model = Model(torch_model, optim.SGD(torch_model.parameters(), lr=1e-3), nn.BCELoss())
|
|
360
|
+
|
|
361
|
+
strategy = Strategy("FedAdam", min_fit_clients=2, min_evaluate_clients=2, min_available_clients=2,
|
|
362
|
+
initial_parameters=global_model.get_parameters())
|
|
363
|
+
strategy.create_strategy()
|
|
364
|
+
|
|
365
|
+
# 4. Train and evaluate
|
|
366
|
+
server = FlowerServer(global_model, strategy=strategy, num_rounds=10,
|
|
367
|
+
num_clients=len(fl_dataset.trainloaders), fed_dataset=fl_dataset,
|
|
368
|
+
diff_privacy=False)
|
|
369
|
+
pipeline = FLpipeline(name="pipeline_1", description="First FL pipeline", server=server)
|
|
370
|
+
history = pipeline.server.run()
|
|
371
|
+
|
|
372
|
+
results = pipeline.auto_test() # per-node metrics, stored in the database
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
Results can be visualized with `MEDfl.LearningManager.plot.AccuracyLossPlotter`, and hyperparameters tuned with `MEDfl.LearningManager.params_optimiser.ParamsOptimiser` (grid search or Optuna).
|
|
376
|
+
|
|
377
|
+
Step-by-step notebooks are available in [notebooks/tutorial/](notebooks/tutorial/) (database, NetManager, transfer learning, LearningManager, results, model choice, hyperparameter optimization).
|
|
378
|
+
|
|
379
|
+
---
|
|
380
|
+
|
|
381
|
+
## Package Structure
|
|
382
|
+
|
|
383
|
+
```
|
|
384
|
+
MEDfl/
|
|
385
|
+
├── NetManager/ # Simulation: networks, nodes, datasets, FL setups, DB access
|
|
386
|
+
├── LearningManager/ # Simulation: models, strategies, server/client, pipelines, plots, HPO
|
|
387
|
+
│ ├── xgboost/ # federated XGBoost (simulation)
|
|
388
|
+
│ └── shap/ # SHAP config, local explainers, federated aggregation
|
|
389
|
+
├── rw/ # Real-world deployment
|
|
390
|
+
│ ├── server.py # FederatedServer
|
|
391
|
+
│ ├── client.py # FlowerClient + DPConfig (PyTorch)
|
|
392
|
+
│ ├── strategy.py # Strategy wrapper (config push, logging, checkpointing)
|
|
393
|
+
│ ├── model.py # Configurable MLP (Net)
|
|
394
|
+
│ ├── holdout.py # Federated holdout test & threshold optimization
|
|
395
|
+
│ └── xgboost/ # XGBoostStrategy, XGBoostFlowerClient, XGBoostConfig
|
|
396
|
+
└── scripts/ # Database creation utilities
|
|
397
|
+
```
|
|
398
|
+
|
|
399
|
+
---
|
|
400
|
+
|
|
401
|
+
## Documentation
|
|
402
|
+
|
|
403
|
+
Full documentation, including API reference and complete simulation and real-world tutorials, is built with **Sphinx** from [docs/](docs/). To build and browse it locally:
|
|
404
|
+
|
|
405
|
+
```bash
|
|
406
|
+
cd docs
|
|
407
|
+
make clean && make html
|
|
408
|
+
python -m http.server --directory _build/html
|
|
409
|
+
```
|
|
410
|
+
|
|
411
|
+
---
|
|
412
|
+
|
|
413
|
+
## Testing
|
|
414
|
+
|
|
415
|
+
```bash
|
|
416
|
+
pip install pytest
|
|
417
|
+
pytest tests/
|
|
418
|
+
```
|
|
419
|
+
|
|
420
|
+
---
|
|
421
|
+
|
|
422
|
+
## Contributing
|
|
423
|
+
|
|
424
|
+
Contributions of all kinds are welcome — bug reports, new features, documentation and tutorials.
|
|
425
|
+
|
|
426
|
+
1. Fork the repository and create a feature branch from `main`.
|
|
427
|
+
2. Add tests for your changes and make sure `pytest` passes.
|
|
428
|
+
3. Format your code with `black` and check it with `flake8`.
|
|
429
|
+
4. Open a Pull Request describing the motivation and the changes.
|
|
430
|
+
|
|
431
|
+
Please use [GitHub Issues](https://github.com/MEDomics-UdeS/MEDfl/issues) to report bugs or request features.
|
|
432
|
+
|
|
433
|
+
---
|
|
434
|
+
|
|
435
|
+
## Acknowledgment
|
|
436
|
+
|
|
437
|
+
MEDfl is part of the **MEDomicsLab** initiative at the **Université de Sherbrooke**. It was developed to enable **secure, privacy-preserving and reproducible** machine learning across distributed medical datasets.
|
|
438
|
+
|
|
439
|
+
---
|
|
440
|
+
|
|
441
|
+
## Authors
|
|
442
|
+
|
|
443
|
+
- [Ouael Nedjem Eddine Sahbi](https://github.com/ouaelesi) — Master's Research Student, Université de Sherbrooke
|
|
444
|
+
- [Haithem Lamri](https://github.com/HaithemLamri) — Research Intern
|
|
445
|
+
- [MEDomics-UdeS](https://www.medomics-udes.org/en/)
|
|
446
|
+
|
|
447
|
+
---
|
|
448
|
+
|
|
449
|
+
## License
|
|
450
|
+
|
|
451
|
+
MEDfl is distributed under the **GNU General Public License v3.0**. See [LICENSE](LICENSE) for details.
|
|
452
|
+
|
|
453
|
+
<div align="center">
|
|
454
|
+
|
|
455
|
+
⭐ If MEDfl is useful to your work, please consider starring the repository to support its development.
|
|
456
|
+
|
|
457
|
+
</div>
|