forked from NVIDIA/NVFlare
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fed Statistics: Adding Percentiles support (NVIDIA#3124)
* 1. Add percentile support using t-digest 2. Add examples for df_stats 3. refactoring the some of the codebase 4. missing work 1. add DP noise 2. make writing filer easier for end-user 3. add job API for the stats. Job 4. make it even easier to work on stats. 5. unit tests * 1. Add percentile support using t-digest 2. Add examples for df_stats 3. refactoring the some of the codebase 4. missing work 1. add DP noise 2. make writing filer easier for end-user 3. add job API for the stats. Job 4. make it even easier to work on stats. 5. unit tests * add unit tests add job api in example format style * add tdigest license file * remove debugging print * fix test * format style changes * format style changes
- Loading branch information
1 parent
6d9d775
commit 62e2441
Showing
29 changed files
with
819 additions
and
143 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
https://github.com/CamDavidsonPilon/tdigest/blob/master/LICENSE.txt | ||
|
||
The MIT License (MIT) | ||
|
||
Copyright (c) 2015 Cameron Davidson-Pilon | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
75 changes: 75 additions & 0 deletions
75
examples/advanced/federated-statistics/df_stats/job_api/df_statistics.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
from typing import Dict, Optional | ||
|
||
import pandas as pd | ||
|
||
from nvflare.apis.fl_context import FLContext | ||
from nvflare.app_opt.statistics.df.df_core_statistics import DFStatisticsCore | ||
|
||
|
||
class DFStatistics(DFStatisticsCore): | ||
def __init__(self, data_path): | ||
super().__init__() | ||
self.data_root_dir = "/tmp/nvflare/df_stats/data" | ||
self.data_path = data_path | ||
self.data: Optional[Dict[str, pd.DataFrame]] = None | ||
self.data_features = [ | ||
"Age", | ||
"Workclass", | ||
"fnlwgt", | ||
"Education", | ||
"Education-Num", | ||
"Marital Status", | ||
"Occupation", | ||
"Relationship", | ||
"Race", | ||
"Sex", | ||
"Capital Gain", | ||
"Capital Loss", | ||
"Hours per week", | ||
"Country", | ||
"Target", | ||
] | ||
|
||
# the original dataset has no header, | ||
# we will use the adult.train dataset for site-1, the adult.test dataset for site-2 | ||
# the adult.test dataset has incorrect formatted row at 1st line, we will skip it. | ||
self.skip_rows = { | ||
"site-1": [], | ||
"site-2": [0], | ||
} | ||
|
||
def load_data(self, fl_ctx: FLContext) -> Dict[str, pd.DataFrame]: | ||
client_name = fl_ctx.get_identity_name() | ||
self.log_info(fl_ctx, f"load data for client {client_name}") | ||
try: | ||
skip_rows = self.skip_rows[client_name] | ||
data_path = f"{self.data_root_dir}/{fl_ctx.get_identity_name()}/{self.data_path}" | ||
# example of load data from CSV | ||
df: pd.DataFrame = pd.read_csv( | ||
data_path, names=self.data_features, sep=r"\s*,\s*", skiprows=skip_rows, engine="python", na_values="?" | ||
) | ||
train = df.sample(frac=0.8, random_state=200) # random state is a seed value | ||
test = df.drop(train.index).sample(frac=1.0) | ||
|
||
self.log_info(fl_ctx, f"load data done for client {client_name}") | ||
return {"train": train, "test": test} | ||
|
||
except Exception as e: | ||
raise Exception(f"Load data for client {client_name} failed! {e}") | ||
|
||
def initialize(self, fl_ctx: FLContext): | ||
self.data = self.load_data(fl_ctx) |
72 changes: 72 additions & 0 deletions
72
examples/advanced/federated-statistics/df_stats/job_api/df_stats_job.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
import argparse | ||
|
||
from df_statistics import DFStatistics | ||
|
||
from nvflare.job_config.stats_job import StatsJob | ||
|
||
|
||
def define_parser(): | ||
parser = argparse.ArgumentParser() | ||
parser.add_argument("-n", "--n_clients", type=int, default=3) | ||
parser.add_argument("-d", "--data_root_dir", type=str, nargs="?", default="/tmp/nvflare/dataset/output") | ||
parser.add_argument("-o", "--stats_output_path", type=str, nargs="?", default="statistics/stats.json") | ||
parser.add_argument("-j", "--job_dir", type=str, nargs="?", default="/tmp/nvflare/jobs/stats_df") | ||
parser.add_argument("-w", "--work_dir", type=str, nargs="?", default="/tmp/nvflare/jobs/stats_df/work_dir") | ||
parser.add_argument("-co", "--export_config", action="store_true", help="config only mode, export config") | ||
|
||
return parser.parse_args() | ||
|
||
|
||
def main(): | ||
args = define_parser() | ||
|
||
n_clients = args.n_clients | ||
data_root_dir = args.data_root_dir | ||
output_path = args.stats_output_path | ||
job_dir = args.job_dir | ||
work_dir = args.work_dir | ||
export_config = args.export_config | ||
|
||
statistic_configs = { | ||
"count": {}, | ||
"mean": {}, | ||
"sum": {}, | ||
"stddev": {}, | ||
"histogram": {"*": {"bins": 20}}, | ||
"Age": {"bins": 20, "range": [0, 10]}, | ||
"percentile": {"*": [25, 50, 75], "Age": [50, 95]}, | ||
} | ||
# define local stats generator | ||
df_stats_generator = DFStatistics(data_root_dir=data_root_dir) | ||
|
||
job = StatsJob( | ||
job_name="stats_df", | ||
statistic_configs=statistic_configs, | ||
stats_generator=df_stats_generator, | ||
output_path=output_path, | ||
) | ||
|
||
sites = [f"site-{i + 1}" for i in range(n_clients)] | ||
job.setup_clients(sites) | ||
|
||
if export_config: | ||
job.export_job(job_dir) | ||
else: | ||
job.simulator_run(work_dir) | ||
|
||
|
||
if __name__ == "__main__": | ||
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.