python_code
stringlengths 0
679k
| repo_name
stringlengths 9
41
| file_path
stringlengths 6
149
|
---|---|---|
# Copyright (c) 2022, 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.
| NVFlare-main | nvflare/private/fed/simulator/__init__.py |
# Copyright (c) 2022, 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.
class SimulatorConstants:
JOB_NAME = "simulate_job"
CLIENT = "client"
CLIENT_CONFIG = "client_config"
DEPLOY_ARGS = "deploy_args"
BUILD_CTX = "build_ctx"
| NVFlare-main | nvflare/private/fed/simulator/simulator_const.py |
# Copyright (c) 2022, 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 nvflare.apis.fl_constant import FLContextKey, RunProcessKey
from nvflare.private.fed.client.client_engine import ClientEngine
from nvflare.private.fed.client.client_status import ClientStatus
from nvflare.private.fed.simulator.simulator_const import SimulatorConstants
class SimulatorParentClientEngine(ClientEngine):
def __init__(self, client, client_token, args, rank=0):
super().__init__(client, client_token, args, rank)
fl_ctx = self.new_context()
fl_ctx.set_prop(FLContextKey.SIMULATE_MODE, True, private=True, sticky=True)
self.client_executor.run_processes[SimulatorConstants.JOB_NAME] = {
RunProcessKey.LISTEN_PORT: None,
RunProcessKey.CONNECTION: None,
RunProcessKey.CHILD_PROCESS: None,
RunProcessKey.STATUS: ClientStatus.STARTED,
}
def get_all_job_ids(self):
jobs = []
for job in self.client_executor.run_processes.keys():
jobs.append(job)
return jobs
def abort_app(self, job_id: str) -> str:
return self.client_executor.run_processes.pop(job_id)
| NVFlare-main | nvflare/private/fed/simulator/simulator_client_engine.py |
# Copyright (c) 2022, 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 nvflare.apis.fl_constant import FLContextKey
from nvflare.private.fed.client.client_app_runner import ClientAppRunner
from nvflare.private.fed.client.client_run_manager import ClientRunManager
from nvflare.private.fed.server.server_app_runner import ServerAppRunner
class SimulatorClientRunManager(ClientRunManager):
def create_job_processing_context_properties(self, workspace, job_id):
return {}
class SimulatorClientAppRunner(ClientAppRunner):
def create_run_manager(self, args, conf, federated_client, workspace):
run_manager = SimulatorClientRunManager(
client_name=args.client_name,
job_id=args.job_id,
workspace=workspace,
client=federated_client,
components=conf.runner_config.components,
handlers=conf.runner_config.handlers,
conf=conf,
)
with run_manager.new_context() as fl_ctx:
fl_ctx.set_prop(FLContextKey.SIMULATE_MODE, True, private=True, sticky=True)
return run_manager
class SimulatorServerAppRunner(ServerAppRunner):
def __init__(self, server) -> None:
super().__init__(server)
def sync_up_parents_process(self, args):
pass
def update_job_run_status(self):
pass
| NVFlare-main | nvflare/private/fed/simulator/simulator_app_runner.py |
# Copyright (c) 2021, 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 logging
import os
import re
import shutil
import sys
import threading
from nvflare.apis.event_type import EventType
from nvflare.apis.fl_component import FLComponent
from nvflare.apis.fl_constant import MachineStatus, SystemComponents, WorkspaceConstants
from nvflare.apis.fl_context import FLContext, FLContextManager
from nvflare.apis.workspace import Workspace
from nvflare.fuel.utils.network_utils import get_open_ports
from nvflare.private.defs import ERROR_MSG_PREFIX, ClientStatusKey, EngineConstant
from nvflare.private.event import fire_event
from nvflare.private.fed.server.job_meta_validator import JobMetaValidator
from nvflare.private.fed.utils.app_deployer import AppDeployer
from nvflare.private.fed.utils.fed_utils import security_close
from nvflare.security.logging import secure_format_exception, secure_log_traceback
from .client_engine_internal_spec import ClientEngineInternalSpec
from .client_executor import ProcessExecutor
from .client_run_manager import ClientRunInfo
from .client_status import ClientStatus
def _remove_custom_path():
regex = re.compile(".*/run_.*/custom")
custom_paths = list(filter(regex.search, sys.path))
for path in custom_paths:
sys.path.remove(path)
class ClientEngine(ClientEngineInternalSpec):
"""ClientEngine runs in the client parent process."""
def __init__(self, client, client_name, args, rank, workers=5):
"""To init the ClientEngine.
Args:
client: FL client object
client_name: client name
args: command args
rank: local process rank
workers: number of workers
"""
super().__init__()
self.client = client
self.client_name = client_name
self.args = args
self.rank = rank
self.client_executor = ProcessExecutor(client, os.path.join(args.workspace, "startup"))
self.admin_agent = None
self.fl_ctx_mgr = FLContextManager(
engine=self,
identity_name=client_name,
job_id="",
public_stickers={},
private_stickers={
SystemComponents.DEFAULT_APP_DEPLOYER: AppDeployer(),
SystemComponents.JOB_META_VALIDATOR: JobMetaValidator(),
},
)
self.status = MachineStatus.STOPPED
if workers < 1:
raise ValueError("workers must >= 1")
self.logger = logging.getLogger(self.__class__.__name__)
self.fl_components = [x for x in self.client.components.values() if isinstance(x, FLComponent)]
def fire_event(self, event_type: str, fl_ctx: FLContext):
fire_event(event=event_type, handlers=self.fl_components, ctx=fl_ctx)
def set_agent(self, admin_agent):
self.admin_agent = admin_agent
def new_context(self) -> FLContext:
return self.fl_ctx_mgr.new_context()
def get_component(self, component_id: str) -> object:
return self.client.components.get(component_id)
def get_engine_status(self):
running_jobs = []
for job_id in self.get_all_job_ids():
run_folder = os.path.join(self.args.workspace, WorkspaceConstants.WORKSPACE_PREFIX + str(job_id))
app_name = ""
app_file = os.path.join(run_folder, "fl_app.txt")
if os.path.exists(app_file):
with open(app_file, "r") as f:
app_name = f.readline().strip()
job = {
ClientStatusKey.APP_NAME: app_name,
ClientStatusKey.JOB_ID: job_id,
ClientStatusKey.STATUS: self.client_executor.check_status(job_id),
}
running_jobs.append(job)
result = {
ClientStatusKey.CLIENT_NAME: self.client.client_name,
ClientStatusKey.RUNNING_JOBS: running_jobs,
}
return result
def start_app(
self,
job_id: str,
allocated_resource: dict = None,
token: str = None,
resource_manager=None,
) -> str:
status = self.client_executor.get_status(job_id)
if status == ClientStatus.STARTED:
return "Client app already started."
app_root = os.path.join(
self.args.workspace,
WorkspaceConstants.WORKSPACE_PREFIX + str(job_id),
WorkspaceConstants.APP_PREFIX + self.client.client_name,
)
if not os.path.exists(app_root):
return f"{ERROR_MSG_PREFIX}: Client app does not exist. Please deploy it before starting client."
app_custom_folder = os.path.join(app_root, "custom")
if os.path.isdir(app_custom_folder):
try:
sys.path.index(app_custom_folder)
except ValueError:
_remove_custom_path()
sys.path.append(app_custom_folder)
self.logger.info("Starting client app. rank: {}".format(self.rank))
open_port = get_open_ports(1)[0]
self.client_executor.start_app(
self.client,
job_id,
self.args,
app_custom_folder,
open_port,
allocated_resource,
token,
resource_manager,
list(self.client.servers.values())[0]["target"],
)
return "Start the client app..."
def get_client_name(self):
return self.client.client_name
def _write_token_file(self, job_id, open_port):
token_file = os.path.join(self.args.workspace, EngineConstant.CLIENT_TOKEN_FILE)
if os.path.exists(token_file):
os.remove(token_file)
with open(token_file, "wt") as f:
f.write(
"%s\n%s\n%s\n%s\n%s\n%s\n"
% (
self.client.token,
self.client.ssid,
job_id,
self.client.client_name,
open_port,
list(self.client.servers.values())[0]["target"],
)
)
def abort_app(self, job_id: str) -> str:
status = self.client_executor.get_status(job_id)
if status == ClientStatus.STOPPED:
return "Client app already stopped."
if status == ClientStatus.NOT_STARTED:
return "Client app has not started."
if status == ClientStatus.STARTING:
return "Client app is starting, please wait for client to have started before abort."
self.client_executor.abort_app(job_id)
return "Abort signal has been sent to the client App."
def abort_task(self, job_id: str) -> str:
status = self.client_executor.get_status(job_id)
if status == ClientStatus.NOT_STARTED:
return "Client app has not started."
if status == ClientStatus.STARTING:
return "Client app is starting, please wait for started before abort_task."
self.client_executor.abort_task(job_id)
return "Abort signal has been sent to the current task."
def shutdown(self) -> str:
self.logger.info("Client shutdown...")
touch_file = os.path.join(self.args.workspace, "shutdown.fl")
self.fire_event(EventType.SYSTEM_END, self.new_context())
thread = threading.Thread(target=shutdown_client, args=(self.client, touch_file))
thread.start()
return "Shutdown the client..."
def restart(self) -> str:
self.logger.info("Client shutdown...")
touch_file = os.path.join(self.args.workspace, "restart.fl")
self.fire_event(EventType.SYSTEM_END, self.new_context())
thread = threading.Thread(target=shutdown_client, args=(self.client, touch_file))
thread.start()
return "Restart the client..."
def deploy_app(self, app_name: str, job_id: str, job_meta: dict, client_name: str, app_data) -> str:
workspace = Workspace(root_dir=self.args.workspace, site_name=client_name)
app_deployer = self.get_component(SystemComponents.APP_DEPLOYER)
if not app_deployer:
# use default deployer
app_deployer = AppDeployer()
err = app_deployer.deploy(
workspace=workspace,
job_id=job_id,
job_meta=job_meta,
app_name=app_name,
app_data=app_data,
fl_ctx=self.new_context(),
)
if err:
return f"{ERROR_MSG_PREFIX}: {err}"
return ""
def delete_run(self, job_id: str) -> str:
job_id_folder = os.path.join(self.args.workspace, WorkspaceConstants.WORKSPACE_PREFIX + str(job_id))
if os.path.exists(job_id_folder):
shutil.rmtree(job_id_folder)
return f"Delete run folder: {job_id_folder}."
def get_current_run_info(self, job_id) -> ClientRunInfo:
return self.client_executor.get_run_info(job_id)
def get_errors(self, job_id):
return self.client_executor.get_errors(job_id)
def reset_errors(self, job_id):
self.client_executor.reset_errors(job_id)
def get_all_job_ids(self):
return self.client_executor.get_run_processes_keys()
def shutdown_client(federated_client, touch_file):
with open(touch_file, "a"):
os.utime(touch_file, None)
try:
print("About to shutdown the client...")
federated_client.communicator.heartbeat_done = True
# time.sleep(3)
federated_client.close()
federated_client.status = ClientStatus.STOPPED
# federated_client.cell.stop()
security_close()
except Exception as e:
secure_log_traceback()
print(f"Failed to shutdown client: {secure_format_exception(e)}")
| NVFlare-main | nvflare/private/fed/client/client_engine.py |
# Copyright (c) 2021, 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 json
import os
from typing import List
from nvflare.apis.job_def import JobMetaKey
from nvflare.apis.workspace import Workspace
from nvflare.fuel.hci.proto import MetaStatusValue, make_meta
from nvflare.fuel.utils.argument_utils import parse_vars
from nvflare.lighter.utils import verify_folder_signature
from nvflare.private.admin_defs import Message, error_reply, ok_reply
from nvflare.private.defs import RequestHeader, ScopeInfoKey, TrainingTopic
from nvflare.private.fed.client.admin import RequestProcessor
from nvflare.private.fed.client.client_engine_internal_spec import ClientEngineInternalSpec
from nvflare.private.fed.utils.fed_utils import get_scope_info
class StartAppProcessor(RequestProcessor):
def get_topics(self) -> List[str]:
return [TrainingTopic.START]
def process(self, req: Message, app_ctx) -> Message:
engine = app_ctx
if not isinstance(engine, ClientEngineInternalSpec):
raise TypeError("engine must be ClientEngineInternalSpec, but got {}".format(type(engine)))
job_id = req.get_header(RequestHeader.JOB_ID)
result = engine.start_app(job_id)
if not result:
result = "OK"
return ok_reply(topic=f"reply_{req.topic}", body=result)
class AbortAppProcessor(RequestProcessor):
def get_topics(self) -> List[str]:
return [TrainingTopic.ABORT]
def process(self, req: Message, app_ctx) -> Message:
engine = app_ctx
if not isinstance(engine, ClientEngineInternalSpec):
raise TypeError("engine must be ClientEngineInternalSpec, but got {}".format(type(engine)))
job_id = req.get_header(RequestHeader.JOB_ID)
result = engine.abort_app(job_id)
if not result:
result = "OK"
return ok_reply(topic=f"reply_{req.topic}", body=result)
class AbortTaskProcessor(RequestProcessor):
def get_topics(self) -> List[str]:
return [TrainingTopic.ABORT_TASK]
def process(self, req: Message, app_ctx) -> Message:
engine = app_ctx
if not isinstance(engine, ClientEngineInternalSpec):
raise TypeError("engine must be ClientEngineInternalSpec, but got {}".format(type(engine)))
job_id = req.get_header(RequestHeader.JOB_ID)
result = engine.abort_task(job_id)
if not result:
result = "OK"
return ok_reply(topic=f"reply_{req.topic}", body=result, meta=make_meta(MetaStatusValue.OK, result))
class ShutdownClientProcessor(RequestProcessor):
def get_topics(self) -> List[str]:
return [TrainingTopic.SHUTDOWN]
def process(self, req: Message, app_ctx) -> Message:
engine = app_ctx
if not isinstance(engine, ClientEngineInternalSpec):
raise TypeError("engine must be ClientEngineInternalSpec, but got {}".format(type(engine)))
result = engine.shutdown()
if not result:
result = "OK"
return ok_reply(topic=f"reply_{req.topic}", body=result)
class RestartClientProcessor(RequestProcessor):
def get_topics(self) -> List[str]:
return [TrainingTopic.RESTART]
def process(self, req: Message, app_ctx) -> Message:
engine = app_ctx
if not isinstance(engine, ClientEngineInternalSpec):
raise TypeError("engine must be ClientEngineInternalSpec, but got {}".format(type(engine)))
result = engine.restart()
if not result:
result = "OK"
return ok_reply(topic=f"reply_{req.topic}", body=result)
class DeployProcessor(RequestProcessor):
def get_topics(self) -> List[str]:
return [TrainingTopic.DEPLOY]
def process(self, req: Message, app_ctx) -> Message:
# Note: this method executes in the Main process of the client
engine = app_ctx
if not isinstance(engine, ClientEngineInternalSpec):
raise TypeError("engine must be ClientEngineInternalSpec, but got {}".format(type(engine)))
job_id = req.get_header(RequestHeader.JOB_ID)
job_meta = json.loads(req.get_header(RequestHeader.JOB_META))
app_name = req.get_header(RequestHeader.APP_NAME)
client_name = engine.get_client_name()
if not job_meta:
return error_reply("missing job meta")
kv_list = parse_vars(engine.args.set)
secure_train = kv_list.get("secure_train", True)
from_hub_site = job_meta.get(JobMetaKey.FROM_HUB_SITE.value)
if secure_train and not from_hub_site:
workspace = Workspace(root_dir=engine.args.workspace, site_name=client_name)
app_path = workspace.get_app_dir(job_id)
root_ca_path = os.path.join(workspace.get_startup_kit_dir(), "rootCA.pem")
if not verify_folder_signature(app_path, root_ca_path):
return error_reply(f"app {app_name} does not pass signature verification")
err = engine.deploy_app(
app_name=app_name, job_id=job_id, job_meta=job_meta, client_name=client_name, app_data=req.body
)
if err:
return error_reply(err)
return ok_reply(body=f"deployed {app_name} to {client_name}")
class DeleteRunNumberProcessor(RequestProcessor):
def get_topics(self) -> List[str]:
return [TrainingTopic.DELETE_RUN]
def process(self, req: Message, app_ctx) -> Message:
engine = app_ctx
if not isinstance(engine, ClientEngineInternalSpec):
raise TypeError("engine must be ClientEngineInternalSpec, but got {}".format(type(engine)))
job_id = req.get_header(RequestHeader.JOB_ID)
result = engine.delete_run(job_id)
if not result:
result = "OK"
return ok_reply(topic=f"reply_{req.topic}", body=result)
class ClientStatusProcessor(RequestProcessor):
def get_topics(self) -> List[str]:
return [TrainingTopic.CHECK_STATUS]
def process(self, req: Message, app_ctx) -> Message:
engine = app_ctx
if not isinstance(engine, ClientEngineInternalSpec):
raise TypeError("engine must be ClientEngineInternalSpec, but got {}".format(type(engine)))
result = engine.get_engine_status()
result = json.dumps(result)
return ok_reply(topic=f"reply_{req.topic}", body=result)
class ScopeInfoProcessor(RequestProcessor):
def get_topics(self) -> List[str]:
return [TrainingTopic.GET_SCOPES]
def process(self, req: Message, app_ctx) -> Message:
scope_names, default_scope_name = get_scope_info()
result = {ScopeInfoKey.SCOPE_NAMES: scope_names, ScopeInfoKey.DEFAULT_SCOPE: default_scope_name}
result = json.dumps(result)
return ok_reply(topic=f"reply_{req.topic}", body=result)
| NVFlare-main | nvflare/private/fed/client/training_cmds.py |
# Copyright (c) 2021, 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 subprocess
from typing import List
from nvflare.private.admin_defs import Message
from nvflare.private.defs import SysCommandTopic
from nvflare.private.fed.client.admin import RequestProcessor
class ShellCommandProcessor(RequestProcessor):
def get_topics(self) -> List[str]:
return [SysCommandTopic.SHELL]
def process(self, req: Message, app_ctx) -> Message:
shell_cmd = req.body
output = subprocess.getoutput(shell_cmd)
return Message(topic="reply_" + req.topic, body=output)
| NVFlare-main | nvflare/private/fed/client/shell_cmd.py |
# Copyright (c) 2021, 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 json
from nvflare.private.admin_defs import Message
from nvflare.private.defs import InfoCollectorTopic, RequestHeader
from nvflare.private.fed.client.admin import RequestProcessor
from nvflare.private.fed.client.client_engine_internal_spec import ClientEngineInternalSpec
class ClientInfoProcessor(RequestProcessor):
def get_topics(self) -> [str]:
return [
InfoCollectorTopic.SHOW_STATS,
InfoCollectorTopic.SHOW_ERRORS,
InfoCollectorTopic.RESET_ERRORS,
]
def process(self, req: Message, app_ctx) -> Message:
engine = app_ctx
if not isinstance(engine, ClientEngineInternalSpec):
raise TypeError("engine must be ClientEngineInternalSpec, but got {}".format(type(engine)))
job_id = req.get_header(RequestHeader.JOB_ID)
if req.topic == InfoCollectorTopic.SHOW_STATS:
result = engine.get_current_run_info(job_id)
elif req.topic == InfoCollectorTopic.SHOW_ERRORS:
result = engine.get_errors(job_id)
elif req.topic == InfoCollectorTopic.RESET_ERRORS:
engine.reset_errors(job_id)
result = {"status": "OK"}
else:
result = {"error": "invalid topic {}".format(req.topic)}
if not isinstance(result, dict):
result = {}
result = json.dumps(result)
return Message(topic="reply_" + req.topic, body=result)
| NVFlare-main | nvflare/private/fed/client/info_coll_cmd.py |
# Copyright (c) 2021, 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.
class ClientStatus(object):
NOT_STARTED = 0
STARTING = 1
STARTED = 2
STOPPED = 3
EXCEPTION = 4
status_messages = {
NOT_STARTED: "not started",
STARTING: "starting",
STARTED: "started",
STOPPED: "stopped",
EXCEPTION: "exception",
}
def get_status_message(status):
return ClientStatus.status_messages.get(status)
| NVFlare-main | nvflare/private/fed/client/client_status.py |
# Copyright (c) 2021, 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 nvflare.private.admin_defs import Message
from nvflare.private.defs import ComponentCallerTopic, RequestHeader
from nvflare.private.fed.client.admin import RequestProcessor
from nvflare.private.fed.client.client_engine_internal_spec import ClientEngineInternalSpec
from nvflare.widgets.comp_caller import ComponentCaller
from nvflare.widgets.widget import WidgetID
class ComponentCallerProcessor(RequestProcessor):
def get_topics(self) -> [str]:
return [ComponentCallerTopic.CALL_COMPONENT]
def process(self, req: Message, app_ctx) -> Message:
engine = app_ctx
if not isinstance(engine, ClientEngineInternalSpec):
raise TypeError("engine must be ClientEngineInternalSpec, but got {}".format(type(engine)))
caller = engine.get_widget(WidgetID.COMPONENT_CALLER)
if not isinstance(caller, ComponentCaller):
raise TypeError("caller must be ComponentCaller, but got {}".format(type(caller)))
run_info = engine.get_current_run_info()
if not run_info or run_info.job_id < 0:
result = {"error": "app not running"}
else:
comp_target = req.get_header(RequestHeader.COMPONENT_TARGET)
call_name = req.get_header(RequestHeader.CALL_NAME)
call_params = req.body
result = caller.call_components(target=comp_target, call_name=call_name, params=call_params)
if not isinstance(result, dict):
result = {}
return Message(topic=req.topic, body=result)
| NVFlare-main | nvflare/private/fed/client/comp_caller_cmd.py |
# Copyright (c) 2021, 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 copy
import logging
from nvflare.apis.fl_constant import FLContextKey
from nvflare.apis.fl_context import FLContext
from nvflare.apis.utils.fl_context_utils import get_serializable_data
from nvflare.fuel.f3.cellnet.core_cell import Message as CellMessage
from nvflare.fuel.f3.cellnet.core_cell import MessageHeaderKey, ReturnCode
from nvflare.fuel.f3.cellnet.core_cell import make_reply as make_cellnet_reply
from nvflare.private.defs import CellChannel, new_cell_message
from .admin_commands import AdminCommands
class CommandAgent(object):
def __init__(self, federated_client) -> None:
"""To init the CommandAgent.
Args:
federated_client: FL client object
"""
self.federated_client = federated_client
self.thread = None
self.asked_to_stop = False
self.commands = AdminCommands.commands
self.logger = logging.getLogger(self.__class__.__name__)
def start(self, fl_ctx: FLContext):
self.engine = fl_ctx.get_engine()
self.register_cell_cb()
def register_cell_cb(self):
self.federated_client.cell.register_request_cb(
channel=CellChannel.CLIENT_COMMAND,
topic="*",
cb=self.execute_command,
)
self.federated_client.cell.register_request_cb(
channel=CellChannel.AUX_COMMUNICATION,
topic="*",
cb=self.aux_communication,
)
def execute_command(self, request: CellMessage) -> CellMessage:
assert isinstance(request, CellMessage), "request must be CellMessage but got {}".format(type(request))
command_name = request.get_header(MessageHeaderKey.TOPIC)
data = request.payload
command = AdminCommands.get_command(command_name)
if command:
with self.engine.new_context() as new_fl_ctx:
reply = command.process(data=data, fl_ctx=new_fl_ctx)
if reply is not None:
return_message = new_cell_message({}, reply)
return_message.set_header(MessageHeaderKey.RETURN_CODE, ReturnCode.OK)
else:
return_message = new_cell_message({}, None)
return return_message
return make_cellnet_reply(ReturnCode.INVALID_REQUEST, "", None)
def aux_communication(self, request: CellMessage) -> CellMessage:
assert isinstance(request, CellMessage), "request must be CellMessage but got {}".format(type(request))
shareable = request.payload
with self.engine.new_context() as fl_ctx:
topic = request.get_header(MessageHeaderKey.TOPIC)
reply = self.engine.dispatch(topic=topic, request=shareable, fl_ctx=fl_ctx)
shared_fl_ctx = FLContext()
shared_fl_ctx.set_public_props(copy.deepcopy(get_serializable_data(fl_ctx).get_all_public_props()))
reply.set_header(key=FLContextKey.PEER_CONTEXT, value=shared_fl_ctx)
if reply is not None:
return_message = new_cell_message({}, reply)
return_message.set_header(MessageHeaderKey.RETURN_CODE, ReturnCode.OK)
else:
return_message = new_cell_message({}, None)
return return_message
def shutdown(self):
self.asked_to_stop = True
| NVFlare-main | nvflare/private/fed/client/command_agent.py |
# Copyright (c) 2021, 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 .info_coll_cmd import ClientInfoProcessor
from .scheduler_cmds import CancelResourceProcessor, CheckResourceProcessor, ReportResourcesProcessor, StartJobProcessor
from .shell_cmd import ShellCommandProcessor
from .sys_cmd import SysInfoProcessor
from .training_cmds import ( # StartClientMGpuProcessor,; SetRunNumberProcessor,
AbortAppProcessor,
AbortTaskProcessor,
ClientStatusProcessor,
DeleteRunNumberProcessor,
DeployProcessor,
RestartClientProcessor,
ScopeInfoProcessor,
ShutdownClientProcessor,
StartAppProcessor,
)
class ClientRequestProcessors:
request_processors = [
StartAppProcessor(),
ClientStatusProcessor(),
ScopeInfoProcessor(),
AbortAppProcessor(),
ShutdownClientProcessor(),
DeployProcessor(),
ShellCommandProcessor(),
DeleteRunNumberProcessor(),
SysInfoProcessor(),
RestartClientProcessor(),
# StartClientMGpuProcessor(),
ClientInfoProcessor(),
AbortTaskProcessor(),
# SetRunNumberProcessor(),
StartJobProcessor(),
CheckResourceProcessor(),
CancelResourceProcessor(),
ReportResourcesProcessor(),
]
@staticmethod
def register_cmd_module(request_processor):
from .admin import RequestProcessor
if not isinstance(request_processor, RequestProcessor):
raise TypeError("request_processor must be RequestProcessor, but got {}".format(type(request_processor)))
ClientRequestProcessors.request_processors.append(request_processor)
| NVFlare-main | nvflare/private/fed/client/client_req_processors.py |
# Copyright (c) 2021, 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 logging
import os
import shlex
import subprocess
import sys
import threading
import time
from abc import ABC, abstractmethod
from nvflare.apis.fl_constant import AdminCommandNames, RunProcessKey
from nvflare.apis.resource_manager_spec import ResourceManagerSpec
from nvflare.fuel.common.exit_codes import PROCESS_EXIT_REASON, ProcessExitCode
from nvflare.fuel.f3.cellnet.core_cell import FQCN
from nvflare.fuel.f3.cellnet.defs import MessageHeaderKey, ReturnCode
from nvflare.private.defs import CellChannel, CellChannelTopic, JobFailureMsgKey, new_cell_message
from nvflare.security.logging import secure_format_exception, secure_log_traceback
from .client_status import ClientStatus, get_status_message
class ClientExecutor(ABC):
@abstractmethod
def start_app(
self,
client,
job_id,
args,
app_custom_folder,
listen_port,
allocated_resource,
token,
resource_manager,
target: str,
):
"""Starts the client app.
Args:
client: the FL client object
job_id: the job_id
args: admin command arguments for starting the FL client training
app_custom_folder: FL application custom folder
listen_port: port to listen the command.
allocated_resource: allocated resources
token: token from resource manager
resource_manager: resource manager
target: SP target location
"""
pass
@abstractmethod
def check_status(self, job_id) -> str:
"""Checks the status of the running client.
Args:
job_id: the job_id
Returns:
A client status message
"""
pass
@abstractmethod
def abort_app(self, job_id):
"""Aborts the running app.
Args:
job_id: the job_id
"""
pass
@abstractmethod
def abort_task(self, job_id):
"""Aborts the client executing task.
Args:
job_id: the job_id
"""
pass
@abstractmethod
def get_run_info(self, job_id):
"""Gets the run information.
Args:
job_id: the job_id
Returns:
A dict of run information.
"""
@abstractmethod
def get_errors(self, job_id):
"""Get the error information.
Returns:
A dict of error information.
"""
@abstractmethod
def reset_errors(self, job_id):
"""Resets the error information.
Args:
job_id: the job_id
"""
class ProcessExecutor(ClientExecutor):
"""Run the Client executor in a child process."""
def __init__(self, client, startup):
"""To init the ProcessExecutor.
Args:
startup: startup folder
"""
self.client = client
self.logger = logging.getLogger(self.__class__.__name__)
self.startup = startup
self.run_processes = {}
self.lock = threading.Lock()
def start_app(
self,
client,
job_id,
args,
app_custom_folder,
listen_port,
allocated_resource,
token,
resource_manager: ResourceManagerSpec,
target: str,
):
"""Starts the app.
Args:
client: the FL client object
job_id: the job_id
args: admin command arguments for starting the worker process
app_custom_folder: FL application custom folder
listen_port: port to listen the command.
allocated_resource: allocated resources
token: token from resource manager
resource_manager: resource manager
target: SP target location
"""
new_env = os.environ.copy()
if app_custom_folder != "":
new_env["PYTHONPATH"] = new_env.get("PYTHONPATH", "") + os.pathsep + app_custom_folder
command_options = ""
for t in args.set:
command_options += " " + t
command = (
f"{sys.executable} -m nvflare.private.fed.app.client.worker_process -m "
+ args.workspace
+ " -w "
+ self.startup
+ " -t "
+ client.token
+ " -d "
+ client.ssid
+ " -n "
+ job_id
+ " -c "
+ client.client_name
+ " -p "
+ str(client.cell.get_internal_listener_url())
+ " -g "
+ target
+ " -s fed_client.json "
" --set" + command_options + " print_conf=True"
)
# use os.setsid to create new process group ID
process = subprocess.Popen(shlex.split(command, True), preexec_fn=os.setsid, env=new_env)
self.logger.info("Worker child process ID: {}".format(process.pid))
client.multi_gpu = False
with self.lock:
self.run_processes[job_id] = {
RunProcessKey.LISTEN_PORT: listen_port,
RunProcessKey.CONNECTION: None,
RunProcessKey.CHILD_PROCESS: process,
RunProcessKey.STATUS: ClientStatus.STARTED,
}
thread = threading.Thread(
target=self._wait_child_process_finish,
args=(client, job_id, allocated_resource, token, resource_manager),
)
thread.start()
def check_status(self, job_id):
"""Checks the status of the running client.
Args:
job_id: the job_id
Returns:
A client status message
"""
try:
with self.lock:
data = {}
fqcn = FQCN.join([self.client.client_name, job_id])
request = new_cell_message({}, data)
return_data = self.client.cell.send_request(
target=fqcn,
channel=CellChannel.CLIENT_COMMAND,
topic=AdminCommandNames.CHECK_STATUS,
request=request,
optional=True,
)
return_code = return_data.get_header(MessageHeaderKey.RETURN_CODE)
if return_code == ReturnCode.OK:
status_message = return_data.payload
self.logger.debug("check status from process listener......")
return status_message
else:
process_status = ClientStatus.NOT_STARTED
return get_status_message(process_status)
except Exception as e:
self.logger.error(f"check_status execution exception: {secure_format_exception(e)}.")
secure_log_traceback()
return "execution exception. Please try again."
def get_run_info(self, job_id):
"""Gets the run information.
Args:
job_id: the job_id
Returns:
A dict of run information.
"""
try:
with self.lock:
data = {}
fqcn = FQCN.join([self.client.client_name, job_id])
request = new_cell_message({}, data)
return_data = self.client.cell.send_request(
target=fqcn,
channel=CellChannel.CLIENT_COMMAND,
topic=AdminCommandNames.SHOW_STATS,
request=request,
optional=True,
)
return_code = return_data.get_header(MessageHeaderKey.RETURN_CODE)
if return_code == ReturnCode.OK:
run_info = return_data.payload
return run_info
else:
return {}
except Exception as e:
self.logger.error(f"get_run_info execution exception: {secure_format_exception(e)}.")
secure_log_traceback()
return {"error": "no info collector. Please try again."}
def get_errors(self, job_id):
"""Get the error information.
Args:
job_id: the job_id
Returns:
A dict of error information.
"""
try:
with self.lock:
data = {"command": AdminCommandNames.SHOW_ERRORS, "data": {}}
fqcn = FQCN.join([self.client.client_name, job_id])
request = new_cell_message({}, data)
return_data = self.client.cell.send_request(
target=fqcn,
channel=CellChannel.CLIENT_COMMAND,
topic=AdminCommandNames.SHOW_ERRORS,
request=request,
optional=True,
)
return_code = return_data.get_header(MessageHeaderKey.RETURN_CODE)
if return_code == ReturnCode.OK:
errors_info = return_data.payload
return errors_info
else:
return None
except Exception as e:
self.logger.error(f"get_errors execution exception: {secure_format_exception(e)}.")
secure_log_traceback()
return None
def reset_errors(self, job_id):
"""Resets the error information.
Args:
job_id: the job_id
"""
try:
with self.lock:
data = {"command": AdminCommandNames.RESET_ERRORS, "data": {}}
fqcn = FQCN.join([self.client.client_name, job_id])
request = new_cell_message({}, data)
self.client.cell.fire_and_forget(
targets=fqcn,
channel=CellChannel.CLIENT_COMMAND,
topic=AdminCommandNames.RESET_ERRORS,
message=request,
optional=True,
)
except Exception as e:
self.logger.error(f"reset_errors execution exception: {secure_format_exception(e)}.")
secure_log_traceback()
def abort_app(self, job_id):
"""Aborts the running app.
Args:
job_id: the job_id
"""
with self.lock:
# When the HeartBeat cleanup process try to abort the worker process, the job maybe already terminated,
# Use retry to avoid print out the error stack trace.
retry = 1
while retry >= 0:
process_status = self.run_processes.get(job_id, {}).get(RunProcessKey.STATUS, ClientStatus.NOT_STARTED)
if process_status == ClientStatus.STARTED:
try:
child_process = self.run_processes[job_id][RunProcessKey.CHILD_PROCESS]
data = {}
fqcn = FQCN.join([self.client.client_name, job_id])
request = new_cell_message({}, data)
self.client.cell.fire_and_forget(
targets=fqcn,
channel=CellChannel.CLIENT_COMMAND,
topic=AdminCommandNames.ABORT,
message=request,
optional=True,
)
self.logger.debug("abort sent to worker")
t = threading.Thread(target=self._terminate_process, args=[child_process, job_id])
t.start()
t.join()
break
except Exception as e:
if retry == 0:
self.logger.error(
f"abort_worker_process execution exception: {secure_format_exception(e)} for run: {job_id}."
)
secure_log_traceback()
retry -= 1
time.sleep(5.0)
else:
self.logger.info(f"Client worker process for run: {job_id} was already terminated.")
break
self.logger.info("Client worker process is terminated.")
def _terminate_process(self, child_process, job_id):
max_wait = 10.0
done = False
start = time.time()
while True:
process = self.run_processes.get(job_id)
if not process:
# already finished gracefully
done = True
break
if time.time() - start > max_wait:
# waited enough
break
time.sleep(0.05) # we want to quickly check
# kill the sub-process group directly
if not done:
self.logger.debug(f"still not done after {max_wait} secs")
try:
os.killpg(os.getpgid(child_process.pid), 9)
self.logger.debug("kill signal sent")
except:
pass
child_process.terminate()
self.logger.info(f"run ({job_id}): child worker process terminated")
def abort_task(self, job_id):
"""Aborts the client executing task.
Args:
job_id: the job_id
"""
with self.lock:
process_status = self.run_processes.get(job_id, {}).get(RunProcessKey.STATUS, ClientStatus.NOT_STARTED)
if process_status == ClientStatus.STARTED:
data = {"command": AdminCommandNames.ABORT_TASK, "data": {}}
fqcn = FQCN.join([self.client.client_name, job_id])
request = new_cell_message({}, data)
self.client.cell.fire_and_forget(
targets=fqcn,
channel=CellChannel.CLIENT_COMMAND,
topic=AdminCommandNames.ABORT_TASK,
message=request,
optional=True,
)
self.logger.debug("abort_task sent")
def _wait_child_process_finish(self, client, job_id, allocated_resource, token, resource_manager):
self.logger.info(f"run ({job_id}): waiting for child worker process to finish.")
with self.lock:
child_process = self.run_processes.get(job_id, {}).get(RunProcessKey.CHILD_PROCESS)
if child_process:
child_process.wait()
return_code = child_process.returncode
self.logger.info(f"run ({job_id}): child worker process finished with RC {return_code}")
if return_code in [ProcessExitCode.UNSAFE_COMPONENT, ProcessExitCode.CONFIG_ERROR]:
request = new_cell_message(
headers={},
payload={
JobFailureMsgKey.JOB_ID: job_id,
JobFailureMsgKey.CODE: return_code,
JobFailureMsgKey.REASON: PROCESS_EXIT_REASON[return_code],
},
)
self.client.cell.fire_and_forget(
targets=[FQCN.ROOT_SERVER],
channel=CellChannel.SERVER_MAIN,
topic=CellChannelTopic.REPORT_JOB_FAILURE,
message=request,
optional=True,
)
self.logger.info(f"reported failure of job {job_id} to server!")
if allocated_resource:
resource_manager.free_resources(
resources=allocated_resource, token=token, fl_ctx=client.engine.new_context()
)
self.run_processes.pop(job_id, None)
self.logger.debug(f"run ({job_id}): child worker resources freed.")
def get_status(self, job_id):
with self.lock:
process_status = self.run_processes.get(job_id, {}).get(RunProcessKey.STATUS, ClientStatus.STOPPED)
return process_status
def get_run_processes_keys(self):
with self.lock:
return [x for x in self.run_processes.keys()]
| NVFlare-main | nvflare/private/fed/client/client_executor.py |
# Copyright (c) 2021, 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 logging
import time
from typing import Dict, List, Optional, Union
from nvflare.apis.fl_component import FLComponent
from nvflare.apis.fl_constant import FLContextKey, ServerCommandKey, ServerCommandNames, SiteType
from nvflare.apis.fl_context import FLContext, FLContextManager
from nvflare.apis.shareable import Shareable
from nvflare.apis.workspace import Workspace
from nvflare.fuel.f3.cellnet.core_cell import FQCN
from nvflare.fuel.f3.cellnet.defs import MessageHeaderKey
from nvflare.fuel.f3.cellnet.defs import ReturnCode as CellReturnCode
from nvflare.private.aux_runner import AuxRunner
from nvflare.private.defs import CellChannel, CellMessageHeaderKeys, new_cell_message
from nvflare.private.event import fire_event
from nvflare.private.fed.utils.fed_utils import create_job_processing_context_properties
from nvflare.widgets.fed_event import ClientFedEventRunner
from nvflare.widgets.info_collector import InfoCollector
from nvflare.widgets.widget import Widget, WidgetID
from .client_engine_executor_spec import ClientEngineExecutorSpec, TaskAssignment
from .client_json_config import ClientJsonConfigurator
from .client_runner import ClientRunner
from .fed_client import FederatedClient
class ClientRunInfo(object):
def __init__(self, job_id):
"""To init the ClientRunInfo.
Args:
job_id: job id
"""
self.job_id = job_id
self.current_task_name = ""
self.start_time = None
# TODO: make this configurable
# this is the number of retries for client side child/job process to get clients from server
# we might need to think of removing the whole get clients from server logic from child process
GET_CLIENTS_RETRY = 300
class ClientRunManager(ClientEngineExecutorSpec):
"""ClientRunManager provides the ClientEngine APIs implementation running in the child process."""
def __init__(
self,
client_name: str,
job_id: str,
workspace: Workspace,
client: FederatedClient,
components: Dict[str, FLComponent],
handlers: Optional[List[FLComponent]] = None,
conf: ClientJsonConfigurator = None,
) -> None:
"""To init the ClientRunManager.
Args:
client_name: client name
job_id: job id
workspace: workspace
client: FL client object
components: available FL components
handlers: available handlers
conf: ClientJsonConfigurator object
"""
super().__init__()
self.client = client
self.handlers = handlers
self.workspace = workspace
self.components = components
# self.aux_runner = ClientAuxRunner()
self.aux_runner = AuxRunner(self)
self.add_handler(self.aux_runner)
self.conf = conf
self.cell = None
self.all_clients = None
if not components:
self.components = {}
if not handlers:
self.handlers = []
# get job meta!
job_ctx_props = self.create_job_processing_context_properties(workspace, job_id)
self.fl_ctx_mgr = FLContextManager(
engine=self, identity_name=client_name, job_id=job_id, public_stickers={}, private_stickers=job_ctx_props
)
self.run_info = ClientRunInfo(job_id=job_id)
self.widgets = {WidgetID.INFO_COLLECTOR: InfoCollector(), WidgetID.FED_EVENT_RUNNER: ClientFedEventRunner()}
for _, widget in self.widgets.items():
self.handlers.append(widget)
self.logger = logging.getLogger(self.__class__.__name__)
def get_task_assignment(self, fl_ctx: FLContext) -> TaskAssignment:
pull_success, task_name, return_shareable = self.client.fetch_task(fl_ctx)
task = None
if pull_success:
shareable = self.client.extract_shareable(return_shareable, fl_ctx)
task_id = shareable.get_header(key=FLContextKey.TASK_ID)
task = TaskAssignment(name=task_name, task_id=task_id, data=shareable)
return task
def new_context(self) -> FLContext:
return self.fl_ctx_mgr.new_context()
def send_task_result(self, result: Shareable, fl_ctx: FLContext) -> bool:
push_result = self.client.push_results(result, fl_ctx) # push task execution results
if push_result[0] == CellReturnCode.OK:
return True
else:
return False
def get_workspace(self) -> Workspace:
return self.workspace
def get_run_info(self) -> ClientRunInfo:
return self.run_info
def show_errors(self) -> ClientRunInfo:
return self.run_info
def reset_errors(self) -> ClientRunInfo:
return self.run_info
def dispatch(self, topic: str, request: Shareable, fl_ctx: FLContext) -> Shareable:
return self.aux_runner.dispatch(topic=topic, request=request, fl_ctx=fl_ctx)
def get_component(self, component_id: str) -> object:
return self.components.get(component_id)
def get_all_components(self) -> dict:
return self.components
def validate_targets(self, inputs) -> ([], []):
valid_inputs = []
invalid_inputs = []
for item in inputs:
if item == FQCN.ROOT_SERVER:
valid_inputs.append(item)
else:
client = self.get_client_from_name(item)
if client:
valid_inputs.append(item)
else:
invalid_inputs.append(item)
return valid_inputs, invalid_inputs
def get_client_from_name(self, client_name):
for _, c in self.all_clients.items():
if client_name == c.name:
return c
return None
def get_widget(self, widget_id: str) -> Widget:
return self.widgets.get(widget_id)
def fire_event(self, event_type: str, fl_ctx: FLContext):
fire_event(event=event_type, handlers=self.handlers, ctx=fl_ctx)
def add_handler(self, handler: FLComponent):
self.handlers.append(handler)
def build_component(self, config_dict):
if not self.conf:
raise RuntimeError("No configurator set up.")
return self.conf.build_component(config_dict)
def get_cell(self):
return self.cell
def send_aux_request(
self,
targets: Union[None, str, List[str]],
topic: str,
request: Shareable,
timeout: float,
fl_ctx: FLContext,
optional=False,
secure=False,
) -> dict:
if not targets:
targets = [FQCN.ROOT_SERVER]
else:
if isinstance(targets, str):
if targets == SiteType.ALL:
targets = [FQCN.ROOT_SERVER]
for _, t in self.all_clients.items():
if t.name != self.client.client_name:
targets.append(t.name)
else:
targets = [targets]
if targets:
return self.aux_runner.send_aux_request(
targets, topic, request, timeout, fl_ctx, optional=optional, secure=secure
)
else:
return {}
def get_all_clients_from_server(self, fl_ctx, retry=0):
job_id = fl_ctx.get_prop(FLContextKey.CURRENT_RUN)
get_clients_message = new_cell_message({CellMessageHeaderKeys.JOB_ID: job_id}, {})
return_data = self.client.cell.send_request(
target=FQCN.ROOT_SERVER,
channel=CellChannel.SERVER_PARENT_LISTENER,
topic=ServerCommandNames.GET_CLIENTS,
request=get_clients_message,
timeout=5.0,
optional=True,
)
return_code = return_data.get_header(MessageHeaderKey.RETURN_CODE)
if return_code == CellReturnCode.OK:
if return_data.payload:
data = return_data.payload
self.all_clients = data.get(ServerCommandKey.CLIENTS)
else:
raise RuntimeError("Empty clients data from server")
else:
# retry to handle the server connect has not been established scenario.
retry += 1
if retry < GET_CLIENTS_RETRY:
time.sleep(0.5)
self.get_all_clients_from_server(fl_ctx, retry)
else:
raise RuntimeError("Failed to get the clients from the server.")
def register_aux_message_handler(self, topic: str, message_handle_func):
self.aux_runner.register_aux_message_handler(topic, message_handle_func)
def fire_and_forget_aux_request(
self, topic: str, request: Shareable, fl_ctx: FLContext, optional=False, secure=False
) -> dict:
return self.send_aux_request(
targets=None, topic=topic, request=request, timeout=0.0, fl_ctx=fl_ctx, optional=optional, secure=secure
)
def abort_app(self, job_id: str, fl_ctx: FLContext):
runner = fl_ctx.get_prop(key=FLContextKey.RUNNER, default=None)
if isinstance(runner, ClientRunner):
runner.abort()
def create_job_processing_context_properties(self, workspace, job_id):
return create_job_processing_context_properties(workspace, job_id)
| NVFlare-main | nvflare/private/fed/client/client_run_manager.py |
# Copyright (c) 2021, 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.
"""This is the NVFlare client package."""
| NVFlare-main | nvflare/private/fed/client/__init__.py |
# Copyright (c) 2021, 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 time
from abc import ABC, abstractmethod
from typing import List, Union
from nvflare.apis.client_engine_spec import ClientEngineSpec
from nvflare.apis.engine_spec import EngineSpec
from nvflare.apis.fl_context import FLContext
from nvflare.apis.shareable import Shareable
from nvflare.apis.workspace import Workspace
from nvflare.widgets.widget import Widget
class TaskAssignment(object):
def __init__(self, name: str, task_id: str, data: Shareable):
"""Init TaskAssignment.
Keeps track of information about the assignment of a task, including the time
that it was created after being fetched by the Client Run Manager.
Args:
name: task name
task_id: task id
data: the Shareable data for the task assignment
"""
self.name = name
self.task_id = task_id
self.data = data
self.receive_time = time.time()
class ClientEngineExecutorSpec(ClientEngineSpec, EngineSpec, ABC):
"""The ClientEngineExecutorSpec defines the ClientEngine APIs running in the child process."""
@abstractmethod
def get_task_assignment(self, fl_ctx: FLContext) -> TaskAssignment:
pass
@abstractmethod
def send_task_result(self, result: Shareable, fl_ctx: FLContext) -> bool:
pass
@abstractmethod
def get_workspace(self) -> Workspace:
pass
@abstractmethod
def get_widget(self, widget_id: str) -> Widget:
pass
@abstractmethod
def get_all_components(self) -> dict:
pass
@abstractmethod
def register_aux_message_handler(self, topic: str, message_handle_func):
"""Register aux message handling function with specified topics.
Exception is raised when:
a handler is already registered for the topic;
bad topic - must be a non-empty string
bad message_handle_func - must be callable
Implementation Note:
This method should simply call the ClientAuxRunner's register_aux_message_handler method.
Args:
topic: the topic to be handled by the func
message_handle_func: the func to handle the message. Must follow aux_message_handle_func_signature.
"""
pass
@abstractmethod
def send_aux_request(
self,
targets: Union[None, str, List[str]],
topic: str,
request: Shareable,
timeout: float,
fl_ctx: FLContext,
optional=False,
secure: bool = False,
) -> dict:
"""Send a request to Server via the aux channel.
Implementation: simply calls the ClientAuxRunner's send_aux_request method.
Args:
targets: aux messages targets. None or empty list means the server.
topic: topic of the request
request: request to be sent
timeout: number of secs to wait for replies. 0 means fire-and-forget.
fl_ctx: FL context
optional: whether the request is optional
secure: should the request sent in the secure way
Returns:
a dict of reply Shareable in the format of:
{ site_name: reply_shareable }
"""
pass
@abstractmethod
def fire_and_forget_aux_request(
self, topic: str, request: Shareable, fl_ctx: FLContext, optional=False, secure=False
) -> Shareable:
"""Send an async request to Server via the aux channel.
Args:
topic: topic of the request
request: request to be sent
fl_ctx: FL context
optional: whether the request is optional
Returns:
"""
pass
@abstractmethod
def build_component(self, config_dict):
"""Build a component from the config_dict.
Args:
config_dict: config dict
"""
pass
@abstractmethod
def abort_app(self, job_id: str, fl_ctx: FLContext):
"""Abort the running FL App on the client.
Args:
job_id: current_job_id
fl_ctx: FLContext
"""
pass
| NVFlare-main | nvflare/private/fed/client/client_engine_executor_spec.py |
# Copyright (c) 2021, 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.
"""FL Admin commands."""
from nvflare.apis.fl_constant import AdminCommandNames, FLContextKey
from nvflare.apis.fl_context import FLContext
from nvflare.apis.shareable import Shareable
from nvflare.private.fed.client.client_status import get_status_message
from nvflare.widgets.info_collector import InfoCollector
from nvflare.widgets.widget import WidgetID
class CommandProcessor(object):
"""The CommandProcessor is responsible for processing a command from parent process."""
def get_command_name(self) -> str:
"""Get command name that this processor will handle.
Returns: name of the command
"""
pass
def process(self, data: Shareable, fl_ctx: FLContext):
"""Called to process the specified command.
Args:
data: process data
fl_ctx: FLContext
Return: reply message
"""
pass
class CheckStatusCommand(CommandProcessor):
"""To implement the check_status command."""
def get_command_name(self) -> str:
"""To get thee command name.
Returns: AdminCommandNames.CHECK_STATUSv
"""
return AdminCommandNames.CHECK_STATUS
def process(self, data: Shareable, fl_ctx: FLContext):
"""Called to process the check_status command.
Args:
data: process data
fl_ctx: FLContext
Returns: status message
"""
engine = fl_ctx.get_engine()
federated_client = engine.client
return get_status_message(federated_client.status)
class AbortCommand(CommandProcessor):
"""To implement the abort command."""
def get_command_name(self) -> str:
"""To get the command name.
Returns: AdminCommandNames.ABORT
"""
return AdminCommandNames.ABORT
def process(self, data: Shareable, fl_ctx: FLContext):
"""Called to process the abort command.
Args:
data: process data
fl_ctx: FLContext
Returns: abort command message
"""
client_runner = fl_ctx.get_prop(FLContextKey.RUNNER)
return client_runner.abort()
class AbortTaskCommand(CommandProcessor):
"""To implement the abort_task command."""
def get_command_name(self) -> str:
"""To get the command name.
Returns: AdminCommandNames.ABORT_TASK
"""
return AdminCommandNames.ABORT_TASK
def process(self, data: Shareable, fl_ctx: FLContext):
"""Called to process the abort_task command.
Args:
data: process data
fl_ctx: FLContext
Returns: abort_task command message
"""
client_runner = fl_ctx.get_prop(FLContextKey.RUNNER)
if client_runner:
client_runner.abort_task()
return None
class ShowStatsCommand(CommandProcessor):
"""To implement the show_stats command."""
def get_command_name(self) -> str:
"""To get the command name.
Returns: AdminCommandNames.SHOW_STATS
"""
return AdminCommandNames.SHOW_STATS
def process(self, data: Shareable, fl_ctx: FLContext):
"""Called to process the abort_task command.
Args:
data: process data
fl_ctx: FLContext
Returns: show_stats command message
"""
engine = fl_ctx.get_engine()
collector = engine.get_widget(WidgetID.INFO_COLLECTOR)
if not collector:
result = {"error": "no info collector"}
else:
if not isinstance(collector, InfoCollector):
raise TypeError("collector must be an instance of InfoCollector, but got {}".format(type(collector)))
result = collector.get_run_stats()
if not result:
result = "No stats info"
return result
class ShowErrorsCommand(CommandProcessor):
"""To implement the show_errors command."""
def get_command_name(self) -> str:
"""To get the command name.
Returns: AdminCommandNames.SHOW_ERRORS
"""
return AdminCommandNames.SHOW_ERRORS
def process(self, data: Shareable, fl_ctx: FLContext):
"""Called to process the show_errors command.
Args:
data: process data
fl_ctx: FLContext
Returns: show_errors command message
"""
engine = fl_ctx.get_engine()
collector = engine.get_widget(WidgetID.INFO_COLLECTOR)
if not collector:
result = {"error": "no info collector"}
else:
if not isinstance(collector, InfoCollector):
raise TypeError("collector must be an instance of InfoCollector, but got {}".format(type(collector)))
result = collector.get_errors()
# CommandAgent is expecting data, could not be None
if result is None:
result = "No Errors"
return result
class ResetErrorsCommand(CommandProcessor):
"""To implement the reset_errors command."""
def get_command_name(self) -> str:
"""To get the command name.
Returns: AdminCommandNames.RESET_ERRORS
"""
return AdminCommandNames.RESET_ERRORS
def process(self, data: Shareable, fl_ctx: FLContext):
"""Called to process the reset_errors command.
Args:
data: process data
fl_ctx: FLContext
Returns: reset_errors command message
"""
engine = fl_ctx.get_engine()
engine.reset_errors()
class ByeCommand(CommandProcessor):
"""To implement the ShutdownCommand."""
def get_command_name(self) -> str:
"""To get the command name.
Returns: AdminCommandNames.SHUTDOWN
"""
return AdminCommandNames.SHUTDOWN
def process(self, data: Shareable, fl_ctx: FLContext):
"""Called to process the Shutdown command.
Args:
data: process data
fl_ctx: FLContext
Returns: Shutdown command message
"""
return None
class AdminCommands(object):
"""AdminCommands contains all the commands for processing the commands from the parent process."""
commands = [
CheckStatusCommand(),
AbortCommand(),
AbortTaskCommand(),
ByeCommand(),
ShowStatsCommand(),
ShowErrorsCommand(),
ResetErrorsCommand(),
]
@staticmethod
def get_command(command_name):
"""Call to return the AdminCommand object.
Args:
command_name: AdminCommand name
Returns: AdminCommand object
"""
for command in AdminCommands.commands:
if command_name == command.get_command_name():
return command
return None
@staticmethod
def register_command(command_processor: CommandProcessor):
"""Call to register the AdminCommand processor.
Args:
command_processor: AdminCommand processor
"""
if not isinstance(command_processor, CommandProcessor):
raise TypeError(
"command_processor must be an instance of CommandProcessor, but got {}".format(type(command_processor))
)
AdminCommands.commands.append(command_processor)
| NVFlare-main | nvflare/private/fed/client/admin_commands.py |
# Copyright (c) 2021, 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 json
from typing import List
import psutil
try:
import pynvml
except ImportError:
pynvml = None
from nvflare.private.admin_defs import Message
from nvflare.private.defs import SysCommandTopic
from nvflare.private.fed.client.admin import RequestProcessor
class SysInfoProcessor(RequestProcessor):
def get_topics(self) -> List[str]:
return [SysCommandTopic.SYS_INFO]
def process(self, req: Message, app_ctx) -> Message:
infos = dict(psutil.virtual_memory()._asdict())
if pynvml:
try:
pynvml.nvmlInit()
device_count = pynvml.nvmlDeviceGetCount()
gpu_info = {"gpu_count": device_count}
for index in range(device_count):
handle = pynvml.nvmlDeviceGetHandleByIndex(index)
gpu_info[f"gpu_device_{index}"] = pynvml.nvmlDeviceGetName(handle).decode("utf-8")
pynvml.nvmlShutdown()
infos.update(gpu_info)
except pynvml.nvml.NVMLError_LibraryNotFound:
pass
# docker_image_tag = os.environ.get('DOCKER_IMAGE_TAG', 'N/A')
# infos.update({'docker_image_tag':docker_image_tag})
message = Message(topic="reply_" + req.topic, body=json.dumps(infos))
print("return sys_info")
print(infos)
return message
| NVFlare-main | nvflare/private/fed/client/sys_cmd.py |
# Copyright (c) 2021, 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 logging
import socket
import time
from typing import List, Optional
from nvflare.apis.filter import Filter
from nvflare.apis.fl_constant import FLContextKey
from nvflare.apis.fl_constant import ReturnCode as ShareableRC
from nvflare.apis.fl_constant import ServerCommandKey, ServerCommandNames
from nvflare.apis.fl_context import FLContext
from nvflare.apis.fl_exception import FLCommunicationError
from nvflare.apis.shareable import Shareable
from nvflare.apis.utils.fl_context_utils import get_serializable_data
from nvflare.fuel.f3.cellnet.core_cell import FQCN, CoreCell
from nvflare.fuel.f3.cellnet.defs import MessageHeaderKey, ReturnCode
from nvflare.private.defs import CellChannel, CellChannelTopic, CellMessageHeaderKeys, SpecialTaskName, new_cell_message
from nvflare.private.fed.client.client_engine_internal_spec import ClientEngineInternalSpec
from nvflare.security.logging import secure_format_exception
def _get_client_ip():
"""Return localhost IP.
More robust than ``socket.gethostbyname(socket.gethostname())``. See
https://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib/28950776#28950776
for more details.
Returns:
The host IP
"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(("10.255.255.255", 1)) # doesn't even have to be reachable
ip = s.getsockname()[0]
except Exception:
ip = "127.0.0.1"
finally:
s.close()
return ip
class Communicator:
def __init__(
self,
ssl_args=None,
secure_train=False,
client_state_processors: Optional[List[Filter]] = None,
compression=None,
cell: CoreCell = None,
client_register_interval=2,
timeout=5.0,
):
"""To init the Communicator.
Args:
ssl_args: SSL args
secure_train: True/False to indicate if secure train
client_state_processors: Client state processor filters
compression: communicate compression algorithm
"""
self.cell = cell
self.ssl_args = ssl_args
self.secure_train = secure_train
self.verbose = False
self.should_stop = False
self.heartbeat_done = False
self.client_state_processors = client_state_processors
self.compression = compression
self.client_register_interval = client_register_interval
self.timeout = timeout
self.logger = logging.getLogger(self.__class__.__name__)
def client_registration(self, client_name, servers, project_name):
"""Client's metadata used to authenticate and communicate.
Args:
client_name: client name
servers: FL servers
project_name: FL study project name
Returns:
The client's token
"""
local_ip = _get_client_ip()
login_message = new_cell_message(
{
CellMessageHeaderKeys.CLIENT_NAME: client_name,
CellMessageHeaderKeys.CLIENT_IP: local_ip,
CellMessageHeaderKeys.PROJECT_NAME: project_name,
}
)
start = time.time()
while not self.cell:
self.logger.info("Waiting for the client cell to be created.")
if time.time() - start > 15.0:
raise RuntimeError("Client cell could not be created. Failed to login the client.")
time.sleep(0.5)
while not self.cell.is_cell_connected(FQCN.ROOT_SERVER):
time.sleep(0.1)
if time.time() - start > 30.0:
raise FLCommunicationError("error:Could not connect to the server for client_registration.")
while True:
try:
result = self.cell.send_request(
target=FQCN.ROOT_SERVER,
channel=CellChannel.SERVER_MAIN,
topic=CellChannelTopic.Register,
request=login_message,
timeout=self.timeout,
)
return_code = result.get_header(MessageHeaderKey.RETURN_CODE)
if return_code == ReturnCode.UNAUTHENTICATED:
unauthenticated = result.get_header(MessageHeaderKey.ERROR)
raise FLCommunicationError("error:client_registration " + unauthenticated)
token = result.get_header(CellMessageHeaderKeys.TOKEN)
ssid = result.get_header(CellMessageHeaderKeys.SSID)
if not token and not self.should_stop:
time.sleep(self.client_register_interval)
else:
break
except Exception as ex:
raise FLCommunicationError("error:client_registration", ex)
return token, ssid
def pull_task(self, servers, project_name, token, ssid, fl_ctx: FLContext):
"""Get a task from server.
Args:
servers: FL servers
project_name: FL study project name
token: client token
ssid: service session ID
fl_ctx: FLContext
Returns:
A CurrentTask message from server
"""
start_time = time.time()
shareable = Shareable()
shared_fl_ctx = FLContext()
shared_fl_ctx.set_public_props(get_serializable_data(fl_ctx).get_all_public_props())
shareable.set_header(ServerCommandKey.PEER_FL_CONTEXT, shared_fl_ctx)
client_name = fl_ctx.get_identity_name()
task_message = new_cell_message(
{
CellMessageHeaderKeys.TOKEN: token,
CellMessageHeaderKeys.CLIENT_NAME: client_name,
CellMessageHeaderKeys.SSID: ssid,
CellMessageHeaderKeys.PROJECT_NAME: project_name,
},
shareable,
)
job_id = str(shared_fl_ctx.get_prop(FLContextKey.CURRENT_RUN))
fqcn = FQCN.join([FQCN.ROOT_SERVER, job_id])
task = self.cell.send_request(
target=fqcn,
channel=CellChannel.SERVER_COMMAND,
topic=ServerCommandNames.GET_TASK,
request=task_message,
timeout=self.timeout,
optional=True,
)
end_time = time.time()
return_code = task.get_header(MessageHeaderKey.RETURN_CODE)
if return_code == ReturnCode.OK:
size = len(task.payload)
task.payload = task.payload
task_name = task.payload.get_header(ServerCommandKey.TASK_NAME)
fl_ctx.set_prop(FLContextKey.SSID, ssid, sticky=False)
if task_name not in [SpecialTaskName.END_RUN, SpecialTaskName.TRY_AGAIN]:
self.logger.info(
f"Received from {project_name} server "
f" ({size} Bytes). getTask: {task_name} time: {end_time - start_time} seconds"
)
elif return_code == ReturnCode.AUTHENTICATION_ERROR:
self.logger.warning("get_task request authentication failed.")
time.sleep(5.0)
return None
else:
task = None
self.logger.warning(f"Failed to get_task from {project_name} server. Will try it again.")
return task
def submit_update(
self, servers, project_name, token, ssid, fl_ctx: FLContext, client_name, shareable, execute_task_name
):
"""Submit the task execution result back to the server.
Args:
servers: FL servers
project_name: server project name
token: client token
ssid: service session ID
fl_ctx: fl_ctx
client_name: client name
shareable: execution task result shareable
execute_task_name: execution task name
Returns:
ReturnCode
"""
start_time = time.time()
shared_fl_ctx = FLContext()
shared_fl_ctx.set_public_props(get_serializable_data(fl_ctx).get_all_public_props())
shareable.set_header(ServerCommandKey.PEER_FL_CONTEXT, shared_fl_ctx)
# shareable.add_cookie(name=FLContextKey.TASK_ID, data=task_id)
shareable.set_header(FLContextKey.TASK_NAME, execute_task_name)
task_ssid = fl_ctx.get_prop(FLContextKey.SSID)
if task_ssid != ssid:
self.logger.warning("submit_update request failed because SSID mismatch.")
return ReturnCode.INVALID_SESSION
rc = shareable.get_return_code()
optional = rc == ShareableRC.TASK_ABORTED
task_message = new_cell_message(
{
CellMessageHeaderKeys.TOKEN: token,
CellMessageHeaderKeys.CLIENT_NAME: client_name,
CellMessageHeaderKeys.SSID: ssid,
CellMessageHeaderKeys.PROJECT_NAME: project_name,
},
shareable,
)
job_id = str(shared_fl_ctx.get_prop(FLContextKey.CURRENT_RUN))
fqcn = FQCN.join([FQCN.ROOT_SERVER, job_id])
result = self.cell.send_request(
target=fqcn,
channel=CellChannel.SERVER_COMMAND,
topic=ServerCommandNames.SUBMIT_UPDATE,
request=task_message,
timeout=self.timeout,
optional=optional,
)
end_time = time.time()
return_code = result.get_header(MessageHeaderKey.RETURN_CODE)
self.logger.info(
f" SubmitUpdate size: {len(task_message.payload)} Bytes. time: {end_time - start_time} seconds"
)
return return_code
def quit_remote(self, servers, task_name, token, ssid, fl_ctx: FLContext):
"""Sending the last message to the server before leaving.
Args:
servers: FL servers
task_name: project name
token: FL client token
fl_ctx: FLContext
Returns:
server's reply to the last message
"""
client_name = fl_ctx.get_identity_name()
quit_message = new_cell_message(
{
CellMessageHeaderKeys.TOKEN: token,
CellMessageHeaderKeys.CLIENT_NAME: client_name,
CellMessageHeaderKeys.SSID: ssid,
CellMessageHeaderKeys.PROJECT_NAME: task_name,
}
)
try:
result = self.cell.send_request(
target=FQCN.ROOT_SERVER,
channel=CellChannel.SERVER_MAIN,
topic=CellChannelTopic.Quit,
request=quit_message,
timeout=self.timeout,
)
return_code = result.get_header(MessageHeaderKey.RETURN_CODE)
if return_code == ReturnCode.UNAUTHENTICATED:
self.logger.info(f"Client token: {token} has been removed from the server.")
server_message = result.get_header(CellMessageHeaderKeys.MESSAGE)
except Exception as ex:
raise FLCommunicationError("error:client_quit", ex)
return server_message
def send_heartbeat(self, servers, task_name, token, ssid, client_name, engine: ClientEngineInternalSpec, interval):
fl_ctx = engine.new_context()
simulate_mode = fl_ctx.get_prop(FLContextKey.SIMULATE_MODE, False)
wait_times = int(interval / 2)
num_heartbeats_sent = 0
heartbeats_log_interval = 10
while not self.heartbeat_done:
try:
job_ids = engine.get_all_job_ids()
heartbeat_message = new_cell_message(
{
CellMessageHeaderKeys.TOKEN: token,
CellMessageHeaderKeys.SSID: ssid,
CellMessageHeaderKeys.CLIENT_NAME: client_name,
CellMessageHeaderKeys.PROJECT_NAME: task_name,
CellMessageHeaderKeys.JOB_IDS: job_ids,
}
)
try:
result = self.cell.send_request(
target=FQCN.ROOT_SERVER,
channel=CellChannel.SERVER_MAIN,
topic=CellChannelTopic.HEART_BEAT,
request=heartbeat_message,
timeout=self.timeout,
)
return_code = result.get_header(MessageHeaderKey.RETURN_CODE)
if return_code == ReturnCode.UNAUTHENTICATED:
unauthenticated = result.get_header(MessageHeaderKey.ERROR)
raise FLCommunicationError("error:client_quit " + unauthenticated)
num_heartbeats_sent += 1
if num_heartbeats_sent % heartbeats_log_interval == 0:
self.logger.debug(f"Client: {client_name} has sent {num_heartbeats_sent} heartbeats.")
if not simulate_mode:
# server_message = result.get_header(CellMessageHeaderKeys.MESSAGE)
abort_jobs = result.get_header(CellMessageHeaderKeys.ABORT_JOBS, [])
self._clean_up_runs(engine, abort_jobs)
else:
if return_code != ReturnCode.OK:
break
except Exception as ex:
raise FLCommunicationError("error:client_quit", ex)
for i in range(wait_times):
time.sleep(2)
if self.heartbeat_done:
break
except Exception as e:
self.logger.info(f"Failed to send heartbeat. Will try again. Exception: {secure_format_exception(e)}")
time.sleep(5)
def _clean_up_runs(self, engine, abort_runs):
# abort_runs = list(set(response.abort_jobs))
display_runs = ",".join(abort_runs)
try:
if abort_runs:
for job in abort_runs:
engine.abort_app(job)
self.logger.debug(f"These runs: {display_runs} are not running on the server. Aborted them.")
except:
self.logger.debug(f"Failed to clean up the runs: {display_runs}")
| NVFlare-main | nvflare/private/fed/client/communicator.py |
# Copyright (c) 2021, 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.
"""The FedAdmin to communicate with the Admin server."""
from nvflare.fuel.f3.cellnet.cell import Cell
from nvflare.fuel.f3.cellnet.core_cell import Message as CellMessage
from nvflare.fuel.hci.server.constants import ConnProps
from nvflare.fuel.sec.audit import Auditor, AuditService
from nvflare.fuel.sec.authz import AuthorizationService, AuthzContext, Person
from nvflare.private.admin_defs import Message, error_reply, ok_reply
from nvflare.private.defs import CellChannel, RequestHeader, new_cell_message
from nvflare.security.logging import secure_format_exception, secure_log_traceback
class RequestProcessor(object):
"""The RequestProcessor is responsible for processing a request."""
def get_topics(self) -> [str]:
"""Get topics that this processor will handle.
Returns: list of topics
"""
pass
def process(self, req: Message, app_ctx) -> Message:
"""Called to process the specified request.
Args:
req: request message
app_ctx: application context
Returns: reply message
"""
pass
class FedAdminAgent(object):
"""FedAdminAgent communicate with the FedAdminServer."""
def __init__(self, client_name: str, cell: Cell, app_ctx):
"""Init the FedAdminAgent.
Args:
client_name: client name
app_ctx: application context
cell: the Cell for communication
"""
auditor = AuditService.get_auditor()
if not isinstance(auditor, Auditor):
raise TypeError("auditor must be an instance of Auditor, but got {}".format(type(auditor)))
self.name = client_name
self.cell = cell
self.auditor = auditor
self.app_ctx = app_ctx
self.processors = {}
self.asked_to_stop = False
self.register_cell_cb()
def register_cell_cb(self):
self.cell.register_request_cb(
channel=CellChannel.CLIENT_MAIN,
topic="*",
cb=self._dispatch_request,
)
def register_processor(self, processor: RequestProcessor):
"""To register the RequestProcessor.
Args:
processor: RequestProcessor
"""
if not isinstance(processor, RequestProcessor):
raise TypeError("processor must be an instance of RequestProcessor, but got {}".format(type(processor)))
topics = processor.get_topics()
for topic in topics:
assert topic not in self.processors, "duplicate processors for topic {}".format(topic)
self.processors[topic] = processor
def _dispatch_request(
self,
request: CellMessage,
# *args, **kwargs
) -> CellMessage:
assert isinstance(request, CellMessage), "request must be CellMessage but got {}".format(type(request))
req = request.payload
assert isinstance(req, Message), "request payload must be Message but got {}".format(type(req))
topic = req.topic
# create audit record
if self.auditor:
user_name = req.get_header(RequestHeader.USER_NAME, "")
ref_event_id = req.get_header(ConnProps.EVENT_ID, "")
self.auditor.add_event(user=user_name, action=topic, ref=ref_event_id)
processor: RequestProcessor = self.processors.get(topic)
if processor:
try:
reply = None
# see whether pre-authorization is needed
authz_flag = req.get_header(RequestHeader.REQUIRE_AUTHZ)
require_authz = authz_flag == "true"
if require_authz:
# authorize this command!
cmd = req.get_header(RequestHeader.ADMIN_COMMAND, None)
if cmd:
user = Person(
name=req.get_header(RequestHeader.USER_NAME, ""),
org=req.get_header(RequestHeader.USER_ORG, ""),
role=req.get_header(RequestHeader.USER_ROLE, ""),
)
submitter = Person(
name=req.get_header(RequestHeader.SUBMITTER_NAME, ""),
org=req.get_header(RequestHeader.SUBMITTER_ORG, ""),
role=req.get_header(RequestHeader.SUBMITTER_ROLE, ""),
)
authz_ctx = AuthzContext(user=user, submitter=submitter, right=cmd)
authorized, err = AuthorizationService.authorize(authz_ctx)
if err:
reply = error_reply(err)
elif not authorized:
reply = error_reply("not authorized")
else:
reply = error_reply("requires authz but missing admin command")
if not reply:
reply = processor.process(req, self.app_ctx)
if reply is None:
# simply ack
reply = ok_reply()
else:
if not isinstance(reply, Message):
raise RuntimeError(f"processor for topic {topic} failed to produce valid reply")
except Exception as e:
secure_log_traceback()
reply = error_reply(f"exception_occurred: {secure_format_exception(e)}")
else:
reply = error_reply("invalid_request")
return new_cell_message({}, reply)
| NVFlare-main | nvflare/private/fed/client/admin.py |
# Copyright (c) 2021, 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 abc import ABC, abstractmethod
from nvflare.apis.client_engine_spec import ClientEngineSpec
class ClientEngineInternalSpec(ClientEngineSpec, ABC):
"""The ClientEngineInternalSpec defines the ClientEngine APIs running in the parent process."""
@abstractmethod
def get_engine_status(self):
pass
@abstractmethod
def get_client_name(self) -> str:
"""Get the ClientEngine client_name.
Returns: the client_name
"""
pass
@abstractmethod
def deploy_app(self, app_name: str, job_id: str, job_meta: dict, client_name: str, app_data) -> str:
"""Deploy the app to specified run.
Args:
app_name: FL_app name
job_id: job that the app is to be deployed to
job_meta: meta data of the job that the app belongs to
client_name: name of the client
app_data: zip data of the app
Returns:
A error message if any; empty str is okay.
"""
pass
@abstractmethod
def start_app(
self,
job_id: str,
allocated_resource: dict = None,
token: str = None,
resource_manager=None,
) -> str:
"""Starts the app for the specified run.
Args:
job_id: job_id
allocated_resource: allocated resource
token: token
resource_manager: resource manager
Returns:
A string message.
"""
pass
@abstractmethod
def abort_app(self, job_id: str) -> str:
"""Aborts the app execution for the specified run.
Returns:
A string message.
"""
pass
@abstractmethod
def abort_task(self, job_id: str) -> str:
"""Abort the client current executing task.
Returns:
A string message.
"""
pass
@abstractmethod
def delete_run(self, job_id: str) -> str:
"""Deletes the specified run.
Args:
job_id: job_id
Returns:
A string message.
"""
pass
@abstractmethod
def shutdown(self) -> str:
"""Shuts down the FL client.
Returns:
A string message.
"""
pass
@abstractmethod
def restart(self) -> str:
"""Restarts the FL client.
Returns:
A string message.
"""
pass
@abstractmethod
def get_all_job_ids(self) -> []:
"""Get all the client job_id.
Returns: list of all the job_id
"""
pass
| NVFlare-main | nvflare/private/fed/client/client_engine_internal_spec.py |
# Copyright (c) 2022, 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 json
from typing import List
from nvflare.apis.event_type import EventType
from nvflare.apis.fl_constant import FLContextKey, ReturnCode, SystemComponents
from nvflare.apis.resource_manager_spec import ResourceConsumerSpec, ResourceManagerSpec
from nvflare.apis.shareable import Shareable
from nvflare.private.admin_defs import Message
from nvflare.private.defs import ERROR_MSG_PREFIX, RequestHeader, SysCommandTopic, TrainingTopic
from nvflare.private.fed.client.admin import RequestProcessor
from nvflare.private.fed.client.client_engine_internal_spec import ClientEngineInternalSpec
from nvflare.private.scheduler_constants import ShareableHeader
from nvflare.security.logging import secure_format_exception
def _get_resource_manager(engine: ClientEngineInternalSpec):
if not isinstance(engine, ClientEngineInternalSpec):
raise ValueError("engine must be ClientEngineInternalSpec, but got {}".format(type(engine)))
resource_manager = engine.get_component(SystemComponents.RESOURCE_MANAGER)
if not isinstance(resource_manager, ResourceManagerSpec):
raise ValueError(f"resource_manager should be of type ResourceManagerSpec, but got {type(resource_manager)}.")
return resource_manager
def _get_resource_consumer(engine: ClientEngineInternalSpec):
if not isinstance(engine, ClientEngineInternalSpec):
raise ValueError("engine must be ClientEngineInternalSpec, but got {}".format(type(engine)))
resource_consumer = engine.get_component(SystemComponents.RESOURCE_CONSUMER)
if not isinstance(resource_consumer, ResourceConsumerSpec):
raise ValueError(
f"resource_consumer should be of type ResourceConsumerSpec, but got {type(resource_consumer)}."
)
return resource_consumer
class CheckResourceProcessor(RequestProcessor):
def get_topics(self) -> List[str]:
return [TrainingTopic.CHECK_RESOURCE]
def process(self, req: Message, app_ctx) -> Message:
engine = app_ctx
result = Shareable()
resource_manager = _get_resource_manager(engine)
is_resource_enough, token = False, ""
with engine.new_context() as fl_ctx:
try:
job_id = req.get_header(RequestHeader.JOB_ID, "")
resource_spec = req.body
fl_ctx.set_prop(key=FLContextKey.CLIENT_RESOURCE_SPECS, value=resource_spec, private=True, sticky=False)
fl_ctx.set_prop(FLContextKey.CURRENT_JOB_ID, job_id, private=True, sticky=False)
engine.fire_event(EventType.BEFORE_CHECK_RESOURCE_MANAGER, fl_ctx)
block_reason = fl_ctx.get_prop(FLContextKey.JOB_BLOCK_REASON)
if block_reason:
is_resource_enough = False
token = block_reason
else:
is_resource_enough, token = resource_manager.check_resources(
resource_requirement=resource_spec, fl_ctx=fl_ctx
)
except Exception:
result.set_return_code(ReturnCode.EXECUTION_EXCEPTION)
result.set_header(ShareableHeader.IS_RESOURCE_ENOUGH, is_resource_enough)
result.set_header(ShareableHeader.RESOURCE_RESERVE_TOKEN, token)
return Message(topic="reply_" + req.topic, body=result)
class StartJobProcessor(RequestProcessor):
def get_topics(self) -> List[str]:
return [TrainingTopic.START_JOB]
def process(self, req: Message, app_ctx) -> Message:
engine = app_ctx
resource_manager = _get_resource_manager(engine)
allocated_resources = None
try:
resource_spec = req.body
job_id = req.get_header(RequestHeader.JOB_ID)
token = req.get_header(ShareableHeader.RESOURCE_RESERVE_TOKEN)
except Exception as e:
msg = f"{ERROR_MSG_PREFIX}: Start job execution exception, missing required information: {secure_format_exception(e)}."
return Message(topic=f"reply_{req.topic}", body=msg)
try:
with engine.new_context() as fl_ctx:
allocated_resources = resource_manager.allocate_resources(
resource_requirement=resource_spec, token=token, fl_ctx=fl_ctx
)
if allocated_resources:
resource_consumer = _get_resource_consumer(engine)
resource_consumer.consume(allocated_resources)
result = engine.start_app(
job_id,
allocated_resource=allocated_resources,
token=token,
resource_manager=resource_manager,
)
except Exception as e:
result = f"{ERROR_MSG_PREFIX}: Start job execution exception: {secure_format_exception(e)}."
if allocated_resources:
with engine.new_context() as fl_ctx:
resource_manager.free_resources(resources=allocated_resources, token=token, fl_ctx=fl_ctx)
if not result:
result = "OK"
return Message(topic="reply_" + req.topic, body=result)
class CancelResourceProcessor(RequestProcessor):
def get_topics(self) -> List[str]:
return [TrainingTopic.CANCEL_RESOURCE]
def process(self, req: Message, app_ctx) -> Message:
engine = app_ctx
result = Shareable()
resource_manager = _get_resource_manager(engine)
with engine.new_context() as fl_ctx:
try:
resource_spec = req.body
token = req.get_header(ShareableHeader.RESOURCE_RESERVE_TOKEN)
resource_manager.cancel_resources(resource_requirement=resource_spec, token=token, fl_ctx=fl_ctx)
except Exception:
result.set_return_code(ReturnCode.EXECUTION_EXCEPTION)
return Message(topic="reply_" + req.topic, body=result)
class ReportResourcesProcessor(RequestProcessor):
def get_topics(self) -> [str]:
return [SysCommandTopic.REPORT_RESOURCES]
def process(self, req: Message, app_ctx) -> Message:
engine = app_ctx
resource_manager = _get_resource_manager(engine)
resources = resource_manager.report_resources(engine.new_context())
message = Message(topic="reply_" + req.topic, body=json.dumps(resources))
return message
| NVFlare-main | nvflare/private/fed/client/scheduler_cmds.py |
# Copyright (c) 2021, 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 logging
import threading
import time
from functools import partial
from multiprocessing.dummy import Pool as ThreadPool
from typing import List, Optional
from nvflare.apis.filter import Filter
from nvflare.apis.fl_component import FLComponent
from nvflare.apis.fl_constant import FLContextKey, SecureTrainConst, ServerCommandKey
from nvflare.apis.fl_context import FLContext
from nvflare.apis.fl_exception import FLCommunicationError
from nvflare.apis.overseer_spec import SP
from nvflare.apis.shareable import Shareable
from nvflare.apis.signal import Signal
from nvflare.fuel.f3.cellnet.cell import Cell
from nvflare.fuel.f3.cellnet.fqcn import FQCN
from nvflare.fuel.f3.cellnet.net_agent import NetAgent
from nvflare.fuel.f3.drivers.driver_params import DriverParams
from nvflare.fuel.f3.mpm import MainProcessMonitor as mpm
from nvflare.fuel.utils.argument_utils import parse_vars
from nvflare.private.defs import EngineConstant
from nvflare.security.logging import secure_format_exception
from .client_status import ClientStatus
from .communicator import Communicator
def _check_progress(remote_tasks):
if remote_tasks[0] is not None:
# shareable = fobs.loads(remote_tasks[0].payload)
shareable = remote_tasks[0].payload
return True, shareable.get_header(ServerCommandKey.TASK_NAME), shareable
else:
return False, None, None
class FederatedClientBase:
"""The client-side base implementation of federated learning.
This class provide the tools function which will be used in both FedClient and FedClientLite.
"""
def __init__(
self,
client_name,
client_args,
secure_train,
server_args=None,
retry_timeout=30,
client_state_processors: Optional[List[Filter]] = None,
handlers: Optional[List[FLComponent]] = None,
compression=None,
overseer_agent=None,
args=None,
components=None,
cell: Cell = None,
):
"""To init FederatedClientBase.
Args:
client_name: client name
client_args: client config args
secure_train: True/False to indicate secure train
server_args: server config args
retry_timeout: retry timeout
client_state_processors: client state processor filters
handlers: handlers
compression: communication compression algorithm
cell: CellNet communicator
"""
self.logger = logging.getLogger(self.__class__.__name__)
self.client_name = client_name
self.token = None
self.ssid = None
self.client_args = client_args
self.servers = server_args
self.cell = cell
self.net_agent = None
self.args = args
self.engine_create_timeout = client_args.get("engine_create_timeout", 15.0)
self.cell_check_frequency = client_args.get("cell_check_frequency", 0.005)
self.communicator = Communicator(
ssl_args=client_args,
secure_train=secure_train,
client_state_processors=client_state_processors,
compression=compression,
cell=cell,
client_register_interval=client_args.get("client_register_interval", 2.0),
timeout=client_args.get("communication_timeout", 30.0),
)
self.secure_train = secure_train
self.handlers = handlers
self.components = components
self.heartbeat_done = False
self.fl_ctx = FLContext()
self.platform = None
self.abort_signal = Signal()
self.engine = None
self.client_runner = None
self.status = ClientStatus.NOT_STARTED
self.remote_tasks = None
self.sp_established = False
self.overseer_agent = overseer_agent
self.overseer_agent = self._init_agent(args)
if secure_train:
if self.overseer_agent:
self.overseer_agent.set_secure_context(
ca_path=client_args["ssl_root_cert"],
cert_path=client_args["ssl_cert"],
prv_key_path=client_args["ssl_private_key"],
)
def start_overseer_agent(self):
if self.overseer_agent:
self.overseer_agent.start(self.overseer_callback)
def _init_agent(self, args=None):
kv_list = parse_vars(args.set)
sp = kv_list.get("sp")
if sp:
fl_ctx = FLContext()
fl_ctx.set_prop(FLContextKey.SP_END_POINT, sp)
self.overseer_agent.initialize(fl_ctx)
return self.overseer_agent
def overseer_callback(self, overseer_agent):
if overseer_agent.is_shutdown():
self.engine.shutdown()
return
sp = overseer_agent.get_primary_sp()
self.set_primary_sp(sp)
def set_sp(self, project_name, sp: SP):
if sp and sp.primary is True:
server = self.servers[project_name].get("target")
location = sp.name + ":" + sp.fl_port
if server != location:
self.servers[project_name]["target"] = location
self.sp_established = True
scheme = self.servers[project_name].get("scheme", "grpc")
scheme_location = scheme + "://" + location
if self.cell:
self.cell.change_server_root(scheme_location)
else:
self._create_cell(location, scheme)
self.logger.info(f"Got the new primary SP: {scheme_location}")
if self.ssid and self.ssid != sp.service_session_id:
self.ssid = sp.service_session_id
thread = threading.Thread(target=self._switch_ssid)
thread.start()
def _create_cell(self, location, scheme):
if self.args.job_id:
fqcn = FQCN.join([self.client_name, self.args.job_id])
parent_url = self.args.parent_url
create_internal_listener = False
else:
fqcn = self.client_name
parent_url = None
create_internal_listener = True
if self.secure_train:
root_cert = self.client_args[SecureTrainConst.SSL_ROOT_CERT]
ssl_cert = self.client_args[SecureTrainConst.SSL_CERT]
private_key = self.client_args[SecureTrainConst.PRIVATE_KEY]
credentials = {
DriverParams.CA_CERT.value: root_cert,
DriverParams.CLIENT_CERT.value: ssl_cert,
DriverParams.CLIENT_KEY.value: private_key,
}
else:
credentials = {}
self.cell = Cell(
fqcn=fqcn,
root_url=scheme + "://" + location,
secure=self.secure_train,
credentials=credentials,
create_internal_listener=create_internal_listener,
parent_url=parent_url,
)
self.cell.start()
self.communicator.cell = self.cell
self.net_agent = NetAgent(self.cell)
mpm.add_cleanup_cb(self.net_agent.close)
mpm.add_cleanup_cb(self.cell.stop)
if self.args.job_id:
start = time.time()
self.logger.info("Wait for client_runner to be created.")
while not self.client_runner:
if time.time() - start > self.engine_create_timeout:
raise RuntimeError(f"Failed get client_runner after {self.engine_create_timeout} seconds")
time.sleep(self.cell_check_frequency)
self.logger.info(f"Got client_runner after {time.time()-start} seconds")
self.client_runner.engine.cell = self.cell
else:
start = time.time()
self.logger.info("Wait for engine to be created.")
while not self.engine:
if time.time() - start > self.engine_create_timeout:
raise RuntimeError(f"Failed to get engine after {time.time()-start} seconds")
time.sleep(self.cell_check_frequency)
self.logger.info(f"Got engine after {time.time() - start} seconds")
self.engine.cell = self.cell
self.engine.admin_agent.register_cell_cb()
def _switch_ssid(self):
if self.engine:
for job_id in self.engine.get_all_job_ids():
self.engine.abort_task(job_id)
# self.register()
self.logger.info(f"Primary SP switched to new SSID: {self.ssid}")
def client_register(self, project_name):
"""Register the client to the FL server.
Args:
project_name: FL study project name.
"""
if not self.token:
try:
self.token, self.ssid = self.communicator.client_registration(
self.client_name, self.servers, project_name
)
if self.token is not None:
self.fl_ctx.set_prop(FLContextKey.CLIENT_NAME, self.client_name, private=False)
self.fl_ctx.set_prop(EngineConstant.FL_TOKEN, self.token, private=False)
self.logger.info(
"Successfully registered client:{} for project {}. Token:{} SSID:{}".format(
self.client_name, project_name, self.token, self.ssid
)
)
except FLCommunicationError:
self.communicator.heartbeat_done = True
def fetch_execute_task(self, project_name, fl_ctx: FLContext):
"""Fetch a task from the server.
Args:
project_name: FL study project name
fl_ctx: FLContext
Returns:
A CurrentTask message from server
"""
try:
self.logger.debug("Starting to fetch execute task.")
task = self.communicator.pull_task(self.servers, project_name, self.token, self.ssid, fl_ctx)
return task
except FLCommunicationError as e:
self.logger.info(secure_format_exception(e))
def push_execute_result(self, project_name, shareable: Shareable, fl_ctx: FLContext):
"""Submit execution results of a task to server.
Args:
project_name: FL study project name
shareable: Shareable object
fl_ctx: FLContext
Returns:
A FederatedSummary message from the server.
"""
try:
self.logger.info("Starting to push execute result.")
execute_task_name = fl_ctx.get_prop(FLContextKey.TASK_NAME)
return_code = self.communicator.submit_update(
self.servers,
project_name,
self.token,
self.ssid,
fl_ctx,
self.client_name,
shareable,
execute_task_name,
)
return return_code
except FLCommunicationError as e:
self.logger.info(secure_format_exception(e))
def send_heartbeat(self, project_name, interval):
try:
if self.token:
start = time.time()
while not self.engine:
time.sleep(1.0)
if time.time() - start > 60.0:
raise RuntimeError("No engine created. Failed to start the heartbeat process.")
self.communicator.send_heartbeat(
self.servers, project_name, self.token, self.ssid, self.client_name, self.engine, interval
)
except FLCommunicationError:
self.communicator.heartbeat_done = True
def quit_remote(self, project_name, fl_ctx: FLContext):
"""Sending the last message to the server before leaving.
Args:
fl_ctx: FLContext
Returns: N/A
"""
return self.communicator.quit_remote(self.servers, project_name, self.token, self.ssid, fl_ctx)
def heartbeat(self, interval):
"""Sends a heartbeat from the client to the server."""
pool = None
try:
pool = ThreadPool(len(self.servers))
return pool.map(partial(self.send_heartbeat, interval=interval), tuple(self.servers))
finally:
if pool:
pool.terminate()
def pull_task(self, fl_ctx: FLContext):
"""Fetch remote models and update the local client's session."""
pool = None
try:
pool = ThreadPool(len(self.servers))
self.remote_tasks = pool.map(partial(self.fetch_execute_task, fl_ctx=fl_ctx), tuple(self.servers))
pull_success, task_name, shareable = _check_progress(self.remote_tasks)
# TODO: if some of the servers failed
return pull_success, task_name, shareable
finally:
if pool:
pool.terminate()
def push_results(self, shareable: Shareable, fl_ctx: FLContext):
"""Push the local model to multiple servers."""
pool = None
try:
pool = ThreadPool(len(self.servers))
return pool.map(partial(self.push_execute_result, shareable=shareable, fl_ctx=fl_ctx), tuple(self.servers))
finally:
if pool:
pool.terminate()
def register(self):
"""Push the local model to multiple servers."""
pool = None
try:
pool = ThreadPool(len(self.servers))
return pool.map(self.client_register, tuple(self.servers))
finally:
if pool:
pool.terminate()
def set_primary_sp(self, sp):
pool = None
try:
pool = ThreadPool(len(self.servers))
return pool.map(partial(self.set_sp, sp=sp), tuple(self.servers))
finally:
if pool:
pool.terminate()
def run_heartbeat(self, interval):
"""Periodically runs the heartbeat."""
try:
self.heartbeat(interval)
except:
self.logger.error("Failed to start run_heartbeat.")
def start_heartbeat(self, interval=30):
heartbeat_thread = threading.Thread(target=self.run_heartbeat, args=[interval])
heartbeat_thread.start()
def logout_client(self, fl_ctx: FLContext):
"""Logout the client from the server.
Args:
fl_ctx: FLContext
Returns: N/A
"""
pool = None
try:
pool = ThreadPool(len(self.servers))
return pool.map(partial(self.quit_remote, fl_ctx=fl_ctx), tuple(self.servers))
finally:
if pool:
pool.terminate()
def set_client_engine(self, engine):
self.engine = engine
def set_client_runner(self, client_runner):
self.client_runner = client_runner
def stop_cell(self):
"""Stop the cell communication"""
if self.communicator.cell:
self.communicator.cell.stop()
def close(self):
"""Quit the remote federated server, close the local session."""
self.terminate()
if self.engine:
fl_ctx = self.engine.new_context()
else:
fl_ctx = FLContext()
self.logout_client(fl_ctx)
self.logger.info(f"Logout client: {self.client_name} from server.")
return 0
def terminate(self):
"""Terminating the local client session."""
self.logger.info(f"Shutting down client run: {self.client_name}")
if self.overseer_agent:
self.overseer_agent.end()
| NVFlare-main | nvflare/private/fed/client/fed_client_base.py |
# Copyright (c) 2021, 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 fnmatch
import threading
import time
from nvflare.apis.event_type import EventType
from nvflare.apis.executor import Executor
from nvflare.apis.fl_component import FLComponent
from nvflare.apis.fl_constant import ConfigVarName, FilterKey, FLContextKey, ReservedKey, ReservedTopic, ReturnCode
from nvflare.apis.fl_context import FLContext
from nvflare.apis.fl_exception import UnsafeJobError
from nvflare.apis.shareable import ReservedHeaderKey, Shareable, make_reply
from nvflare.apis.signal import Signal
from nvflare.apis.utils.fl_context_utils import add_job_audit_event
from nvflare.apis.utils.task_utils import apply_filters
from nvflare.fuel.utils.config_service import ConfigService
from nvflare.private.defs import SpecialTaskName, TaskConstant
from nvflare.private.fed.client.client_engine_executor_spec import ClientEngineExecutorSpec, TaskAssignment
from nvflare.private.json_configer import ConfigError
from nvflare.private.privacy_manager import Scope
from nvflare.security.logging import secure_format_exception
from nvflare.widgets.info_collector import GroupInfoCollector, InfoCollector
class TaskRouter:
def __init__(self):
self.task_table = {}
self.patterns = []
@staticmethod
def _is_pattern(p: str):
return "*" in p
def add_executor(self, tasks: list, executor: Executor):
for t in tasks:
assert isinstance(t, str)
if t in self.task_table:
raise ConfigError(f'multiple executors defined for task "{t}"')
self.task_table[t] = executor
if self._is_pattern(t):
self.patterns.append((t, executor))
def route(self, task_name: str):
e = self.task_table.get(task_name)
if e:
return e
# check patterns
for p, e in self.patterns:
if fnmatch.fnmatch(task_name, p):
return e
return None
class ClientRunnerConfig(object):
def __init__(
self,
task_router: TaskRouter,
task_data_filters: dict, # task_name => list of filters
task_result_filters: dict, # task_name => list of filters
handlers=None, # list of event handlers
components=None, # dict of extra python objects: id => object
default_task_fetch_interval: float = 0.5,
):
"""To init ClientRunnerConfig.
Args:
task_router: TaskRouter object to find executor for a task
task_data_filters: task_name => list of data filters
task_result_filters: task_name => list of result filters
handlers: list of event handlers
components: dict of extra python objects: id => object
default_task_fetch_interval: default task fetch interval before getting the correct value from server.
default is set to 0.5.
"""
self.task_router = task_router
self.task_data_filters = task_data_filters
self.task_result_filters = task_result_filters
self.handlers = handlers
self.components = components
self.default_task_fetch_interval = default_task_fetch_interval
if not components:
self.components = {}
if not handlers:
self.handlers = []
def add_component(self, comp_id: str, component: object):
if not isinstance(comp_id, str):
raise TypeError(f"component id must be str but got {type(comp_id)}")
if comp_id in self.components:
raise ValueError(f"duplicate component id {comp_id}")
self.components[comp_id] = component
if isinstance(component, FLComponent):
self.handlers.append(component)
class ClientRunner(FLComponent):
def __init__(
self,
config: ClientRunnerConfig,
job_id,
engine: ClientEngineExecutorSpec,
):
"""Initializes the ClientRunner.
Args:
config: ClientRunnerConfig
job_id: job id
engine: ClientEngine object
"""
FLComponent.__init__(self)
self.task_router = config.task_router
self.task_data_filters = config.task_data_filters
self.task_result_filters = config.task_result_filters
self.default_task_fetch_interval = config.default_task_fetch_interval
self.job_id = job_id
self.engine = engine
self.run_abort_signal = Signal()
self.task_lock = threading.Lock()
self.running_tasks = {} # task_id => TaskAssignment
self._register_aux_message_handlers(engine)
def find_executor(self, task_name):
return self.task_router.route(task_name)
def _register_aux_message_handlers(self, engine):
engine.register_aux_message_handler(topic=ReservedTopic.END_RUN, message_handle_func=self._handle_end_run)
engine.register_aux_message_handler(topic=ReservedTopic.DO_TASK, message_handle_func=self._handle_do_task)
@staticmethod
def _reply_and_audit(reply: Shareable, ref, msg, fl_ctx: FLContext) -> Shareable:
audit_event_id = add_job_audit_event(fl_ctx=fl_ctx, ref=ref, msg=msg)
reply.set_header(ReservedKey.AUDIT_EVENT_ID, audit_event_id)
return reply
def _process_task(self, task: TaskAssignment, fl_ctx: FLContext) -> Shareable:
if fl_ctx.is_job_unsafe():
return make_reply(ReturnCode.UNSAFE_JOB)
with self.task_lock:
self.running_tasks[task.task_id] = task
abort_signal = Signal(parent=self.run_abort_signal)
try:
reply = self._do_process_task(task, fl_ctx, abort_signal)
except Exception as ex:
self.log_exception(fl_ctx, secure_format_exception(ex))
reply = make_reply(ReturnCode.EXECUTION_EXCEPTION)
with self.task_lock:
self.running_tasks.pop(task.task_id, None)
if not isinstance(reply, Shareable):
self.log_error(fl_ctx, f"task reply must be Shareable, but got {type(reply)}")
reply = make_reply(ReturnCode.EXECUTION_EXCEPTION)
cookie_jar = task.data.get_cookie_jar()
if cookie_jar:
reply.set_cookie_jar(cookie_jar)
reply.set_header(ReservedHeaderKey.TASK_NAME, task.name)
return reply
def _do_process_task(self, task: TaskAssignment, fl_ctx: FLContext, abort_signal: Signal) -> Shareable:
if not isinstance(task.data, Shareable):
self.log_error(fl_ctx, f"got invalid task data in assignment: expect Shareable, but got {type(task.data)}")
return make_reply(ReturnCode.BAD_TASK_DATA)
fl_ctx.set_prop(FLContextKey.TASK_DATA, value=task.data, private=True, sticky=False)
fl_ctx.set_prop(FLContextKey.TASK_NAME, value=task.name, private=True, sticky=False)
fl_ctx.set_prop(FLContextKey.TASK_ID, value=task.task_id, private=True, sticky=False)
server_audit_event_id = task.data.get_header(ReservedKey.AUDIT_EVENT_ID, "")
add_job_audit_event(fl_ctx=fl_ctx, ref=server_audit_event_id, msg="received task from server")
peer_ctx = fl_ctx.get_peer_context()
if not peer_ctx:
self.log_error(fl_ctx, "missing peer context in Server task assignment")
return self._reply_and_audit(
reply=make_reply(ReturnCode.MISSING_PEER_CONTEXT),
ref=server_audit_event_id,
fl_ctx=fl_ctx,
msg=f"submit result: {ReturnCode.MISSING_PEER_CONTEXT}",
)
if not isinstance(peer_ctx, FLContext):
self.log_error(
fl_ctx,
"bad peer context in Server task assignment: expects FLContext but got {}".format(type(peer_ctx)),
)
return self._reply_and_audit(
reply=make_reply(ReturnCode.BAD_PEER_CONTEXT),
ref=server_audit_event_id,
fl_ctx=fl_ctx,
msg=f"submit result: {ReturnCode.BAD_PEER_CONTEXT}",
)
task.data.set_peer_props(peer_ctx.get_all_public_props())
peer_job_id = peer_ctx.get_job_id()
if peer_job_id != self.job_id:
self.log_error(fl_ctx, "bad task assignment: not for the same job_id")
return self._reply_and_audit(
reply=make_reply(ReturnCode.RUN_MISMATCH),
ref=server_audit_event_id,
fl_ctx=fl_ctx,
msg=f"submit result: {ReturnCode.RUN_MISMATCH}",
)
executor = self.find_executor(task.name)
if not executor:
self.log_error(fl_ctx, f"bad task assignment: no executor available for task {task.name}")
return self._reply_and_audit(
reply=make_reply(ReturnCode.TASK_UNKNOWN),
ref=server_audit_event_id,
fl_ctx=fl_ctx,
msg=f"submit result: {ReturnCode.TASK_UNKNOWN}",
)
executor_name = executor.__class__.__name__
self.log_debug(fl_ctx, "firing event EventType.BEFORE_TASK_DATA_FILTER")
self.fire_event(EventType.BEFORE_TASK_DATA_FILTER, fl_ctx)
task_data = task.data
try:
filter_name = Scope.TASK_DATA_FILTERS_NAME
task_data = apply_filters(filter_name, task_data, fl_ctx, self.task_data_filters, task.name, FilterKey.IN)
except UnsafeJobError:
self.log_exception(fl_ctx, "UnsafeJobError from Task Data Filters")
executor.unsafe = True
fl_ctx.set_job_is_unsafe()
self.run_abort_signal.trigger(True)
return self._reply_and_audit(
reply=make_reply(ReturnCode.UNSAFE_JOB),
ref=server_audit_event_id,
fl_ctx=fl_ctx,
msg=f"submit result: {ReturnCode.UNSAFE_JOB}",
)
except Exception as e:
self.log_exception(fl_ctx, f"Processing error from Task Data Filters : {secure_format_exception(e)}")
return self._reply_and_audit(
reply=make_reply(ReturnCode.TASK_DATA_FILTER_ERROR),
ref=server_audit_event_id,
fl_ctx=fl_ctx,
msg=f"submit result: {ReturnCode.TASK_DATA_FILTER_ERROR}",
)
if not isinstance(task_data, Shareable):
self.log_error(
fl_ctx, "task data was converted to wrong type: expect Shareable but got {}".format(type(task_data))
)
return self._reply_and_audit(
reply=make_reply(ReturnCode.TASK_DATA_FILTER_ERROR),
ref=server_audit_event_id,
fl_ctx=fl_ctx,
msg=f"submit result: {ReturnCode.TASK_DATA_FILTER_ERROR}",
)
task.data = task_data
self.log_debug(fl_ctx, "firing event EventType.AFTER_TASK_DATA_FILTER")
fl_ctx.set_prop(FLContextKey.TASK_DATA, value=task.data, private=True, sticky=False)
self.fire_event(EventType.AFTER_TASK_DATA_FILTER, fl_ctx)
self.log_debug(fl_ctx, "firing event EventType.BEFORE_TASK_EXECUTION")
fl_ctx.set_prop(FLContextKey.TASK_DATA, value=task.data, private=True, sticky=False)
self.fire_event(EventType.BEFORE_TASK_EXECUTION, fl_ctx)
try:
self.log_info(fl_ctx, f"invoking task executor {executor_name}")
add_job_audit_event(fl_ctx=fl_ctx, msg=f"invoked executor {executor_name}")
try:
reply = executor.execute(task.name, task.data, fl_ctx, abort_signal)
finally:
if abort_signal.triggered:
return self._reply_and_audit(
reply=make_reply(ReturnCode.TASK_ABORTED),
ref=server_audit_event_id,
fl_ctx=fl_ctx,
msg=f"submit result: {ReturnCode.TASK_ABORTED}",
)
if not isinstance(reply, Shareable):
self.log_error(
fl_ctx, f"bad result generated by executor {executor_name}: must be Shareable but got {type(reply)}"
)
return self._reply_and_audit(
reply=make_reply(ReturnCode.EXECUTION_RESULT_ERROR),
ref=server_audit_event_id,
fl_ctx=fl_ctx,
msg=f"submit result: {ReturnCode.EXECUTION_RESULT_ERROR}",
)
except RuntimeError as e:
self.log_exception(
fl_ctx, f"RuntimeError from executor {executor_name}: {secure_format_exception(e)}: Aborting the job!"
)
return self._reply_and_audit(
reply=make_reply(ReturnCode.EXECUTION_RESULT_ERROR),
ref=server_audit_event_id,
fl_ctx=fl_ctx,
msg=f"submit result: {ReturnCode.EXECUTION_RESULT_ERROR}",
)
except UnsafeJobError:
self.log_exception(fl_ctx, f"UnsafeJobError from executor {executor_name}")
executor.unsafe = True
fl_ctx.set_job_is_unsafe()
return self._reply_and_audit(
reply=make_reply(ReturnCode.UNSAFE_JOB),
ref=server_audit_event_id,
fl_ctx=fl_ctx,
msg=f"submit result: {ReturnCode.UNSAFE_JOB}",
)
except Exception as e:
self.log_exception(fl_ctx, f"Processing error from executor {executor_name}: {secure_format_exception(e)}")
return self._reply_and_audit(
reply=make_reply(ReturnCode.EXECUTION_EXCEPTION),
ref=server_audit_event_id,
fl_ctx=fl_ctx,
msg=f"submit result: {ReturnCode.EXECUTION_EXCEPTION}",
)
fl_ctx.set_prop(FLContextKey.TASK_RESULT, value=reply, private=True, sticky=False)
self.log_debug(fl_ctx, "firing event EventType.AFTER_TASK_EXECUTION")
self.fire_event(EventType.AFTER_TASK_EXECUTION, fl_ctx)
self.log_debug(fl_ctx, "firing event EventType.BEFORE_TASK_RESULT_FILTER")
self.fire_event(EventType.BEFORE_TASK_RESULT_FILTER, fl_ctx)
try:
filter_name = Scope.TASK_RESULT_FILTERS_NAME
reply = apply_filters(filter_name, reply, fl_ctx, self.task_result_filters, task.name, FilterKey.OUT)
except UnsafeJobError:
self.log_exception(fl_ctx, "UnsafeJobError from Task Result Filters")
executor.unsafe = True
fl_ctx.set_job_is_unsafe()
return self._reply_and_audit(
reply=make_reply(ReturnCode.UNSAFE_JOB),
ref=server_audit_event_id,
fl_ctx=fl_ctx,
msg=f"submit result: {ReturnCode.UNSAFE_JOB}",
)
except Exception as e:
self.log_exception(fl_ctx, f"Processing error in Task Result Filter : {secure_format_exception(e)}")
return self._reply_and_audit(
reply=make_reply(ReturnCode.TASK_RESULT_FILTER_ERROR),
ref=server_audit_event_id,
fl_ctx=fl_ctx,
msg=f"submit result: {ReturnCode.TASK_RESULT_FILTER_ERROR}",
)
if not isinstance(reply, Shareable):
self.log_error(
fl_ctx, "task result was converted to wrong type: expect Shareable but got {}".format(type(reply))
)
return self._reply_and_audit(
reply=make_reply(ReturnCode.TASK_RESULT_FILTER_ERROR),
ref=server_audit_event_id,
fl_ctx=fl_ctx,
msg=f"submit result: {ReturnCode.TASK_RESULT_FILTER_ERROR}",
)
fl_ctx.set_prop(FLContextKey.TASK_RESULT, value=reply, private=True, sticky=False)
self.log_debug(fl_ctx, "firing event EventType.AFTER_TASK_RESULT_FILTER")
self.fire_event(EventType.AFTER_TASK_RESULT_FILTER, fl_ctx)
self.log_info(fl_ctx, "finished processing task")
if not isinstance(reply, Shareable):
self.log_error(
fl_ctx, "task processing error: expects result to be Shareable, but got {}".format(type(reply))
)
return self._reply_and_audit(
reply=make_reply(ReturnCode.EXECUTION_RESULT_ERROR),
ref=server_audit_event_id,
fl_ctx=fl_ctx,
msg=f"submit result: {ReturnCode.EXECUTION_RESULT_ERROR}",
)
return self._reply_and_audit(reply=reply, ref=server_audit_event_id, fl_ctx=fl_ctx, msg="submit result OK")
def _try_run(self):
while not self.run_abort_signal.triggered:
with self.engine.new_context() as fl_ctx:
task_fetch_interval, _ = self.fetch_and_run_one_task(fl_ctx)
time.sleep(task_fetch_interval)
def fetch_and_run_one_task(self, fl_ctx) -> (float, bool):
"""Fetches and runs a task.
Returns:
A tuple of (task_fetch_interval, task_processed).
"""
default_task_fetch_interval = self.default_task_fetch_interval
self.log_debug(fl_ctx, "fetching task from server ...")
task = self.engine.get_task_assignment(fl_ctx)
if not task:
self.log_debug(fl_ctx, "no task received - will try in {} secs".format(default_task_fetch_interval))
return default_task_fetch_interval, False
elif task.name == SpecialTaskName.END_RUN:
self.log_info(fl_ctx, "server asked to end the run")
self.run_abort_signal.trigger(True)
return default_task_fetch_interval, False
elif task.name == SpecialTaskName.TRY_AGAIN:
task_data = task.data
task_fetch_interval = default_task_fetch_interval
if task_data and isinstance(task_data, Shareable):
task_fetch_interval = task_data.get_header(TaskConstant.WAIT_TIME, task_fetch_interval)
self.log_debug(fl_ctx, "server asked to try again - will try in {} secs".format(task_fetch_interval))
return task_fetch_interval, False
self.log_info(fl_ctx, f"got task assignment: name={task.name}, id={task.task_id}")
task_data = task.data
if not isinstance(task_data, Shareable):
raise TypeError("task_data must be Shareable, but got {}".format(type(task_data)))
task_fetch_interval = task_data.get_header(TaskConstant.WAIT_TIME, default_task_fetch_interval)
task_reply = self._process_task(task, fl_ctx)
self.log_debug(fl_ctx, "firing event EventType.BEFORE_SEND_TASK_RESULT")
self.fire_event(EventType.BEFORE_SEND_TASK_RESULT, fl_ctx)
reply_sent = self.engine.send_task_result(task_reply, fl_ctx)
if reply_sent:
self.log_info(fl_ctx, "result sent to server for task: name={}, id={}".format(task.name, task.task_id))
else:
self.log_error(
fl_ctx,
"failed to send result to server for task: name={}, id={}".format(task.name, task.task_id),
)
self.log_debug(fl_ctx, "firing event EventType.AFTER_SEND_TASK_RESULT")
self.fire_event(EventType.AFTER_SEND_TASK_RESULT, fl_ctx)
return task_fetch_interval, True
def run(self, app_root, args):
self.init_run(app_root, args)
try:
self._try_run()
except Exception as e:
with self.engine.new_context() as fl_ctx:
self.log_exception(fl_ctx, f"processing error in RUN execution: {secure_format_exception(e)}")
finally:
self.end_run_events_sequence()
with self.task_lock:
self.running_tasks = {}
def init_run(self, app_root, args):
sync_timeout = ConfigService.get_float_var(
name=ConfigVarName.RUNNER_SYNC_TIMEOUT,
default=2.0,
)
max_sync_tries = ConfigService.get_int_var(
name=ConfigVarName.MAX_RUNNER_SYNC_TRIES,
default=30,
)
target = "server"
synced = False
sync_start = time.time()
with self.engine.new_context() as fl_ctx:
for i in range(max_sync_tries):
# sync with server runner before starting
time.sleep(0.5)
resp = self.engine.send_aux_request(
targets=[target],
topic=ReservedTopic.SYNC_RUNNER,
request=Shareable(),
timeout=sync_timeout,
fl_ctx=fl_ctx,
optional=True,
secure=False,
)
if not resp:
continue
reply = resp.get(target)
if not reply:
continue
assert isinstance(reply, Shareable)
rc = reply.get_return_code()
if rc == ReturnCode.OK:
synced = True
break
if not synced:
raise RuntimeError(f"cannot sync with Server Runner after {max_sync_tries} tries")
self.log_info(fl_ctx, f"synced to Server Runner in {time.time()-sync_start} seconds")
self.fire_event(EventType.ABOUT_TO_START_RUN, fl_ctx)
fl_ctx.set_prop(FLContextKey.APP_ROOT, app_root, sticky=True)
fl_ctx.set_prop(FLContextKey.ARGS, args, sticky=True)
fl_ctx.set_prop(ReservedKey.RUN_ABORT_SIGNAL, self.run_abort_signal, private=True, sticky=True)
self.log_debug(fl_ctx, "firing event EventType.START_RUN")
self.fire_event(EventType.START_RUN, fl_ctx)
self.log_info(fl_ctx, "client runner started")
def end_run_events_sequence(self):
with self.engine.new_context() as fl_ctx:
self.log_info(fl_ctx, "started end-run events sequence")
with self.task_lock:
num_running_tasks = len(self.running_tasks)
if num_running_tasks > 0:
self.fire_event(EventType.ABORT_TASK, fl_ctx)
self.log_info(fl_ctx, "fired ABORT_TASK event to abort all running tasks")
self.fire_event(EventType.ABOUT_TO_END_RUN, fl_ctx)
self.log_info(fl_ctx, "ABOUT_TO_END_RUN fired")
self.fire_event(EventType.END_RUN, fl_ctx)
self.log_info(fl_ctx, "END_RUN fired")
def abort(self):
"""To Abort the current run.
Returns: N/A
"""
# This is caused by the abort_job command.
with self.engine.new_context() as fl_ctx:
self.log_info(fl_ctx, "ABORT (RUN) command received")
self.run_abort_signal.trigger(True)
def handle_event(self, event_type: str, fl_ctx: FLContext):
if event_type == InfoCollector.EVENT_TYPE_GET_STATS:
collector = fl_ctx.get_prop(InfoCollector.CTX_KEY_STATS_COLLECTOR)
if collector:
if not isinstance(collector, GroupInfoCollector):
raise TypeError("collector must be GroupInfoCollector, but got {}".format(type(collector)))
with self.task_lock:
current_tasks = []
for _, task in self.running_tasks.items():
current_tasks.append(task.name)
collector.set_info(
group_name="ClientRunner",
info={"job_id": self.job_id, "current_tasks": current_tasks},
)
elif event_type == EventType.FATAL_SYSTEM_ERROR:
# This happens when a task calls system_panic().
reason = fl_ctx.get_prop(key=FLContextKey.EVENT_DATA, default="")
self.log_error(fl_ctx, "Stopped ClientRunner due to FATAL_SYSTEM_ERROR: {}".format(reason))
self.run_abort_signal.trigger(True)
def _handle_end_run(self, topic: str, request: Shareable, fl_ctx: FLContext) -> Shareable:
# This happens when the controller on server asks the client to end the job.
# Usually at the end of the workflow.
self.log_info(fl_ctx, "received request from Server to end current RUN")
self.run_abort_signal.trigger(True)
return make_reply(ReturnCode.OK)
def _handle_do_task(self, topic: str, request: Shareable, fl_ctx: FLContext) -> Shareable:
self.log_info(fl_ctx, "received aux request to do task")
task_name = request.get_header(ReservedHeaderKey.TASK_NAME)
task_id = request.get_header(ReservedHeaderKey.TASK_ID)
task = TaskAssignment(name=task_name, task_id=task_id, data=request)
reply = self._process_task(task, fl_ctx)
return reply
| NVFlare-main | nvflare/private/fed/client/client_runner.py |
# Copyright (c) 2022, 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 logging
import os
from nvflare.apis.fl_constant import FLContextKey
from nvflare.apis.fl_context import FLContext
from nvflare.apis.workspace import Workspace
from nvflare.private.defs import EngineConstant
from nvflare.private.fed.app.fl_conf import create_privacy_manager
from nvflare.private.fed.client.client_json_config import ClientJsonConfigurator
from nvflare.private.fed.client.client_run_manager import ClientRunManager
from nvflare.private.fed.client.client_runner import ClientRunner
from nvflare.private.fed.client.client_status import ClientStatus
from nvflare.private.fed.client.command_agent import CommandAgent
from nvflare.private.fed.runner import Runner
from nvflare.private.fed.utils.fed_utils import authorize_build_component
from nvflare.private.privacy_manager import PrivacyService
class ClientAppRunner(Runner):
logger = logging.getLogger("ClientAppRunner")
def __init__(self, time_out=60.0) -> None:
super().__init__()
self.command_agent = None
self.timeout = time_out
self.client_runner = None
def start_run(self, app_root, args, config_folder, federated_client, secure_train, sp, event_handlers):
self.client_runner = self.create_client_runner(
app_root, args, config_folder, federated_client, secure_train, event_handlers
)
federated_client.set_client_runner(self.client_runner)
federated_client.set_primary_sp(sp)
with self.client_runner.engine.new_context() as fl_ctx:
self.start_command_agent(args, federated_client, fl_ctx)
self.sync_up_parents_process(federated_client)
federated_client.start_overseer_agent()
federated_client.status = ClientStatus.STARTED
self.client_runner.run(app_root, args)
federated_client.stop_cell()
@staticmethod
def _set_fl_context(fl_ctx: FLContext, app_root, args, workspace, secure_train):
fl_ctx.set_prop(FLContextKey.CLIENT_NAME, args.client_name, private=False)
fl_ctx.set_prop(EngineConstant.FL_TOKEN, args.token, private=False)
fl_ctx.set_prop(FLContextKey.WORKSPACE_ROOT, args.workspace, private=True)
fl_ctx.set_prop(FLContextKey.ARGS, args, sticky=True)
fl_ctx.set_prop(FLContextKey.APP_ROOT, app_root, private=True, sticky=True)
fl_ctx.set_prop(FLContextKey.WORKSPACE_OBJECT, workspace, private=True)
fl_ctx.set_prop(FLContextKey.SECURE_MODE, secure_train, private=True, sticky=True)
fl_ctx.set_prop(FLContextKey.CURRENT_RUN, args.job_id, private=False, sticky=True)
fl_ctx.set_prop(FLContextKey.CURRENT_JOB_ID, args.job_id, private=False, sticky=True)
def create_client_runner(self, app_root, args, config_folder, federated_client, secure_train, event_handlers=None):
workspace = Workspace(args.workspace, args.client_name, config_folder)
fl_ctx = FLContext()
self._set_fl_context(fl_ctx, app_root, args, workspace, secure_train)
client_config_file_name = os.path.join(app_root, args.client_config)
conf = ClientJsonConfigurator(
config_file_name=client_config_file_name, app_root=app_root, args=args, kv_list=args.set
)
if event_handlers:
conf.set_component_build_authorizer(authorize_build_component, fl_ctx=fl_ctx, event_handlers=event_handlers)
conf.configure()
runner_config = conf.runner_config
# configure privacy control!
privacy_manager = create_privacy_manager(workspace, names_only=False)
if privacy_manager.is_policy_defined():
if privacy_manager.components:
for cid, comp in privacy_manager.components.items():
runner_config.add_component(cid, comp)
# initialize Privacy Service
PrivacyService.initialize(privacy_manager)
run_manager = self.create_run_manager(args, conf, federated_client, workspace)
federated_client.run_manager = run_manager
federated_client.handlers = conf.runner_config.handlers
with run_manager.new_context() as fl_ctx:
self._set_fl_context(fl_ctx, app_root, args, workspace, secure_train)
client_runner = ClientRunner(config=conf.runner_config, job_id=args.job_id, engine=run_manager)
run_manager.add_handler(client_runner)
fl_ctx.set_prop(FLContextKey.RUNNER, client_runner, private=True)
# self.start_command_agent(args, client_runner, federated_client, fl_ctx)
return client_runner
def create_run_manager(self, args, conf, federated_client, workspace):
return ClientRunManager(
client_name=args.client_name,
job_id=args.job_id,
workspace=workspace,
client=federated_client,
components=conf.runner_config.components,
handlers=conf.runner_config.handlers,
conf=conf,
)
def start_command_agent(self, args, federated_client, fl_ctx):
# Start the command agent
self.command_agent = CommandAgent(federated_client)
self.command_agent.start(fl_ctx)
def sync_up_parents_process(self, federated_client):
run_manager = federated_client.run_manager
with run_manager.new_context() as fl_ctx:
run_manager.get_all_clients_from_server(fl_ctx)
def close(self):
if self.command_agent:
self.command_agent.shutdown()
def stop(self):
if self.client_runner:
self.client_runner.abort()
| NVFlare-main | nvflare/private/fed/client/client_app_runner.py |
# Copyright (c) 2021, 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 os
import re
from nvflare.apis.executor import Executor
from nvflare.apis.fl_component import FLComponent
from nvflare.apis.fl_constant import SystemConfigs
from nvflare.fuel.utils.argument_utils import parse_vars
from nvflare.fuel.utils.config_service import ConfigService
from nvflare.fuel.utils.json_scanner import Node
from nvflare.private.fed_json_config import FedJsonConfigurator
from nvflare.private.json_configer import ConfigContext, ConfigError
from .client_runner import ClientRunnerConfig, TaskRouter
class _ExecutorDef(object):
def __init__(self):
self.tasks = []
self.executor = None
FL_PACKAGES = ["nvflare"]
FL_MODULES = ["apis", "app_common", "widgets", "app_opt"]
class ClientJsonConfigurator(FedJsonConfigurator):
def __init__(self, config_file_name: str, args, app_root: str, kv_list=None, exclude_libs=True):
"""To init the ClientJsonConfigurator.
Args:
config_file_name: config file name
exclude_libs: True/False to exclude the libs folder
"""
self.args = args
self.app_root = app_root
base_pkgs = FL_PACKAGES
module_names = FL_MODULES
FedJsonConfigurator.__init__(
self,
config_file_name=config_file_name,
base_pkgs=base_pkgs,
module_names=module_names,
exclude_libs=exclude_libs,
is_server=False,
)
if kv_list:
assert isinstance(kv_list, list), "cmd_vars must be list, but got {}".format(type(kv_list))
self.cmd_vars = parse_vars(kv_list)
else:
self.cmd_vars = {}
self.config_files = [config_file_name]
self.runner_config = None
self.executors = []
self.current_exe = None
self._default_task_fetch_interval = 0.5
def process_config_element(self, config_ctx: ConfigContext, node: Node):
FedJsonConfigurator.process_config_element(self, config_ctx, node)
element = node.element
path = node.path()
# default task fetch interval
if re.search(r"default_task_fetch_interval", path):
if not isinstance(element, int) and not isinstance(element, float):
raise ConfigError('"default_task_fetch_interval" must be a number, but got {}'.format(type(element)))
if element <= 0:
raise ConfigError('"default_task_fetch_interval" must > 0, but got {}'.format(element))
self._default_task_fetch_interval = element
return
# executors
if re.search(r"^executors\.#[0-9]+$", path):
self.current_exe = _ExecutorDef()
node.props["data"] = self.current_exe
node.exit_cb = self._process_executor_def
return
if re.search(r"^executors\.#[0-9]+\.tasks$", path):
self.current_exe.tasks = element
return
if re.search(r"^executors\.#[0-9]+\.executor$", path):
self.current_exe.executor = self.authorize_and_build_component(element, config_ctx, node)
return
def build_component(self, config_dict):
t = super().build_component(config_dict)
if isinstance(t, FLComponent):
self.handlers.append(t)
return t
def _process_executor_def(self, node: Node):
e = node.props["data"]
if not isinstance(e, _ExecutorDef):
raise TypeError("e must be _ExecutorDef but got {}".format(type(e)))
self.validate_tasks(e.tasks)
if not isinstance(e.executor, Executor):
raise ConfigError('"executor" must be an Executor object but got {}'.format(type(e.executor)))
self.executors.append(e)
def finalize_config(self, config_ctx: ConfigContext):
FedJsonConfigurator.finalize_config(self, config_ctx)
if len(self.executors) <= 0:
raise ConfigError("executors are not specified")
task_router = TaskRouter()
for e in self.executors:
task_router.add_executor(e.tasks, e.executor)
self.runner_config = ClientRunnerConfig(
task_router=task_router,
task_data_filters=self.data_filter_table,
task_result_filters=self.result_filter_table,
components=self.components,
handlers=self.handlers,
default_task_fetch_interval=self._default_task_fetch_interval,
)
ConfigService.initialize(
section_files={SystemConfigs.APPLICATION_CONF: os.path.basename(self.config_files[0])},
config_path=[self.app_root],
parsed_args=self.args,
var_dict=self.cmd_vars,
)
| NVFlare-main | nvflare/private/fed/client/client_json_config.py |
# Copyright (c) 2021, 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.
"""The client of the federated training process."""
from typing import List, Optional
from nvflare.apis.event_type import EventType
from nvflare.apis.executor import Executor
from nvflare.apis.filter import Filter
from nvflare.apis.fl_component import FLComponent
from nvflare.apis.fl_constant import FLContextKey
from nvflare.apis.fl_context import FLContext
from nvflare.fuel.f3.cellnet.cell import Cell
from nvflare.private.defs import SpecialTaskName
from nvflare.private.event import fire_event
from .fed_client_base import FederatedClientBase
class FederatedClient(FederatedClientBase):
"""Federated client-side implementation."""
def __init__(
self,
client_name,
client_args,
secure_train,
server_args=None,
retry_timeout=30,
client_state_processors: Optional[List[Filter]] = None,
handlers: Optional[List[FLComponent]] = None,
executors: Optional[List[Executor]] = None,
compression=None,
overseer_agent=None,
args=None,
components=None,
cell: Cell = None,
):
"""To init FederatedClient.
Args:
client_name: client name
client_args: client config args
secure_train: True/False to indicate secure train
server_args: server config args
retry_timeout: retry timeout seconds
client_state_processors: Client state processor filters
handlers: handlers
executors: executors
compression: communication compression algorithm
cell (object): CellNet communicator
"""
# We call the base implementation directly.
super().__init__(
client_name=client_name,
client_args=client_args,
secure_train=secure_train,
server_args=server_args,
retry_timeout=retry_timeout,
client_state_processors=client_state_processors,
handlers=handlers,
compression=compression,
overseer_agent=overseer_agent,
args=args,
components=components,
cell=cell,
)
self.executors = executors
def fetch_task(self, fl_ctx: FLContext):
fire_event(EventType.BEFORE_PULL_TASK, self.handlers, fl_ctx)
pull_success, task_name, shareable = self.pull_task(fl_ctx)
fire_event(EventType.AFTER_PULL_TASK, self.handlers, fl_ctx)
if task_name == SpecialTaskName.TRY_AGAIN:
self.logger.debug(f"pull_task completed. Task name:{task_name} Status:{pull_success} ")
else:
self.logger.info(f"pull_task completed. Task name:{task_name} Status:{pull_success} ")
return pull_success, task_name, shareable
def extract_shareable(self, responses, fl_ctx: FLContext):
# shareable = Shareable()
# peer_context = FLContext()
# for item in responses:
# shareable = shareable.from_bytes(proto_to_bytes(item.data.params["data"]))
# peer_context = fobs.loads(proto_to_bytes(item.data.params["fl_context"]))
# shareable = fobs.loads(responses.payload)
peer_context = responses.get_header(FLContextKey.PEER_CONTEXT)
fl_ctx.set_peer_context(peer_context)
responses.set_peer_props(peer_context.get_all_public_props())
return responses
| NVFlare-main | nvflare/private/fed/client/fed_client.py |
# Copyright (c) 2022, 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 logging
import threading
import time
from typing import Any, Dict, Optional
from requests import Request, RequestException, Response, Session, codes
from requests.adapters import HTTPAdapter
from nvflare.apis.overseer_spec import SP, OverseerAgent
from nvflare.security.logging import secure_format_exception
class HttpOverseerAgent(OverseerAgent):
def __init__(
self,
role,
overseer_end_point,
project,
name: str,
fl_port: str = "",
admin_port: str = "",
heartbeat_interval=5,
):
if role not in ["server", "client", "admin"]:
raise ValueError(f'Expect role in ["server", "client", "admin"] but got {role}')
super().__init__()
self._role = role
self._overseer_end_point = overseer_end_point
self._project = project
self._session = None
self._status_lock = threading.Lock()
self._report_and_query = threading.Thread(target=self._rnq_worker, args=())
self._psp = SP()
self._flag = threading.Event()
self._ca_path = None
self._cert_path = None
self._prv_key_path = None
self._last_service_session_id = ""
self._asked_to_exit = False
self._logger = logging.getLogger(self.__class__.__name__)
self._retry_delay = 4
self._asked_to_stop_retrying = False
self._update_callback = None
self._conditional_cb = False
if self._role == "server":
self._sp_end_point = ":".join([name, fl_port, admin_port])
self._heartbeat_interval = heartbeat_interval
def _send(
self, api_point, headers: Optional[Dict[str, Any]] = None, payload: Optional[Dict[str, Any]] = None
) -> Response:
try_count = 0
while not self._asked_to_stop_retrying:
try:
req = Request("POST", api_point, json=payload, headers=headers)
prepared = self._session.prepare_request(req)
resp = self._session.send(prepared)
return resp
except RequestException as e:
self._logger.debug(f"Overseer error: {secure_format_exception(e)}")
try_count += 1
time.sleep(self._retry_delay)
def set_secure_context(self, ca_path: str, cert_path: str = "", prv_key_path: str = ""):
self._ca_path = ca_path
self._cert_path = cert_path
self._prv_key_path = prv_key_path
def start(self, update_callback=None, conditional_cb=False):
self._session = Session()
adapter = HTTPAdapter(max_retries=1)
self._session.mount("http://", adapter)
self._session.mount("https://", adapter)
if self._ca_path:
self._session.verify = self._ca_path
self._session.cert = (self._cert_path, self._prv_key_path)
self._conditional_cb = conditional_cb
if update_callback:
self._update_callback = update_callback
self._report_and_query.start()
self._flag.set()
def pause(self):
self._asked_to_stop_retrying = True
self._flag.clear()
def resume(self):
self._asked_to_stop_retrying = False
self._flag.set()
def end(self):
self._asked_to_stop_retrying = True
self._flag.set()
self._asked_to_exit = True
self._report_and_query.join()
def is_shutdown(self) -> bool:
"""Return whether the agent receives a shutdown request."""
return self.overseer_info.get("system") == "shutdown"
def get_primary_sp(self) -> SP:
"""Return current primary service provider.
If primary sp not available, such as not reported by SD, connection to SD not established yet
the name and ports will be empty strings.
"""
return self._psp
def promote_sp(self, sp_end_point, headers=None) -> Response:
api_point = self._overseer_end_point + "/promote"
return self._send(api_point, headers=None, payload={"sp_end_point": sp_end_point, "project": self._project})
def set_state(self, state) -> Response:
api_point = self._overseer_end_point + "/state"
return self._send(api_point, payload={"state": state})
def _do_callback(self):
if self._update_callback:
self._update_callback(self)
def _handle_ssid(self, ssid):
if not self._conditional_cb or self._last_service_session_id != ssid:
self._last_service_session_id = ssid
self._do_callback()
def _prepare_data(self):
data = dict(role=self._role, project=self._project)
return data
def _rnq_worker(self):
data = self._prepare_data()
if self._role == "server":
data["sp_end_point"] = self._sp_end_point
api_point = self._overseer_end_point + "/heartbeat"
while not self._asked_to_exit:
self._flag.wait()
self._rnq(api_point, headers=None, data=data)
time.sleep(self._heartbeat_interval)
def _rnq(self, api_point, headers, data):
resp = self._send(api_point, headers=headers, payload=data)
if resp is None:
return
if resp.status_code != codes.ok:
return
self.overseer_info = resp.json()
psp = self.overseer_info.get("primary_sp")
if psp:
name, fl_port, admin_port = psp.get("sp_end_point").split(":")
service_session_id = psp.get("service_session_id", "")
self._psp = SP(name, fl_port, admin_port, service_session_id, True)
# last_heartbeat = psp.get("last_heartbeat", "")
self._handle_ssid(service_session_id)
else:
self._psp = SP()
service_session_id = ""
self._handle_ssid(service_session_id)
| NVFlare-main | nvflare/ha/overseer_agent.py |
# Copyright (c) 2022, 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.
| NVFlare-main | nvflare/ha/__init__.py |
# Copyright (c) 2022, 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 pprint import pprint
from nvflare.ha.overseer_agent import HttpOverseerAgent
def setup_basic_info():
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--project", type=str, default="example_project", help="project name")
parser.add_argument("-r", "--role", type=str, help="role (server, client or admin)")
parser.add_argument("-n", "--name", type=str, help="globally unique name")
parser.add_argument("-f", "--fl_port", type=str, help="fl port number")
parser.add_argument("-a", "--admin_port", type=str, help="adm port number")
parser.add_argument("-s", "--sleep", type=float, help="sleep (seconds) in heartbeat")
parser.add_argument("-c", "--ca_path", type=str, help="root CA path")
parser.add_argument("-o", "--overseer_url", type=str, help="Overseer URL")
parser.add_argument("-t", "--cert_path", type=str, help="cert path")
parser.add_argument("-v", "--prv_key_path", type=str, help="priviate key path")
args = parser.parse_args()
overseer_agent = HttpOverseerAgent(
overseer_end_point=args.overseer_url,
project=args.project,
role=args.role,
name=args.name,
fl_port=args.fl_port,
admin_port=args.admin_port,
heartbeat_interval=args.sleep,
)
if args.ca_path:
overseer_agent.set_secure_context(
ca_path=args.ca_path, cert_path=args.cert_path, prv_key_path=args.prv_key_path
)
return overseer_agent
def main():
overseer_agent = setup_basic_info()
overseer_agent.start(simple_callback, conditional_cb=True)
while True:
answer = input("(p)ause/(r)esume/(s)witch/(d)ump/(e)nd? ")
normalized_answer = answer.strip().upper()
if normalized_answer == "P":
overseer_agent.pause()
elif normalized_answer == "R":
overseer_agent.resume()
elif normalized_answer == "E":
overseer_agent.end()
break
elif normalized_answer == "D":
pprint(overseer_agent.overseer_info)
elif normalized_answer == "":
continue
elif normalized_answer[0] == "S":
split = normalized_answer.split()
if len(split) == 2:
sp_index = int(split[1])
else:
print("expect sp index but got nothing. Please provide the sp index to be promoted")
continue
try:
sp = overseer_agent.overseer_info.get("sp_list")[sp_index]
except IndexError:
print("index out of range")
else:
resp = overseer_agent.promote_sp(sp.get("sp_end_point"))
pprint(resp.json())
def simple_callback(overseer_agent):
print(f"\nGot callback {overseer_agent.get_primary_sp()}")
if __name__ == "__main__":
main()
| NVFlare-main | nvflare/ha/overseer_agent_app.py |
# Copyright (c) 2022, 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 json
import logging
from nvflare.apis.fl_constant import AdminCommandNames
from nvflare.apis.overseer_spec import OverseerAgent
from nvflare.fuel.hci.client.api_spec import CommandContext
from nvflare.fuel.hci.client.api_status import APIStatus
from nvflare.fuel.hci.proto import MetaStatusValue, ProtoKey, make_meta
from nvflare.fuel.hci.reg import CommandModule, CommandModuleSpec, CommandSpec
from nvflare.security.logging import secure_format_exception
class HACommandModule(CommandModule):
"""Command module with commands for management in relation to the high availability framework."""
def __init__(self, overseer_agent: OverseerAgent):
self.overseer_agent = overseer_agent
self.logger = logging.getLogger(self.__class__.__name__)
def get_spec(self):
return CommandModuleSpec(
name="ha_mgmt",
cmd_specs=[
CommandSpec(
name="list_sp",
description="list service providers information from previous heartbeat",
usage="list_sp",
handler_func=self.list_sp,
),
CommandSpec(
name="get_active_sp",
description="get active service provider",
usage="get_active_sp",
handler_func=self.get_active_sp,
),
CommandSpec(
name="promote_sp",
description="promote active service provider to specified",
usage="promote_sp sp_end_point",
handler_func=self.promote_sp,
),
CommandSpec(
name="shutdown_system",
description="shut down entire system by setting the system state to shutdown through the overseer",
usage="shutdown_system",
handler_func=self.shutdown_system,
),
],
)
def list_sp(self, args, ctx: CommandContext):
"""Lists service provider information based on the last heartbeat from the overseer.
Details are used for displaying the response in the CLI, and data is the data in a dict that is provided in FLAdminAPI.
"""
overseer_agent = self.overseer_agent
return {
ProtoKey.STATUS: APIStatus.SUCCESS,
ProtoKey.DETAILS: str(overseer_agent.overseer_info),
ProtoKey.DATA: overseer_agent.overseer_info,
}
def get_active_sp(self, args, ctx: CommandContext):
overseer_agent = self.overseer_agent
sp = overseer_agent.get_primary_sp()
return {ProtoKey.STATUS: APIStatus.SUCCESS, ProtoKey.DETAILS: str(sp), ProtoKey.META: sp.__dict__}
def promote_sp(self, args, ctx: CommandContext):
overseer_agent = self.overseer_agent
if len(args) != 2:
return {
ProtoKey.STATUS: APIStatus.ERROR_SYNTAX,
ProtoKey.DETAILS: "usage: promote_sp example1.com:8002:8003",
ProtoKey.META: make_meta(MetaStatusValue.SYNTAX_ERROR),
}
sp_end_point = args[1]
resp = overseer_agent.promote_sp(sp_end_point)
err = json.loads(resp.text).get("Error")
if err:
return {
ProtoKey.STATUS: APIStatus.ERROR_RUNTIME,
ProtoKey.DETAILS: f"Error: {err}",
ProtoKey.META: make_meta(MetaStatusValue.INTERNAL_ERROR, err),
}
else:
info = f"Promoted endpoint: {sp_end_point}. Synchronizing with overseer..."
return {
ProtoKey.STATUS: APIStatus.SUCCESS,
ProtoKey.DETAILS: info,
ProtoKey.META: make_meta(MetaStatusValue.OK, info),
}
def shutdown_system(self, args, ctx: CommandContext):
api = ctx.get_api()
overseer_agent = self.overseer_agent
try:
admin_status_result = api.do_command(AdminCommandNames.ADMIN_CHECK_STATUS + " server")
if admin_status_result.get(ProtoKey.META).get(ProtoKey.STATUS) == MetaStatusValue.NOT_AUTHORIZED:
return {
ProtoKey.STATUS: APIStatus.ERROR_AUTHORIZATION,
ProtoKey.DETAILS: "Error: Not authorized for this command.",
}
status = admin_status_result.get(ProtoKey.DATA)
if status[0].get(ProtoKey.DATA) != "Engine status: stopped":
return {
ProtoKey.STATUS: APIStatus.ERROR_RUNTIME,
ProtoKey.DETAILS: "Error: There are still jobs running. Please let them finish or abort_job before attempting shutdown.",
}
except Exception as e:
return {
ProtoKey.STATUS: APIStatus.ERROR_RUNTIME,
ProtoKey.DETAILS: f"Error getting server status to make sure all jobs are stopped before shutting down system: {secure_format_exception(e)}",
}
# print("Shutting down the system...")
resp = overseer_agent.set_state("shutdown")
if json.loads(resp.text).get("Error"):
return {
ProtoKey.STATUS: APIStatus.ERROR_RUNTIME,
ProtoKey.DETAILS: "Error: {}".format(json.loads(resp.text).get("Error")),
}
else:
return {ProtoKey.STATUS: APIStatus.SUCCESS, ProtoKey.DETAILS: "Set state to shutdown in overseer."}
| NVFlare-main | nvflare/ha/ha_admin_cmds.py |
# Copyright (c) 2022, 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 json
import threading
import time
from requests import Response
from nvflare.apis.fl_constant import FLContextKey
from nvflare.apis.fl_context import FLContext
from nvflare.apis.overseer_spec import SP, OverseerAgent
class DummyOverseerAgent(OverseerAgent):
SSID = "ebc6125d-0a56-4688-9b08-355fe9e4d61a"
def __init__(self, sp_end_point, heartbeat_interval=5):
super().__init__()
self._base_init(sp_end_point)
self._report_and_query = threading.Thread(target=self._rnq_worker, args=())
self._report_and_query.daemon = True
self._flag = threading.Event()
self._asked_to_exit = False
self._update_callback = None
self._conditional_cb = False
self._heartbeat_interval = heartbeat_interval
def _base_init(self, sp_end_point):
self.sp_end_point = sp_end_point
name, fl_port, admin_port = self.sp_end_point.split(":")
self._psp = SP(name, fl_port, admin_port, DummyOverseerAgent.SSID, True)
psp_dict = {
"sp_end_point": sp_end_point,
"service_session_id": DummyOverseerAgent.SSID,
"primary": True,
"state": "online",
}
self.overseer_info = {
"primary_sp": psp_dict,
"sp_list": [psp_dict],
"system": "ready",
}
def initialize(self, fl_ctx: FLContext):
sp_end_point = fl_ctx.get_prop(FLContextKey.SP_END_POINT)
if sp_end_point:
self._base_init(sp_end_point)
def is_shutdown(self) -> bool:
"""Return whether the agent receives a shutdown request."""
return False
def get_primary_sp(self) -> SP:
"""Return current primary service provider. The PSP is static in the dummy agent."""
return self._psp
def promote_sp(self, sp_end_point, headers=None) -> Response:
# a hack to create dummy response
resp = Response()
resp.status_code = 200
resp._content = json.dumps({"Error": "this functionality is not supported by the dummy agent"}).encode("utf-8")
return resp
def start(self, update_callback=None, conditional_cb=False):
self._conditional_cb = conditional_cb
self._update_callback = update_callback
self._report_and_query.start()
self._flag.set()
def pause(self):
self._flag.clear()
def resume(self):
self._flag.set()
def set_state(self, state) -> Response:
# a hack to create dummy response
resp = Response()
resp.status_code = 200
resp._content = json.dumps({"Error": "this functionality is not supported by the dummy agent"}).encode("utf-8")
return resp
def end(self):
self._flag.set()
self._asked_to_exit = True
# self._report_and_query.join()
def set_secure_context(self, ca_path: str, cert_path: str = "", prv_key_path: str = ""):
pass
def _do_callback(self):
if self._update_callback:
self._update_callback(self)
def _rnq_worker(self):
while not self._asked_to_exit:
self._flag.wait()
if not self._conditional_cb:
self._do_callback()
time.sleep(self._heartbeat_interval)
| NVFlare-main | nvflare/ha/dummy_overseer_agent.py |
# Copyright (c) 2022, 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 gunicorn.workers.sync import SyncWorker
class ClientAuthWorker(SyncWorker):
def handle_request(self, listener, req, client, addr):
subject = client.getpeercert().get("subject")
role = None
for ((key, value),) in subject:
if key == "unstructuredName":
role = value
break
if role is not None:
headers = dict(req.headers)
headers["X-ROLE"] = role
req.headers = list(headers.items())
super(ClientAuthWorker, self).handle_request(listener, req, client, addr)
| NVFlare-main | nvflare/ha/overseer/worker.py |
# Copyright (c) 2022, 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 threading
data_store = dict()
data_store["SP"] = dict()
data_store_lock = threading.Lock()
def _primary_key(sp):
return f'{sp["project"]}/{sp["sp_end_point"]}'
def get_all_sp(project):
with data_store_lock:
sp_list = [v for v in data_store["SP"].values() if v["project"] == project]
return sp_list
def get_primary_sp(project):
psp = {}
with data_store_lock:
for _, sp in data_store["SP"].items():
if sp["primary"] and sp["project"] == project:
psp = sp
break
return psp
def update_sp(sp):
with data_store_lock:
key = _primary_key(sp)
existing_sp = data_store["SP"].get(key)
if existing_sp:
existing_sp.update(sp)
data_store["SP"][key] = existing_sp
else:
data_store["SP"][key] = sp
def get_sp_by(predicate: dict):
result = {}
with data_store_lock:
for sp in data_store["SP"].values():
if all(sp[k] == predicate[k] for k in predicate):
result = sp
break
return result
| NVFlare-main | nvflare/ha/overseer/mem_store.py |
# Copyright (c) 2022, 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.
| NVFlare-main | nvflare/ha/overseer/__init__.py |
# Copyright (c) 2022, 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 uuid
from datetime import datetime, timedelta
from .mem_store import get_all_sp, get_primary_sp, get_sp_by, update_sp # noqa
system_state = "ready"
def get_system_state():
global system_state
return system_state
def set_system_state(state):
global system_state
system_state = state
return get_system_state()
def update_sp_state(project, now, heartbeat_timeout=10):
valid_starting = now - timedelta(seconds=heartbeat_timeout)
# mark all late SP as offline and not primary
# print(f"{now=} {valid_starting=}")
for sp in get_all_sp(project):
if datetime.fromisoformat(sp["last_heartbeat"]) < valid_starting:
sp["state"] = "offline"
sp["primary"] = False
else:
sp["state"] = "online"
update_sp(sp)
def simple_PSP_policy(incoming_sp, now):
"""Find the primary SP (PSP).
If there is no PSP or current PSP timeout, choose one without heartbeat timeout.
"""
project = incoming_sp["project"]
sp = get_sp_by(dict(project=project, sp_end_point=incoming_sp["sp_end_point"]))
if sp:
sp["last_heartbeat"] = now.isoformat()
update_sp(sp)
else:
update_sp(
dict(
project=incoming_sp["project"],
sp_end_point=incoming_sp["sp_end_point"],
last_heartbeat=now.isoformat(),
state="online",
primary=False,
)
)
psp = get_primary_sp(project)
if not psp:
psp = get_sp_by(dict(project=project, state="online"))
if psp:
print(f"{psp['sp_end_point']} online")
psp["primary"] = True
psp["service_session_id"] = str(uuid.uuid4())
update_sp(psp)
return psp
def promote_sp(sp):
psp = get_sp_by(sp)
project = sp["project"]
sp_end_point = sp["sp_end_point"]
if psp and psp["state"] == "online":
current_psp = get_primary_sp(project)
if all(current_psp[k] == v for k, v in sp.items()):
return True, f"Same sp_end_point, no need to promote {sp_end_point}."
psp["primary"] = True
current_psp["primary"] = False
psp["service_session_id"] = str(uuid.uuid4())
print(f"{psp['sp_end_point']} promoted")
print(f"{current_psp['sp_end_point']} demoted")
update_sp(psp)
update_sp(current_psp)
return False, psp
else:
return True, f"Unable to promote {sp_end_point}, either offline or not registered."
| NVFlare-main | nvflare/ha/overseer/utils.py |
# Copyright (c) 2022, 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 flask import Flask
app = Flask(__name__)
app.config["APPLICATION_ROOT"] = "/api/v1"
| NVFlare-main | nvflare/ha/overseer/app.py |
# Copyright (c) 2022, 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 os
from datetime import datetime
from flask import jsonify, request
from nvflare.ha.overseer.app import app
from nvflare.ha.overseer.utils import (
get_all_sp,
get_primary_sp,
get_system_state,
promote_sp,
set_system_state,
simple_PSP_policy,
update_sp_state,
)
heartbeat_timeout = os.environ.get("NVFL_OVERSEER_HEARTBEAT_TIMEOUT", "10")
try:
heartbeat_timeout = int(heartbeat_timeout)
except Exception:
heartbeat_timeout = 10
@app.route("/api/v1/heartbeat", methods=["GET", "POST"])
def heartbeat():
if request.method == "POST":
req = request.json
project = req.get("project")
role = req.get("role")
if project is None or role is None:
return jsonify({"Error": "project and role must be provided"})
now = datetime.utcnow()
update_sp_state(project, now, heartbeat_timeout=heartbeat_timeout)
if role == "server":
sp_end_point = req.get("sp_end_point")
if sp_end_point is None:
return jsonify({"Error": "sp_end_point is not provided"})
incoming_sp = dict(sp_end_point=sp_end_point, project=project)
psp = simple_PSP_policy(incoming_sp, now)
elif role in ["client", "admin"]:
psp = get_primary_sp(project)
else:
psp = {}
return jsonify({"primary_sp": psp, "sp_list": get_all_sp(project), "system": get_system_state()})
@app.route("/api/v1/promote", methods=["GET", "POST"])
def promote():
if app.config.get("DEBUG") is not True and request.headers.get("X-ROLE") != "project_admin":
return jsonify({"Error": "No rights"})
if request.method == "POST":
req = request.json
sp_end_point = req.get("sp_end_point", "")
project = req.get("project", "")
if project and sp_end_point:
incoming_sp = dict(sp_end_point=sp_end_point, project=project)
err, result = promote_sp(incoming_sp)
if not err:
return jsonify({"primary_sp": result})
else:
return jsonify({"Error": result})
else:
return jsonify({"Error": "Wrong project or sp_end_point."})
@app.route("/api/v1/state", methods=["POST"])
def state():
if app.config.get("DEBUG") is not True and request.headers.get("X-ROLE") != "project_admin":
return jsonify({"Error": "No rights"})
req = request.json
state = req.get("state")
if state not in ["ready", "shutdown"]:
return jsonify({"Error": "Wrong state"})
set_system_state(state)
return jsonify({"Status": get_system_state()})
@app.route("/api/v1/refresh")
def refresh():
if app.config.get("DEBUG") is not True and request.headers.get("X-ROLE") != "project_admin":
return jsonify({"Error": "No rights"})
return jsonify({"Status": "Error. API disabled."})
if __name__ == "__main__":
app.run()
| NVFlare-main | nvflare/ha/overseer/overseer.py |
# Copyright (c) 2021, 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.
| NVFlare-main | nvflare/app_common/__init__.py |
# Copyright (c) 2021, 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.
class ExecutorTasks:
TRAIN = "train"
VALIDATE = "validate"
CROSS_VALIDATION = "__cross_validation"
SUBMIT_BEST = "__submit_best"
REPORT_STATUS = "report_status"
class AppConstants(object):
CONFIG_PATH = "config_path"
MODEL_NETWORK = "model_network"
MULTI_GPU = "multi_gpu"
TRAIN_CONTEXT = "train_context"
DEVICE = "device"
MODEL_NAME = "model_name"
MODEL_URL = "model_url"
START_ROUND = "start_round"
CURRENT_ROUND = "current_round"
CONTRIBUTION_ROUND = "contribution_round"
CONTRIBUTION_CLIENT = "contribution_client"
NUM_ROUNDS = "num_rounds"
WAIT_AFTER_MIN_CLIENTS = "wait_after_min_clients"
NUM_TOTAL_STEPS = "num_total_steps" # TOTAL_STEPS
NUM_EPOCHS_CURRENT_ROUND = "num_epochs_current_round" # CURRENT_EPOCHS
NUM_TOTAL_EPOCHS = "num_total_epochs" # LOCAL_EPOCHS
LOCAL_EPOCHS = "local_epochs"
IS_FIRST_ROUND = "is_first_round"
MY_RANK = "my_rank"
INITIAL_LEARNING_RATE = "initial_learning_rate"
CURRENT_LEARNING_RATE = "current_learning_rate"
NUMBER_OF_GPUS = "number_of_gpus"
META_COOKIE = "cookie"
META_DATA = "meta_data"
GLOBAL_MODEL = "global_model"
IS_BEST = "is_best"
FAILURE = "failure"
LOG_DIR = "model_log_dir"
CKPT_PRELOAD_PATH = "ckpt_preload_path"
DXO = "DXO"
PHASE = "_phase_"
PHASE_INIT = "_init_"
PHASE_TRAIN = "train"
PHASE_MODEL_VALIDATION = "model_validation"
PHASE_FINISHED = "_finished_"
STATUS_WAIT = "_wait_"
STATUS_DONE = "_done_"
STATUS_TRAINING = "_training_"
STATUS_IDLE = "_idle_"
MODEL_LOAD_PATH = "_model_load_path"
MODEL_SAVE_PATH = "_model_save_path"
DEFAULT_MODEL_DIR = "models"
ROUND = "_round_"
MODEL_WEIGHTS = "_model_weights_"
AGGREGATION_RESULT = "_aggregation_result"
AGGREGATION_TRIGGERED = "_aggregation_triggered"
AGGREGATION_ACCEPTED = "_aggregation_accepted"
TRAIN_SHAREABLE = "_train_shareable_"
TRAINING_RESULT = "_training_result_"
SUBMIT_MODEL_FAILURE_REASON = "_submit_model_failure_reason"
CROSS_VAL_DIR = "cross_site_val"
CROSS_VAL_MODEL_DIR_NAME = "model_shareables"
CROSS_VAL_RESULTS_DIR_NAME = "result_shareables"
CROSS_VAL_MODEL_PATH = "_cross_val_model_path_"
CROSS_VAL_RESULTS_PATH = "_cross_val_results_path_"
RECEIVED_MODEL = "_receive_model_"
RECEIVED_MODEL_OWNER = "_receive_model_owner_"
MODEL_TO_VALIDATE = "_model_to_validate_"
DATA_CLIENT = "_data_client_"
VALIDATION_RESULT = "_validation_result_"
TASK_SUBMIT_MODEL = "submit_model"
TASK_VALIDATION = "validate"
TASK_CONFIGURE = "configure"
CROSS_VAL_SERVER_MODEL = "_cross_val_server_model_"
CROSS_VAL_CLIENT_MODEL = "_cross_val_client_model_"
PARTICIPATING_CLIENTS = "_particpating_clients_"
MODEL_OWNER = "_model_owner_"
DEFAULT_FORMATTER_ID = "formatter"
DEFAULT_MODEL_LOCATOR_ID = "model_locator"
TASK_END_RUN = "_end_run_"
TASK_TRAIN = "train"
TASK_GET_WEIGHTS = "get_weights"
DEFAULT_AGGREGATOR_ID = "aggregator"
DEFAULT_PERSISTOR_ID = "persistor"
DEFAULT_SHAREABLE_GENERATOR_ID = "shareable_generator"
SUBMIT_MODEL_NAME = "submit_model_name"
VALIDATE_TYPE = "_validate_type"
class EnvironmentKey(object):
CHECKPOINT_DIR = "APP_CKPT_DIR"
CHECKPOINT_FILE_NAME = "APP_CKPT"
class DefaultCheckpointFileName(object):
GLOBAL_MODEL = "FL_global_model.pt"
BEST_GLOBAL_MODEL = "best_FL_global_model.pt"
class ModelName(object):
BEST_MODEL = "best_model"
FINAL_MODEL = "final_model"
class ModelFormat(object):
PT_CHECKPOINT = "pt_checkpoint"
TORCH_SCRIPT = "torch_script"
PT_ONNX = "pt_onnx"
TF_CHECKPOINT = "tf_checkpoint"
KERAS = "keras_model"
class ValidateType(object):
BEFORE_TRAIN_VALIDATE = "before_train_validate"
MODEL_VALIDATE = "model_validate"
class AlgorithmConstants(object):
SCAFFOLD_CTRL_DIFF = "scaffold_c_diff"
SCAFFOLD_CTRL_GLOBAL = "scaffold_c_global"
SCAFFOLD_CTRL_AGGREGATOR_ID = "scaffold_ctrl_aggregator"
class StatisticsConstants(AppConstants):
STATS_COUNT = "count"
STATS_FAILURE_COUNT = "failure_count"
STATS_MEAN = "mean"
STATS_SUM = "sum"
STATS_VAR = "var"
STATS_STDDEV = "stddev"
STATS_HISTOGRAM = "histogram"
STATS_MAX = "max"
STATS_MIN = "min"
STATS_FEATURES = "stats_features"
STATS_GLOBAL_MEAN = "global_mean"
STATS_GLOBAL_COUNT = "global_count"
STATS_BINS = "bins"
STATS_BIN_RANGE = "range"
STATS_TARGET_STATISTICS = "statistics"
FED_STATS_PRE_RUN = "fed_stats_pre_run"
FED_STATS_TASK = "fed_stats"
STATISTICS_TASK_KEY = "fed_stats_task_key"
STATS_1st_STATISTICS = "fed_stats_1st_statistics"
STATS_2nd_STATISTICS = "fed_stats_2nd_statistics"
GLOBAL = "Global"
ordered_statistics = {
STATS_1st_STATISTICS: [STATS_COUNT, STATS_FAILURE_COUNT, STATS_SUM, STATS_MEAN, STATS_MIN, STATS_MAX],
STATS_2nd_STATISTICS: [STATS_HISTOGRAM, STATS_VAR, STATS_STDDEV],
}
PRE_RUN_RESULT = "fed_stats_pre_run_result"
class PSIConst(AppConstants):
TASK_KEY = "PSI_TASK_KEY"
DIRECTION_KEY = "PSI_DIRECTION_KEY"
FORWARD = "PSI_FORWARD"
BACKWARD = "PSI_BACKWARD"
TASK = "PSI"
TASK_PREPARE = "PSI_PREPARE"
TASK_SETUP = "PSI_SETUP"
TASK_REQUEST = "PSI_REQUEST"
TASK_RESPONSE = "PSI_RESPONSE"
TASK_INTERSECT = "PSI_TASK_INTERSECT"
ITEMS_SIZE = "PSI_ITEMS_SIZE"
ITEMS_SIZE_SET = "PSI_ITEMS_SIZE_SET"
# Bloom Filter False Positive Rate
BLOOM_FILTER_FPR = "PSI_BLOOM_FILTER_FPR"
SETUP_MSG = "PSI_SETUP_MSG"
REQUEST_MSG = "PSI_REQUEST_MSG"
REQUEST_MSG_SET = "PSI_REQUEST_MSG_SET"
RESPONSE_MSG = "PSI_RESPONSE_MSG"
| NVFlare-main | nvflare/app_common/app_constant.py |
# Copyright (c) 2021, 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.
class AppEventType(object):
"""Defines application events."""
BEFORE_AGGREGATION = "_before_aggregation"
END_AGGREGATION = "_end_aggregation"
SUBMIT_LOCAL_BEST_MODEL = "_submit_local_best_model"
SERVER_RECEIVE_BEST_MODEL = "_server_receive_best_model"
RECEIVE_VALIDATION_MODEL = "_receive_validation_model"
SEND_VALIDATION_RESULTS = "_send_validation_results"
RECEIVE_VALIDATION_RESULTS = "_receive_validation_results"
BEFORE_INITIALIZE = "_before_initialize"
AFTER_INITIALIZE = "_after_initialize"
BEFORE_TRAIN = "_before_train"
AFTER_TRAIN = "_after_train"
BEFORE_SHAREABLE_TO_LEARNABLE = "_before_model_update"
AFTER_SHAREABLE_TO_LEARNABLE = "_after_model_update"
BEFORE_LEARNABLE_PERSIST = "_before_save_model"
AFTER_LEARNABLE_PERSIST = "_after_save_model"
BEFORE_SEND_BEST_MODEL = "_before_send_best_model"
AFTER_SEND_BEST_MODEL = "_after_send_best_model"
LOCAL_BEST_MODEL_AVAILABLE = "_local_best_model_available"
GLOBAL_BEST_MODEL_AVAILABLE = "_global_best_model_available"
BEFORE_GET_VALIDATION_MODELS = "_before_get_validation_models"
AFTER_GET_VALIDATION_MODELS = "_after_get_validation_models"
SEND_MODEL_FOR_VALIDATION = "_send_model_for_validation"
BEFORE_VALIDATE_MODEL = "_before_validate_model"
AFTER_VALIDATE_MODEL = "_after_validate_model"
BEFORE_SUBMIT_VALIDATION_RESULTS = "_before_submit_validation_results"
AFTER_SUBMIT_VALIDATION_RESULTS = "_after_submit_validation_results"
# Events
ROUND_STARTED = "_round_started"
ROUND_DONE = "_round_done"
INITIAL_MODEL_LOADED = "_initial_model_loaded"
BEFORE_TRAIN_TASK = "_before_train_task"
RECEIVE_CONTRIBUTION = "_receive_contribution"
AFTER_CONTRIBUTION_ACCEPT = "_after_contribution_accept"
AFTER_AGGREGATION = "_after_aggregation"
BEFORE_CONTRIBUTION_ACCEPT = "_before_contribution_accept"
GLOBAL_WEIGHTS_UPDATED = "_global_weights_updated"
TRAINING_STARTED = "_training_started"
TRAINING_FINISHED = "_training_finished"
TRAIN_DONE = "_train_done"
CROSS_VAL_INIT = "_cross_val_init"
VALIDATION_RESULT_RECEIVED = "_validation_result_received"
RECEIVE_BEST_MODEL = "_receive_best_model"
| NVFlare-main | nvflare/app_common/app_event_type.py |
# Copyright (c) 2021, 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.
class ModelDescriptor:
def __init__(self, name: str, location: str, model_format: str, props: dict = None) -> None:
"""The class to describe the model.
Args:
name: model name
location: model location
model_format: model format
props: additional properties of the model
"""
super().__init__()
self.name = name
self.location = location
self.model_format = model_format
self.props = props
| NVFlare-main | nvflare/app_common/model_desc.py |
# Copyright (c) 2022, 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 Any, Type
from nvflare.app_common.abstract.statistics_spec import (
Bin,
BinRange,
DataType,
Feature,
Histogram,
HistogramType,
StatisticConfig,
)
from nvflare.fuel.utils import fobs
from nvflare.fuel.utils.fobs.datum import DatumManager
class StatisticConfigDecomposer(fobs.Decomposer):
def supported_type(self) -> Type[Any]:
return StatisticConfig
def decompose(self, statistic_config: StatisticConfig, manager: DatumManager = None) -> Any:
return [statistic_config.name, statistic_config.config]
def recompose(self, data: list, manager: DatumManager = None) -> StatisticConfig:
return StatisticConfig(data[0], data[1])
class FeatureDecomposer(fobs.Decomposer):
def supported_type(self) -> Type[Any]:
return Feature
def decompose(self, f: Feature, manager: DatumManager = None) -> Any:
return [f.feature_name, f.data_type]
def recompose(self, data: list, manager: DatumManager = None) -> Feature:
return Feature(data[0], data[1])
class BinDecomposer(fobs.Decomposer):
def supported_type(self) -> Type[Any]:
return Bin
def decompose(self, b: Bin, manager: DatumManager = None) -> Any:
return [b.low_value, b.high_value, b.sample_count]
def recompose(self, data: list, manager: DatumManager = None) -> Bin:
return Bin(data[0], data[1], data[2])
class BinRangeDecomposer(fobs.Decomposer):
def supported_type(self) -> Type[Any]:
return BinRange
def decompose(self, b: BinRange, manager: DatumManager = None) -> Any:
return [b.min_value, b.max_value]
def recompose(self, data: list, manager: DatumManager = None) -> BinRange:
return BinRange(data[0], data[1])
class HistogramDecomposer(fobs.Decomposer):
def supported_type(self) -> Type[Any]:
return Histogram
def decompose(self, b: Histogram, manager: DatumManager = None) -> Any:
return [b.hist_type, b.bins, b.hist_name]
def recompose(self, data: list, manager: DatumManager = None) -> Histogram:
return Histogram(data[0], data[1], data[2])
class HistogramTypeDecomposer(fobs.Decomposer):
def supported_type(self) -> Type[HistogramType]:
return HistogramType
def decompose(self, target: HistogramType, manager: DatumManager = None) -> Any:
return target.value
def recompose(self, data: Any, manager: DatumManager = None) -> HistogramType:
return HistogramType(data)
class DataTypeDecomposer(fobs.Decomposer):
def supported_type(self) -> Type[DataType]:
return DataType
def decompose(self, target: DataType, manager: DatumManager = None) -> Any:
return target.value
def recompose(self, data: Any, manager: DatumManager = None) -> DataType:
return DataType(data)
def fobs_registration():
fobs.register(StatisticConfigDecomposer)
fobs.register(FeatureDecomposer)
fobs.register(HistogramDecomposer)
fobs.register(BinDecomposer)
fobs.register(BinRangeDecomposer)
fobs.register(HistogramTypeDecomposer)
fobs.register(DataTypeDecomposer)
| NVFlare-main | nvflare/app_common/statistics/statisitcs_objects_decomposer.py |
# Copyright (c) 2022, 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 abc import ABC, abstractmethod
from typing import Dict, List, Tuple
from nvflare.app_common.app_constant import StatisticsConstants as StC
class StatisticsPrivacyCleanser(ABC):
@abstractmethod
def apply(self, statistics: dict, client_name: str) -> Tuple[dict, bool]:
pass
def cleanse(
self, statistics: dict, statistic_keys: List[str], validation_result: Dict[str, Dict[str, bool]]
) -> (dict, bool):
"""
Args:
statistics: original client local metrics
statistic_keys: statistic keys need to be cleansed
validation_result: local metrics privacy validation result
Returns:
filtered metrics with feature metrics that violating the privacy policy be removed from the original metrics
"""
statistics_modified = False
for key in statistic_keys:
if key != StC.STATS_COUNT:
for ds_name in list(statistics[key].keys()):
for feature in list(statistics[key][ds_name].keys()):
if not validation_result[ds_name][feature]:
statistics[key][ds_name].pop(feature, None)
statistics_modified = True
return statistics, statistics_modified
| NVFlare-main | nvflare/app_common/statistics/statistics_privacy_cleanser.py |
# Copyright (c) 2022, 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 math import sqrt
from typing import Dict, List, TypeVar
from nvflare.app_common.abstract.statistics_spec import Bin, BinRange, DataType, Feature, Histogram, HistogramType
from nvflare.app_common.app_constant import StatisticsConstants as StC
T = TypeVar("T")
def get_global_feature_data_types(
client_feature_dts: Dict[str, Dict[str, List[Feature]]]
) -> Dict[str, Dict[str, DataType]]:
global_feature_data_types = {}
for client_name in client_feature_dts:
ds_features: Dict[str, List[Feature]] = client_feature_dts[client_name]
for ds_name in ds_features:
global_feature_data_types[ds_name] = {}
features = ds_features[ds_name]
for f in features:
if f.feature_name not in global_feature_data_types:
global_feature_data_types[ds_name][f.feature_name] = f.data_type
return global_feature_data_types
def get_global_stats(global_metrics: dict, client_metrics: dict, metric_task: str) -> dict:
# we need to calculate the metrics in specified order
ordered_target_metrics = StC.ordered_statistics[metric_task]
ordered_metrics = [metric for metric in ordered_target_metrics if metric in client_metrics]
for metric in ordered_metrics:
if metric not in global_metrics:
global_metrics[metric] = {}
stats = client_metrics[metric]
if metric == StC.STATS_COUNT or metric == StC.STATS_FAILURE_COUNT or metric == StC.STATS_SUM:
for client_name in stats:
global_metrics[metric] = accumulate_metrics(stats[client_name], global_metrics[metric])
elif metric == StC.STATS_MEAN:
global_metrics[metric] = get_means(global_metrics[StC.STATS_SUM], global_metrics[StC.STATS_COUNT])
elif metric == StC.STATS_MAX:
for client_name in stats:
global_metrics[metric] = get_min_or_max_values(stats[client_name], global_metrics[metric], max)
elif metric == StC.STATS_MIN:
for client_name in stats:
global_metrics[metric] = get_min_or_max_values(stats[client_name], global_metrics[metric], min)
elif metric == StC.STATS_HISTOGRAM:
for client_name in stats:
global_metrics[metric] = accumulate_hists(stats[client_name], global_metrics[metric])
elif metric == StC.STATS_VAR:
for client_name in stats:
global_metrics[metric] = accumulate_metrics(stats[client_name], global_metrics[metric])
elif metric == StC.STATS_STDDEV:
ds_vars = global_metrics[StC.STATS_VAR]
ds_stddev = {}
for ds_name in ds_vars:
ds_stddev[ds_name] = {}
feature_vars = ds_vars[ds_name]
for feature in feature_vars:
ds_stddev[ds_name][feature] = sqrt(feature_vars[feature])
global_metrics[StC.STATS_STDDEV] = ds_stddev
return global_metrics
def accumulate_metrics(metrics: dict, global_metrics: dict) -> dict:
for ds_name in metrics:
if ds_name not in global_metrics:
global_metrics[ds_name] = {}
feature_metrics = metrics[ds_name]
for feature_name in feature_metrics:
if feature_metrics[feature_name] is not None:
if feature_name not in global_metrics[ds_name]:
global_metrics[ds_name][feature_name] = feature_metrics[feature_name]
else:
global_metrics[ds_name][feature_name] += feature_metrics[feature_name]
return global_metrics
def get_min_or_max_values(metrics: dict, global_metrics: dict, fn2) -> dict:
"""Use 2 argument function to calculate fn2(global, client), for example, min or max.
.. note::
The global min/max values are min/max of all clients and all datasets.
Args:
metrics: client's metric
global_metrics: global metrics
fn2: two-argument function such as min or max
Returns: Dict[dataset, Dict[feature, int]]
"""
for ds_name in metrics:
if ds_name not in global_metrics:
global_metrics[ds_name] = {}
feature_metrics = metrics[ds_name]
for feature_name in feature_metrics:
if feature_name not in global_metrics[ds_name]:
global_metrics[ds_name][feature_name] = feature_metrics[feature_name]
else:
global_metrics[ds_name][feature_name] = fn2(
global_metrics[ds_name][feature_name], feature_metrics[feature_name]
)
results = {}
for ds_name in global_metrics:
for feature_name in global_metrics[ds_name]:
if feature_name not in results:
results[feature_name] = global_metrics[ds_name][feature_name]
else:
results[feature_name] = fn2(results[feature_name], global_metrics[ds_name][feature_name])
for ds_name in global_metrics:
for feature_name in global_metrics[ds_name]:
global_metrics[ds_name][feature_name] = results[feature_name]
return global_metrics
def bins_to_dict(bins: List[Bin]) -> Dict[BinRange, float]:
buckets = {}
for bucket in bins:
bucket_range = BinRange(bucket.low_value, bucket.high_value)
buckets[bucket_range] = bucket.sample_count
return buckets
def accumulate_hists(
metrics: Dict[str, Dict[str, Histogram]], global_hists: Dict[str, Dict[str, Histogram]]
) -> Dict[str, Dict[str, Histogram]]:
for ds_name in metrics:
feature_hists = metrics[ds_name]
if ds_name not in global_hists:
global_hists[ds_name] = {}
for feature in feature_hists:
hist: Histogram = feature_hists[feature]
if feature not in global_hists[ds_name]:
g_bins = []
for bucket in hist.bins:
g_bins.append(Bin(bucket.low_value, bucket.high_value, bucket.sample_count))
g_hist = Histogram(HistogramType.STANDARD, g_bins)
global_hists[ds_name][feature] = g_hist
else:
g_hist = global_hists[ds_name][feature]
g_buckets = bins_to_dict(g_hist.bins)
for bucket in hist.bins:
bin_range = BinRange(bucket.low_value, bucket.high_value)
if bin_range in g_buckets:
g_buckets[bin_range] += bucket.sample_count
else:
g_buckets[bin_range] = bucket.sample_count
# update ordered bins
updated_bins = []
for gb in g_hist.bins:
bin_range = BinRange(gb.low_value, gb.high_value)
updated_bins.append(Bin(gb.low_value, gb.high_value, g_buckets[bin_range]))
global_hists[ds_name][feature] = Histogram(g_hist.hist_type, updated_bins)
return global_hists
def get_means(sums: dict, counts: dict) -> dict:
means = {}
for ds_name in sums:
means[ds_name] = {}
feature_sums = sums[ds_name]
feature_counts = counts[ds_name]
for feature in feature_sums:
means[ds_name][feature] = feature_sums[feature] / feature_counts[feature]
return means
def filter_numeric_features(ds_features: Dict[str, List[Feature]]) -> Dict[str, List[Feature]]:
numeric_ds_features = {}
for ds_name in ds_features:
features: List[Feature] = ds_features[ds_name]
n_features = [f for f in features if (f.data_type == DataType.INT or f.data_type == DataType.FLOAT)]
numeric_ds_features[ds_name] = n_features
return numeric_ds_features
| NVFlare-main | nvflare/app_common/statistics/numeric_stats.py |
# Copyright (c) 2022, 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 json
from typing import List, Optional
import numpy as np
from nvflare.app_common.abstract.statistics_spec import Bin, BinRange, DataType
class NpEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
if isinstance(obj, np.floating):
return float(obj)
if isinstance(obj, np.ndarray):
return obj.tolist()
return super(NpEncoder, self).default(obj)
def dtype_to_data_type(dtype) -> DataType:
if dtype.char in np.typecodes["AllFloat"]:
return DataType.FLOAT
elif dtype.char in np.typecodes["AllInteger"] or dtype == bool:
return DataType.INT
elif np.issubdtype(dtype, np.datetime64) or np.issubdtype(dtype, np.timedelta64):
return DataType.DATETIME
else:
return DataType.STRING
def get_std_histogram_buckets(nums: np.ndarray, num_bins: int = 10, br: Optional[BinRange] = None):
num_posinf = len(nums[np.isposinf(nums)])
num_neginf = len(nums[np.isneginf(nums)])
if br:
counts, buckets = np.histogram(nums, bins=num_bins, range=(br.min_value, br.max_value))
else:
counts, buckets = np.histogram(nums, bins=num_bins)
histogram_buckets: List[Bin] = []
for bucket_count in range(len(counts)):
# Add any negative or positive infinities to the first and last
# buckets in the histogram.
bucket_low_value = buckets[bucket_count]
bucket_high_value = buckets[bucket_count + 1]
bucket_sample_count = counts[bucket_count]
if bucket_count == 0 and num_neginf > 0:
bucket_low_value = float("-inf")
bucket_sample_count += num_neginf
elif bucket_count == len(counts) - 1 and num_posinf > 0:
bucket_high_value = float("inf")
bucket_sample_count += num_posinf
histogram_buckets.append(
Bin(low_value=bucket_low_value, high_value=bucket_high_value, sample_count=bucket_sample_count)
)
if buckets is not None and len(buckets) > 0:
bucket = None
if num_neginf:
bucket = Bin(low_value=float("-inf"), high_value=float("-inf"), sample_count=num_neginf)
if num_posinf:
bucket = Bin(low_value=float("inf"), high_value=float("inf"), sample_count=num_posinf)
if bucket:
histogram_buckets.append(bucket)
return histogram_buckets
| NVFlare-main | nvflare/app_common/statistics/numpy_utils.py |
# Copyright (c) 2022, 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, Tuple
from nvflare.apis.fl_component import FLComponent
from nvflare.app_common.abstract.statistics_spec import Histogram
from nvflare.app_common.app_constant import StatisticsConstants as StC
from nvflare.app_common.statistics.statistics_privacy_cleanser import StatisticsPrivacyCleanser
class HistogramBinsCleanser(FLComponent, StatisticsPrivacyCleanser):
def __init__(self, max_bins_percent):
"""
max_bins_percent: max number of bins allowed in terms of percent of local data size.
Set this number to avoid number of bins equal or close equal to the
data size, which can lead to data leak.
for example: max_bins_percent = 10, means 10%
number of bins < max_bins_percent /100 * local count
"""
super().__init__()
self.max_bins_percent = max_bins_percent
self.validate_inputs()
def validate_inputs(self):
if self.max_bins_percent < 0 or self.max_bins_percent > 100:
raise ValueError(f"max_bins_percent {self.max_bins_percent} is not within (0, 100) ")
def hist_bins_validate(self, client_name: str, statistics: Dict) -> Dict[str, Dict[str, bool]]:
result = {}
if StC.STATS_HISTOGRAM in statistics:
hist_statistics = statistics[StC.STATS_HISTOGRAM]
for ds_name in hist_statistics:
result[ds_name] = {}
feature_item_counts = statistics[StC.STATS_COUNT][ds_name]
feature_item_failure_counts = statistics[StC.STATS_FAILURE_COUNT][ds_name]
feature_statistics = hist_statistics[ds_name]
for feature in feature_statistics:
hist: Histogram = feature_statistics[feature]
num_of_bins: int = len(hist.bins)
item_count = feature_item_counts[feature]
item_failure_count = feature_item_failure_counts[feature]
effective_count = item_count - item_failure_count
result[ds_name][feature] = True
limit_count = round(effective_count * self.max_bins_percent / 100)
if num_of_bins >= limit_count:
result[ds_name][feature] = False
self.logger.info(
f"number of bins: '{num_of_bins}' needs to be smaller than: {limit_count}], which"
f" is '{self.max_bins_percent}' percent of ( total count - failure count) '{effective_count}'"
f" for feature '{feature}' in dataset '{ds_name}' for client {client_name}"
)
return result
def apply(self, statistics: dict, client_name: str) -> Tuple[dict, bool]:
self.logger.info(f"HistogramBinCheck for client {client_name}")
if StC.STATS_HISTOGRAM in statistics:
validation_result = self.hist_bins_validate(client_name, statistics)
statistics_keys = [StC.STATS_HISTOGRAM]
return super().cleanse(statistics, statistics_keys, validation_result)
else:
return statistics, False
| NVFlare-main | nvflare/app_common/statistics/histogram_bins_cleanser.py |
# Copyright (c) 2022, 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.
| NVFlare-main | nvflare/app_common/statistics/__init__.py |
# Copyright (c) 2022, 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 json
import os
from nvflare.apis.fl_constant import FLContextKey
from nvflare.apis.fl_context import FLContext
from nvflare.apis.storage import StorageException
from nvflare.app_common.abstract.statistics_writer import StatisticsWriter
from nvflare.app_common.utils.json_utils import ObjectEncoder
from nvflare.fuel.utils.class_utils import get_class
class JsonStatsFileWriter(StatisticsWriter):
def __init__(self, output_path: str, json_encoder_path: str = ""):
super().__init__()
self.job_dir = None
if len(output_path) == 0:
raise ValueError(f"output_path {output_path} is empty string")
self.output_path = output_path
if json_encoder_path == "":
self.json_encoder_class = ObjectEncoder
else:
self.json_encoder_path = json_encoder_path
self.json_encoder_class = get_class(json_encoder_path)
def save(
self,
data: dict,
overwrite_existing,
fl_ctx: FLContext,
):
full_uri = self.get_output_path(fl_ctx)
self._validate_directory(full_uri)
data_exists = os.path.isfile(full_uri)
if data_exists and not overwrite_existing:
raise StorageException("object {} already exists and overwrite_existing is False".format(full_uri))
content = json.dumps(data, cls=self.json_encoder_class)
self.log_info(fl_ctx, f"trying to save data to {full_uri}")
with open(full_uri, "w") as outfile:
outfile.write(content)
self.log_info(fl_ctx, f"file {full_uri} saved")
def get_output_path(self, fl_ctx: FLContext) -> str:
self.job_dir = os.path.dirname(os.path.abspath(fl_ctx.get_prop(FLContextKey.APP_ROOT)))
self.log_info(fl_ctx, "job dir = " + self.job_dir)
return os.path.join(self.job_dir, self.output_path)
def _validate_directory(self, full_path: str):
if not os.path.isabs(full_path):
raise ValueError(f"path {full_path} must be an absolute path.")
parent_dir = os.path.dirname(full_path)
if os.path.exists(parent_dir) and not os.path.isdir(parent_dir):
raise ValueError(f"directory {parent_dir} exists but is not a directory.")
if not os.path.exists(parent_dir):
os.makedirs(parent_dir, exist_ok=False)
| NVFlare-main | nvflare/app_common/statistics/json_stats_file_persistor.py |
# Copyright (c) 2022, 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 random
from typing import Tuple
from nvflare.apis.fl_component import FLComponent
from nvflare.app_common.app_constant import StatisticsConstants as StC
from nvflare.app_common.statistics.statistics_privacy_cleanser import StatisticsPrivacyCleanser
class AddNoiseToMinMax(FLComponent, StatisticsPrivacyCleanser):
def __init__(self, min_noise_level: float, max_noise_level: float):
"""Random is used to generate random noise between (min_random and max_random).
Args:
min_noise_level: minimum noise -- used to protect min/max values before sending to server
max_noise_level: maximum noise -- used to protect min/max values before sending to server
For example, the random noise is to be within (0.1 and 0.3), i.e. 10% to 30% level.
This component will make local min values smaller than the true local min values, and max values larger than
the true local max values. As result, the estimate global max and min values (i.e. with noise)
are still bound to the true global min/max values, such that:
.. code-block:: text
est. global min value <
true global min value <
client's min value <
client's max value <
true global max <
est. global max value
"""
super().__init__()
self.noise_level = (min_noise_level, max_noise_level)
self.noise_generators = {
StC.STATS_MIN: AddNoiseToMinMax._get_min_value,
StC.STATS_MAX: AddNoiseToMinMax._get_max_value,
}
self.validate_inputs()
def validate_inputs(self):
for i in range(0, 2):
if self.noise_level[i] < 0 or self.noise_level[i] > 1.0:
raise ValueError(f"noise_level {self.noise_level} is not within (0, 1)")
if self.noise_level[0] > self.noise_level[1]:
raise ValueError(
f"minimum noise level {self.noise_level[0]} should be less "
f"than maximum noise level {self.noise_level[1]}"
)
@staticmethod
def _get_min_value(local_min_value: float, noise_level: Tuple):
r = random.uniform(noise_level[0], noise_level[1])
if local_min_value == 0:
min_value = -(1 - r) * 1e-5
else:
if local_min_value > 0:
min_value = local_min_value * (1 - r)
else:
min_value = local_min_value * (1 + r)
return min_value
@staticmethod
def _get_max_value(local_max_value: float, noise_level: Tuple):
r = random.uniform(noise_level[0], noise_level[1])
if local_max_value == 0:
max_value = (1 + r) * 1e-5
else:
if local_max_value > 0:
max_value = local_max_value * (1 + r)
else:
max_value = local_max_value * (1 - r)
return max_value
def generate_noise(self, statistics: dict, statistic) -> dict:
noise_gen = self.noise_generators[statistic]
for ds_name in statistics[statistic]:
for feature_name in statistics[statistic][ds_name]:
local_value = statistics[statistic][ds_name][feature_name]
noise_value = noise_gen(local_value, self.noise_level)
statistics[statistic][ds_name][feature_name] = noise_value
return statistics
def apply(self, statistics: dict, client_name: str) -> Tuple[dict, bool]:
statistics_modified = False
for statistic in statistics:
if statistic in self.noise_generators:
self.logger.info(f"AddNoiseToMinMax on {statistic} for client {client_name}")
statistics = self.generate_noise(statistics, statistic)
statistics_modified = True
return statistics, statistics_modified
| NVFlare-main | nvflare/app_common/statistics/min_max_cleanser.py |
# Copyright (c) 2022, 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, Tuple
from nvflare.apis.fl_component import FLComponent
from nvflare.app_common.app_constant import StatisticsConstants as StC
from nvflare.app_common.statistics.statistics_privacy_cleanser import StatisticsPrivacyCleanser
class MinCountCleanser(FLComponent, StatisticsPrivacyCleanser):
def __init__(self, min_count: float):
"""
min_count: minimum of data records (or tabular data rows) that required in order to perform statistics
calculation this is part the data privacy policy.
"""
super().__init__()
self.min_count = min_count
self.validate_inputs()
def validate_inputs(self):
if self.min_count < 0:
raise ValueError(f"min_count must be positive, but {self.min_count} is provided. ")
def min_count_validate(self, client_name: str, statistics: Dict) -> Dict[str, Dict[str, bool]]:
feature_statistics_valid = {}
if StC.STATS_COUNT in statistics:
count_statistics = statistics[StC.STATS_COUNT]
for ds_name in count_statistics:
feature_statistics_valid[ds_name] = {}
feature_counts = statistics[StC.STATS_COUNT][ds_name]
feature_failure_counts = statistics[StC.STATS_FAILURE_COUNT][ds_name]
for feature in feature_counts:
count = feature_counts[feature]
failure_count = feature_failure_counts[feature]
effective_count = count - failure_count
feature_statistics_valid[ds_name][feature] = True
if effective_count < self.min_count:
feature_statistics_valid[ds_name][feature] = False
self.logger.info(
f"dataset {ds_name} feature '{feature}' item count is "
f"less than required minimum count {self.min_count} for client {client_name} "
)
return feature_statistics_valid
def apply(self, statistics: dict, client_name) -> Tuple[dict, bool]:
self.logger.info(f"apply MinCountCheck for client {client_name}")
validation_result = self.min_count_validate(client_name, statistics)
statistics_keys = list(statistics.keys())
return super().cleanse(statistics, statistics_keys, validation_result)
| NVFlare-main | nvflare/app_common/statistics/min_count_cleanser.py |
# Copyright (c) 2022, 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 List, Optional
from nvflare.app_common.app_constant import StatisticsConstants as StC
def get_feature_bin_range(feature_name: str, hist_config: dict) -> Optional[List[float]]:
bin_range = None
if feature_name in hist_config:
if StC.STATS_BIN_RANGE in hist_config[feature_name]:
bin_range = hist_config[feature_name][StC.STATS_BIN_RANGE]
elif "*" in hist_config:
default_config = hist_config["*"]
if StC.STATS_BIN_RANGE in default_config:
bin_range = default_config[StC.STATS_BIN_RANGE]
return bin_range
| NVFlare-main | nvflare/app_common/statistics/statistics_config_utils.py |
# Copyright (c) 2021, 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 abc import ABC, abstractmethod
from nvflare.apis.fl_component import FLComponent
from nvflare.apis.fl_context import FLContext
from nvflare.app_common.abstract.learnable import Learnable
class LearnablePersistor(FLComponent, ABC):
@abstractmethod
def load(self, fl_ctx: FLContext) -> Learnable:
"""Load the Learnable object.
Args:
fl_ctx: FLContext
Returns:
Learnable object loaded
"""
pass
@abstractmethod
def save(self, learnable: Learnable, fl_ctx: FLContext):
"""Persist the Learnable object.
Args:
learnable: the Learnable object to be saved
fl_ctx: FLContext
"""
pass
| NVFlare-main | nvflare/app_common/abstract/learnable_persistor.py |
# Copyright (c) 2021, 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 abc import abstractmethod
from nvflare.apis.fl_component import FLComponent
from nvflare.apis.fl_context import FLContext
class Formatter(FLComponent):
@abstractmethod
def format(self, fl_ctx: FLContext) -> str:
"""Format the data into human readable string.
Args:
fl_ctx (FLContext): FL Context object.
Returns:
str: Human readable string.
"""
pass
| NVFlare-main | nvflare/app_common/abstract/formatter.py |
# Copyright (c) 2021, 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 __future__ import annotations
from nvflare.fuel.utils import fobs
class Learnable(dict):
def is_empty(self):
return False
def to_bytes(self) -> bytes:
"""Method to serialize the Learnable object into bytes.
Returns:
object serialized in bytes.
"""
return fobs.dumps(self)
@classmethod
def from_bytes(cls, data: bytes):
"""Method to convert the object bytes into Learnable object.
Args:
data: a bytes object
Returns:
an object loaded by FOBS from data
"""
return fobs.loads(data)
| NVFlare-main | nvflare/app_common/abstract/learnable.py |
# Copyright (c) 2021, 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 abc import ABC, abstractmethod
from nvflare.apis.fl_component import FLComponent
from nvflare.apis.fl_context import FLContext
from nvflare.apis.shareable import Shareable
class Aggregator(FLComponent, ABC):
def reset(self, fl_ctx: FLContext):
"""Reset the internal state of the aggregator.
Args:
fl_ctx: FLContext
Returns:
"""
pass
@abstractmethod
def accept(self, shareable: Shareable, fl_ctx: FLContext) -> bool:
"""Accept the shareable submitted by the client.
Args:
shareable: submitted Shareable object
fl_ctx: FLContext
Returns:
first boolean to indicate if the contribution has been accepted.
"""
pass
@abstractmethod
def aggregate(self, fl_ctx: FLContext) -> Shareable:
"""Perform the aggregation for all the received Shareable from the clients.
Args:
fl_ctx: FLContext
Returns:
shareable
"""
pass
| NVFlare-main | nvflare/app_common/abstract/aggregator.py |
# Copyright (c) 2021, 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 abc import ABC, abstractmethod
from nvflare.apis.fl_component import FLComponent
from nvflare.apis.fl_context import FLContext
from nvflare.apis.shareable import Shareable
from nvflare.app_common.abstract.learnable import Learnable
class ShareableGenerator(FLComponent, ABC):
@abstractmethod
def learnable_to_shareable(self, model: Learnable, fl_ctx: FLContext) -> Shareable:
"""Generate the initial Shareable from the Learnable object.
Args:
model: model object
fl_ctx: FLContext
Returns:
shareable
"""
pass
@abstractmethod
def shareable_to_learnable(self, shareable: Shareable, fl_ctx: FLContext) -> Learnable:
"""Construct the Learnable object from Shareable.
Args:
shareable: shareable
fl_ctx: FLContext
Returns:
model object
"""
pass
| NVFlare-main | nvflare/app_common/abstract/shareable_generator.py |
# Copyright (c) 2023, 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 abc import abstractmethod
from typing import Union
class MetricComparator:
@abstractmethod
def compare(self, a, b) -> Union[int, float]:
"""Compare two metric values.
Metric values do not have to be numbers.
Args:
a: first metric value
b: second metric value
Returns: negative number if a < b; 0 if a == b; positive number if a > b.
"""
pass
| NVFlare-main | nvflare/app_common/abstract/metric_comparator.py |
# Copyright (c) 2023, 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 Any, Union
from nvflare.apis.fl_component import FLComponent
from nvflare.apis.fl_context import FLContext
from nvflare.apis.fl_exception import TaskExecutionError
from nvflare.app_common.abstract.fl_model import FLModel
class ModelLearner(FLComponent):
STATE = None
def __init__(self):
super().__init__()
self.engine = None
self.fl_ctx = None
self.workspace = None
self.shareable = None
self.args = None
self.site_name = None
self.job_id = None
self.app_root = None
self.job_root = None
self.workspace_root = None
self.abort_signal = None
self.current_round = 0
self.total_rounds = 0
def is_aborted(self) -> bool:
"""Check whether the task has been asked to abort by the framework.
Returns: whether the task has been asked to abort by the framework
"""
return self.abort_signal and self.abort_signal.triggered
def get_shareable_header(self, key: str, default=None):
"""Convenience method for getting specified header from the shareable.
Args:
key: name of the header
default: default value if the header doesn't exist
Returns: value of the header if it exists in the shareable; or the specified default if it doesn't.
"""
if not self.shareable:
return default
return self.shareable.get_header(key, default)
def get_context_prop(self, key: str, default=None):
"""Convenience method for getting specified property from the FL Context.
Args:
key: name of the property
default: default value if the prop doesn't exist in FL Context
Returns: value of the prop if it exists in the context; or the specified default if it doesn't.
"""
if not self.fl_ctx:
return default
assert isinstance(self.fl_ctx, FLContext)
return self.fl_ctx.get_prop(key, default)
def get_component(self, component_id: str) -> Any:
"""Get the specified component from the context
Args:
component_id: ID of the component
Returns: the specified component if it is defined; or None if not.
"""
if self.engine:
return self.engine.get_component(component_id)
else:
return None
def debug(self, msg: str):
"""Convenience method for logging a DEBUG message with contextual info
Args:
msg: the message to be logged
Returns:
"""
self.log_debug(self.fl_ctx, msg)
def info(self, msg: str):
"""Convenience method for logging an INFO message with contextual info
Args:
msg: the message to be logged
Returns:
"""
self.log_info(self.fl_ctx, msg)
def error(self, msg: str):
"""Convenience method for logging an ERROR message with contextual info
Args:
msg: the message to be logged
Returns:
"""
self.log_error(self.fl_ctx, msg)
def warning(self, msg: str):
"""Convenience method for logging a WARNING message with contextual info
Args:
msg: the message to be logged
Returns:
"""
self.log_warning(self.fl_ctx, msg)
def exception(self, msg: str):
"""Convenience method for logging an EXCEPTION message with contextual info
Args:
msg: the message to be logged
Returns:
"""
self.log_exception(self.fl_ctx, msg)
def critical(self, msg: str):
"""Convenience method for logging a CRITICAL message with contextual info
Args:
msg: the message to be logged
Returns:
"""
self.log_critical(self.fl_ctx, msg)
def stop_task(self, reason: str):
"""Stop the current task.
This method is to be called by the Learner's training or validation code when it runs into
a situation that the task processing cannot continue.
Args:
reason: why the task cannot continue
Returns:
"""
self.log_error(self.fl_ctx, f"Task stopped: {reason}")
raise TaskExecutionError(reason)
def initialize(self):
"""Called by the framework to initialize the Learner object.
This is called before the Learner can train or validate.
This is called only once.
"""
pass
def train(self, model: FLModel) -> Union[str, FLModel]:
"""Called by the framework to perform training. Can be called many times during the lifetime of the Learner.
Args:
model: the training input model
Returns: train result as a FLModel if successful; or return code as str if failed.
"""
pass
def get_model(self, model_name: str) -> Union[str, FLModel]:
"""Called by the framework to return the trained model from the Learner.
Args:
model_name: type of the model for validation
Returns: trained model; or return code if failed
"""
pass
def validate(self, model: FLModel) -> Union[str, FLModel]:
"""Called by the framework to validate the model with the specified weights in dxo
Args:
model: the FLModel object that contains model weights to be validated
Returns: validation metrics in FLModel if successful; or return code if failed.
"""
pass
def configure(self, model: FLModel):
"""Called by the framework to configure the Learner with the config info in the model
Args:
model: the object that contains config parameters
Returns: None
"""
pass
def abort(self):
"""Called by the framework for the Learner to gracefully abort the current task.
This could be caused by multiple reasons:
- user issued the abort command to stop the whole job
- Controller runs into some condition that requires the job to be aborted
"""
pass
def finalize(self):
"""Called by the framework to finalize the Learner (close/release resources gracefully) when
the job is finished.
After this call, the Learner will be destroyed.
Args:
"""
pass
| NVFlare-main | nvflare/app_common/abstract/model_learner.py |
# Copyright (c) 2021, 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.
| NVFlare-main | nvflare/app_common/abstract/__init__.py |
# Copyright (c) 2021, 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 abc import ABC, abstractmethod
from nvflare.apis.fl_context import FLContext
from nvflare.app_common.model_desc import ModelDescriptor
from .learnable_persistor import LearnablePersistor
from .model import ModelLearnable
from .persistor_filter import PersistorFilter
class ModelPersistor(LearnablePersistor, ABC):
def __init__(self, filter_id: str = None):
"""Abstract class.
Implementations will need to implement the `load_model()` and `save_model()`
methods to persist & load the current ModelLearnable.
Args:
filter_id: Optional string that defines a filter component that is applied to prepare the model to be saved,
e.g. for serialization of custom Python objects.
"""
super().__init__()
self.filter_id = filter_id
def load(self, fl_ctx: FLContext) -> ModelLearnable:
learnable = self.load_model(fl_ctx)
if self.filter_id:
_filter = fl_ctx.get_engine().get_component(self.filter_id)
if not isinstance(_filter, PersistorFilter):
raise ValueError(f"Expected filter to be of type `PersistorFilter` but got {type(filter)}")
learnable = _filter.process_post_load(learnable=learnable, fl_ctx=fl_ctx)
return learnable
def save(self, learnable: ModelLearnable, fl_ctx: FLContext):
if self.filter_id:
_filter = fl_ctx.get_engine().get_component(self.filter_id)
if not isinstance(_filter, PersistorFilter):
raise ValueError(f"Expected filter to be of type `PersistorFilter` but got {type(filter)}")
learnable = _filter.process_pre_save(learnable=learnable, fl_ctx=fl_ctx)
self.save_model(learnable, fl_ctx)
if self.filter_id:
_filter.process_post_save(learnable=learnable, fl_ctx=fl_ctx)
def get(self, model_file, fl_ctx: FLContext) -> object:
learnable = self.get_model(model_file, fl_ctx)
if self.filter_id:
_filter = fl_ctx.get_engine().get_component(self.filter_id)
if not isinstance(_filter, PersistorFilter):
raise ValueError(f"Expected filter to be of type `PersistorFilter` but got {type(filter)}")
learnable = _filter.process_post_get(learnable=learnable, fl_ctx=fl_ctx)
return learnable
@abstractmethod
def load_model(self, fl_ctx: FLContext) -> ModelLearnable:
"""Initialize and load the model.
Args:
fl_ctx: FLContext
Returns:
Model object
"""
pass
@abstractmethod
def save_model(self, model: ModelLearnable, fl_ctx: FLContext):
"""Persist the model object.
Args:
model: Model object to be saved
fl_ctx: FLContext
"""
pass
def get_model_inventory(self, fl_ctx: FLContext) -> {str: ModelDescriptor}:
"""Get the model inventory of the ModelPersister.
Args:
fl_ctx: FLContext
Returns: { model_kind: ModelDescriptor }
"""
pass
def get_model(self, model_file: str, fl_ctx: FLContext) -> ModelLearnable:
pass
| NVFlare-main | nvflare/app_common/abstract/model_persistor.py |
# Copyright (c) 2023, 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 abc import ABC, abstractmethod
from typing import Optional
from nvflare.apis.fl_context import FLContext
from nvflare.apis.shareable import Shareable
from nvflare.apis.signal import Signal
from nvflare.app_common.abstract.init_final_component import InitFinalComponent
from nvflare.app_common.utils.component_utils import check_component_type
class TaskHandler(InitFinalComponent, ABC):
"""TaskHandler focuses on computing and returning results only for given task."""
def __init__(self, local_comp_id: str, local_comp_type: type):
super().__init__()
self.fl_ctx = None
self.local_comp_id = local_comp_id
self.local_comp: Optional[InitFinalComponent] = None
self.target_local_comp_type: type = local_comp_type
def initialize(self, fl_ctx: FLContext):
"""
This is called when client is start Run. At this point
the server hasn't communicated to the local component yet.
Args:
fl_ctx: fl_ctx: FLContext of the running environment
"""
self.fl_ctx = fl_ctx
self.load_and_init_local_comp(fl_ctx)
def load_and_init_local_comp(self, fl_ctx):
engine = fl_ctx.get_engine()
local_comp: InitFinalComponent = engine.get_component(self.local_comp_id)
check_component_type(local_comp, self.target_local_comp_type)
local_comp.initialize(fl_ctx)
self.local_comp = local_comp
@abstractmethod
def execute_task(self, task_name: str, shareable: Shareable, fl_ctx: FLContext, abort_signal: Signal) -> Shareable:
"""Executes a task.
Args:
task_name: task name
shareable: input data
fl_ctx: FLContext
abort_signal (Signal): signal to check during execution to determine whether this task is aborted.
Returns:
Output data
"""
pass
def finalize(self, fl_ctx: FLContext):
if self.local_comp:
self.local_comp.finalize(fl_ctx)
self.local_comp = None
| NVFlare-main | nvflare/app_common/abstract/task_handler.py |
# Copyright (c) 2023, 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 nvflare.apis.fl_component import FLComponent
from nvflare.apis.fl_context import FLContext
from .model import Learnable
class PersistorFilter(FLComponent):
def process_post_load(self, learnable: Learnable, fl_ctx: FLContext) -> Learnable:
"""Filter process applied to the Learnable object after it was loaded in ModelPersistor's `load()` call.
Args:
learnable: Learnable
fl_ctx: FLContext
Returns:
a Learnable object
"""
return learnable
def process_pre_save(self, learnable: Learnable, fl_ctx: FLContext) -> Learnable:
"""Filter process applied to the Learnable object before its being saved in ModelPersistor's `save()` call.
Args:
learnable: Learnable
fl_ctx: FLContext
Returns:
a Learnable object
"""
return learnable
def process_post_save(self, learnable: Learnable, fl_ctx: FLContext) -> Learnable:
"""Filter process applied to the Learnable object after it's being saved in ModelPersistor's `save()` call.
Args:
learnable: Learnable
fl_ctx: FLContext
Returns:
a Learnable object
"""
return learnable
def process_post_get(self, learnable: Learnable, fl_ctx: FLContext) -> Learnable:
"""Filter process applied to the Learnable object after it was returned in ModelPersistor's `get()` call.
Args:
learnable: Learnable
fl_ctx: FLContext
Returns:
a Learnable object
"""
return learnable
| NVFlare-main | nvflare/app_common/abstract/persistor_filter.py |
# Copyright (c) 2022, 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 abc import ABC, abstractmethod
from nvflare.apis.fl_component import FLComponent
from nvflare.apis.fl_context import FLContext
class StatisticsWriter(FLComponent, ABC):
@abstractmethod
def save(self, data: dict, overwrite_existing: bool, fl_ctx: FLContext):
"""Save data.
To perform data privacy min_count check, failure_count is always required.
Args:
data: the data to be saved
overwrite_existing: whether or not to overwrite existing
fl_ctx: FLContext
Returns: None
"""
pass
| NVFlare-main | nvflare/app_common/abstract/statistics_writer.py |
# Copyright (c) 2023, 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 enum import Enum
from typing import Any, Dict, Optional, Union
from nvflare.apis.fl_constant import FLMetaKey
from nvflare.fuel.utils.validation_utils import check_object_type
class ParamsType(str, Enum):
FULL = "FULL"
DIFF = "DIFF"
class FLModelConst:
PARAMS_TYPE = "params_type"
PARAMS = "params"
OPTIMIZER_PARAMS = "optimizer_params"
METRICS = "metrics"
CURRENT_ROUND = "current_round"
TOTAL_ROUNDS = "total_rounds"
META = "meta"
class MetaKey(FLMetaKey):
pass
class FLModel:
def __init__(
self,
params_type: Union[None, str, ParamsType] = None,
params: Any = None,
optimizer_params: Any = None,
metrics: Optional[Dict] = None,
current_round: Optional[int] = None,
total_rounds: Optional[int] = None,
meta: Optional[Dict] = None,
):
"""
Args:
params_type: type of the parameters. It only describes the "params".
If params_type is None, params need to be None.
If params is provided but params_type is not provided, then it will be treated
as FULL.
params: model parameters, for example: model weights for deep learning.
optimizer_params: optimizer parameters.
For many cases, the optimizer parameters don't need to be transferred during FL training.
metrics: evaluation metrics such as loss and scores.
current_round: the current FL rounds. A round means round trip between client/server during training.
None for inference.
total_rounds: total number of FL rounds. A round means round trip between client/server during training.
None for inference.
meta: metadata dictionary used to contain any key-value pairs to facilitate the process.
"""
if params_type is None:
if params is not None:
params_type = ParamsType.FULL
else:
params_type = ParamsType(params_type)
if params_type == ParamsType.FULL or params_type == ParamsType.DIFF:
if params is None:
raise ValueError(f"params must be provided when params_type is {params_type}")
self.params_type = params_type
self.params = params
self.optimizer_params = optimizer_params
self.metrics = metrics
self.current_round = current_round
self.total_rounds = total_rounds
if meta is not None:
check_object_type("meta", meta, dict)
else:
meta = {}
self.meta = meta
def __str__(self):
return (
f"FLModel(params:{self.params}, params_type: {self.params_type},"
f" optimizer_params: {self.optimizer_params}, metrics: {self.metrics},"
f" current_round: {self.current_round}, meta: {self.meta})"
)
| NVFlare-main | nvflare/app_common/abstract/fl_model.py |
# Copyright (c) 2021, 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.
"""The Learnable in the deep learning domain is usually called Model by researchers.
This import simply lets you call the Learnable 'Model'.
Model Learnable is a dict that contains two items: weights and meta info
"""
from nvflare.apis.dxo import DXO, DataKind
from .learnable import Learnable
class ModelLearnableKey(object):
WEIGHTS = "weights"
META = "meta"
class ModelLearnable(Learnable):
def is_empty(self):
if self.get(ModelLearnableKey.WEIGHTS):
return False
else:
return True
def validate_model_learnable(model_learnable: ModelLearnable) -> str:
"""Check whether the specified model is a valid Model Shareable.
Args:
model_learnable (ModelLearnable): model to be validated
Returns:
str: error text or empty string if no error
"""
if not isinstance(model_learnable, ModelLearnable):
return "invalid model learnable: expect Model type but got {}".format(type(model_learnable))
if ModelLearnableKey.WEIGHTS not in model_learnable:
return "invalid model learnable: missing weights"
if ModelLearnableKey.META not in model_learnable:
return "invalid model learnable: missing meta"
return ""
def make_model_learnable(weights, meta_props) -> ModelLearnable:
ml = ModelLearnable()
ml[ModelLearnableKey.WEIGHTS] = weights
ml[ModelLearnableKey.META] = meta_props
return ml
def model_learnable_to_dxo(ml: ModelLearnable) -> DXO:
err = validate_model_learnable(ml)
if err:
raise ValueError(err)
return DXO(data_kind=DataKind.WEIGHTS, data=ml[ModelLearnableKey.WEIGHTS], meta=ml[ModelLearnableKey.META])
| NVFlare-main | nvflare/app_common/abstract/model.py |
# Copyright (c) 2023, 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 abc import ABC, abstractmethod
from nvflare.apis.fl_component import FLComponent
from nvflare.apis.fl_context import FLContext
class InitFinalComponent(FLComponent, ABC):
@abstractmethod
def initialize(self, fl_ctx: FLContext):
pass
@abstractmethod
def finalize(self, fl_ctx: FLContext):
pass
class InitFinalArgsComponent(InitFinalComponent, ABC):
@abstractmethod
def initialize(self, fl_ctx: FLContext, **kwargs):
pass
@abstractmethod
def finalize(self, fl_ctx: FLContext):
pass
| NVFlare-main | nvflare/app_common/abstract/init_final_component.py |
# Copyright (c) 2022, 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 abc import ABC, abstractmethod
from nvflare.apis.client import Client
from nvflare.apis.fl_component import FLComponent
from nvflare.apis.fl_context import FLContext
from nvflare.apis.shareable import Shareable
class ResponseProcessor(FLComponent, ABC):
@abstractmethod
def create_task_data(self, task_name: str, fl_ctx: FLContext) -> Shareable:
"""Create the task data for the process request to clients
This method is called at the beginning of the ResponseProcessor controller, e.g., in BroadcastAndProcess.
The internal state of the processor should be reset here, if the processor is used multiple times.
Args:
task_name: name of the task
fl_ctx: FL context
Returns: task data as a shareable
"""
pass
@abstractmethod
def process_client_response(self, client: Client, task_name: str, response: Shareable, fl_ctx: FLContext) -> bool:
"""Processes the response submitted by a client.
This method is called every time a response is received from a client.
Args:
client: the client that submitted response
task_name: name of the task that the response corresponds to
response: client submitted response
fl_ctx: FLContext
Returns:
boolean to indicate if the client data is acceptable.
If not acceptable, the control flow will exit.
"""
pass
@abstractmethod
def final_process(self, fl_ctx: FLContext) -> bool:
"""Perform the final process.
This method is called after received responses from all clients.
Args:
fl_ctx: FLContext
Returns:
boolean indicating whether the final response processing is successful.
If not successful, the control flow will exit.
"""
pass
| NVFlare-main | nvflare/app_common/abstract/response_processor.py |
# Copyright (c) 2023, 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 os
from abc import ABC, abstractmethod
from enum import Enum
from typing import Optional
from nvflare.apis.fl_context import FLContext
from nvflare.apis.shareable import Shareable
from nvflare.apis.signal import Signal
from nvflare.apis.workspace import Workspace
class LauncherCompleteStatus(str, Enum):
SUCCESS = "success"
FAILED = "failed"
class Launcher(ABC):
def initialize(self, fl_ctx: FLContext) -> None:
pass
def finalize(self, fl_ctx: FLContext) -> None:
pass
@staticmethod
def get_app_dir(fl_ctx: FLContext) -> Optional[str]:
"""Gets the deployed application directory."""
if fl_ctx is not None:
workspace: Workspace = fl_ctx.get_engine().get_workspace()
app_dir = workspace.get_app_dir(fl_ctx.get_job_id())
if app_dir is not None:
return os.path.abspath(app_dir)
return None
@abstractmethod
def launch_task(self, task_name: str, shareable: Shareable, fl_ctx: FLContext, abort_signal: Signal) -> bool:
"""Launches external system to handle a task.
Args:
task_name (str): task name.
shareable (Shareable): input shareable.
fl_ctx (FLContext): fl context.
abort_signal (Signal): signal to check during execution to determine whether this task is aborted.
Returns:
Whether launch success or not.
"""
pass
@abstractmethod
def wait_task(self, task_name: str, fl_ctx: FLContext, timeout: Optional[float] = None) -> LauncherCompleteStatus:
"""Waits for external system to end.
Args:
task_name (str): task name.
fl_ctx (FLContext): fl context.
timeout (optional, float): time to wait for task.
Returns:
The completion status of Launcher.
"""
pass
@abstractmethod
def stop_task(self, task_name: str, fl_ctx: FLContext) -> None:
"""Stops external system and free up resources.
Args:
task_name (str): task name.
fl_ctx (FLContext): fl context.
"""
pass
| NVFlare-main | nvflare/app_common/abstract/launcher.py |
# Copyright (c) 2022, 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 abc import ABC, abstractmethod
from enum import IntEnum
from typing import Dict, List, NamedTuple, Optional
from nvflare.apis.fl_context import FLContext
from nvflare.app_common.abstract.init_final_component import InitFinalComponent
"""
Statistics defines methods that user need to implement in order to calculate the local statistics
Only the metrics required by data privacy (such as count) or individual metrics of interested need to implement
"""
class DataType(IntEnum):
INT = 0
FLOAT = 1
STRING = 2
BYTES = 3
STRUCT = 4
DATETIME = 5
class BinRange(NamedTuple):
# The minimum value of the bucket, inclusive.
min_value: float
# The max value of the bucket, exclusive (unless the highValue is positive infinity).
max_value: float
class Bin(NamedTuple):
# The low value of the bucket, inclusive.
low_value: float
# The high value of the bucket, exclusive (unless the highValue is positive infinity).
high_value: float
# quantile sample count could be fractional
sample_count: float
class HistogramType(IntEnum):
STANDARD = 0
QUANTILES = 1
class Histogram(NamedTuple):
# The type of the histogram. A standard histogram has equal-width buckets.
# The quantiles type is used for when the histogram message is used to store
# quantile information (by using equal-count buckets with variable widths).
# The type of the histogram.
hist_type: HistogramType
# A list of buckets in the histogram, sorted from lowest bucket to highest bucket.
bins: List[Bin]
# An optional descriptive name of the histogram, to be used for labeling.
hist_name: Optional[str] = None
class Feature(NamedTuple):
feature_name: str
data_type: DataType
class StatisticConfig(NamedTuple):
# metric name
name: str
# metric configuration
config: dict
class Statistics(InitFinalComponent, ABC):
def initialize(self, fl_ctx: FLContext):
"""
This is called when client is start Run. At this point
the server hasn't communicated to the Statistics calculator yet.
Args:
fl_ctx: fl_ctx: FLContext of the running environment
"""
pass
def pre_run(
self,
statistics: List[str],
num_of_bins: Optional[Dict[str, Optional[int]]],
bin_ranges: Optional[Dict[str, Optional[List[float]]]],
):
"""This method is the initial hand-shake, where controller pass all the requested statistics configuration to client.
This method invocation is optional and Configured via controller argument. If it is configured,
this method will be called before all other statistic calculation methods
Args:
statistics: list of statistics to be calculated, count, sum, etc.
num_of_bins: if histogram statistic is required, num_of_bins will be specified for each feature.
"*" implies default feature.
None value implies the feature's number of bins is not specified.
bin_ranges: if histogram statistic is required, bin_ranges for the feature may be provided.
if bin_ranges is None. no bin_range is provided for any feature.
if bins_range is not None, but bins_ranges['feature_A'] is None, means that for specific feature
'feature_A', the bin_range is not provided by user.
Returns: Dict
"""
return {}
@abstractmethod
def features(self) -> Dict[str, List[Feature]]:
"""Return Features for each dataset.
For example, if we have training and test datasets,
the method will return
{ "train": features1, "test": features2}
where features1,2 are the list of Features which contains feature name and DataType
Returns: Dict[<dataset_name>, List[Feature]]
Raises:
NotImplementedError
"""
raise NotImplementedError
@abstractmethod
def count(self, dataset_name: str, feature_name: str) -> int:
"""Returns record count for given dataset and feature.
to perform data privacy min_count check, count is always required
Args:
dataset_name:
feature_name:
Returns: number of total records
Raises:
NotImplementedError
"""
raise NotImplementedError
def sum(self, dataset_name: str, feature_name: str) -> float:
"""Calculate local sums for given dataset and feature.
Args:
dataset_name:
feature_name:
Returns: sum of all records
Raises:
NotImplementedError will be raised when sum statistic is configured but not implemented. If the sum is not
configured to be calculated, no need to implement this method and NotImplementedError will not be raised.
"""
raise NotImplementedError
def mean(self, dataset_name: str, feature_name: str) -> float:
"""
Args:
dataset_name: dataset name
feature_name: feature name
Returns: mean (average) value
Raises:
NotImplementedError will be raised when mean statistic is configured but not implemented. If the mean is not
configured to be calculated, no need to implement this method and NotImplementedError will not be raised.
"""
raise NotImplementedError
def stddev(self, dataset_name: str, feature_name: str) -> float:
"""Get local stddev value for given dataset and feature.
Args:
dataset_name: dataset name
feature_name: feature name
Returns: local standard deviation
Raises:
NotImplementedError will be raised when stddev statistic is configured but not implemented. If the stddev is not
configured to be calculated, no need to implement this method and NotImplementedError will not be raised.
"""
raise NotImplementedError
def variance_with_mean(
self,
dataset_name: str,
feature_name: str,
global_mean: float,
global_count: float,
) -> float:
"""Calculate the variance with the given mean and count values.
This is not local variance based on the local mean values.
The calculation should be::
m = global mean
N = global Count
variance = (sum ( x - m)^2))/ (N-1)
This is used to calculate global standard deviation.
Therefore, this method must be implemented if stddev statistic is requested
Args:
dataset_name: dataset name
feature_name: feature name
global_mean: global mean value
global_count: total count records across all sites
Returns: variance result
Raises:
NotImplementedError will be raised when stddev statistic is configured but not implemented. If the stddev is not
configured to be calculated, no need to implement this method and NotImplementedError will not be raised.
"""
raise NotImplementedError
def histogram(
self, dataset_name: str, feature_name: str, num_of_bins: int, global_min_value: float, global_max_value: float
) -> Histogram:
"""
Args:
dataset_name: dataset name
feature_name: feature name
num_of_bins: number of bins or buckets
global_min_value: global min value for the histogram range
global_max_value: global max value for the histogram range
Returns: histogram
Raises:
NotImplementedError will be raised when histogram statistic is configured but not implemented. If the histogram
is not configured to be calculated, no need to implement this method and NotImplementedError will not be raised.
"""
raise NotImplementedError
def max_value(self, dataset_name: str, feature_name: str) -> float:
"""Returns max value.
This method is only needed when "histogram" statistic is configured and the histogram range is not specified.
And the histogram range needs to dynamically estimated based on the client's local min/max values.
this method returns local max value. The actual max value will not directly return to the FL server.
the data privacy policy will add additional noise to the estimated value.
Args:
dataset_name: dataset name
feature_name: feature name
Returns: local max value
Raises:
NotImplementedError will be raised when histogram statistic is configured and histogram range for the
given feature is not specified, and this method is not implemented. If the histogram
is not configured to be calculated; or the given feature histogram range is already specified.
no need to implement this method and NotImplementedError will not be raised.
"""
raise NotImplementedError
def min_value(self, dataset_name: str, feature_name: str) -> float:
"""Returns min value.
This method is only needed when "histogram" statistic is configured and the histogram range is not specified.
And the histogram range needs to dynamically estimated based on the client's local min/max values.
this method returns local min value. The actual min value will not directly return to the FL server.
the data privacy policy will add additional noise to the estimated value.
Args:
dataset_name: dataset name
feature_name: feature name
Returns: local min value
Raises:
NotImplementedError will be raised when histogram statistic is configured and histogram range for the
given feature is not specified, and this method is not implemented. If the histogram
is not configured to be calculated; or the given feature histogram range is already specified.
no need to implement this method and NotImplementedError will not be raised.
"""
raise NotImplementedError
def failure_count(self, dataset_name: str, feature_name: str) -> int:
"""Return failed count for given dataset and feature.
To perform data privacy min_count check, failure_count is always required.
Args:
dataset_name:
feature_name:
Returns: number of failure records, default to 0
"""
return 0
def finalize(self, fl_ctx: FLContext):
"""Called to finalize the Statistic calculator (close/release resources gracefully).
After this call, the Learner will be destroyed.
"""
pass
| NVFlare-main | nvflare/app_common/abstract/statistics_spec.py |
# Copyright (c) 2021, 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 nvflare.apis.fl_component import FLComponent
from nvflare.apis.fl_context import FLContext
from nvflare.apis.shareable import ReturnCode, Shareable, make_reply
from nvflare.apis.signal import Signal
class Learner(FLComponent):
def initialize(self, parts: dict, fl_ctx: FLContext):
"""Initialize the Learner object. This is called before the Learner can train or validate.
This is called only once.
Args:
parts: components to be used by the Trainer
fl_ctx: FLContext of the running environment
"""
pass
def train(self, data: Shareable, fl_ctx: FLContext, abort_signal: Signal) -> Shareable:
"""Called to perform training. Can be called many times during the lifetime of the Learner.
Args:
data: the training input data (e.g. model weights)
fl_ctx: FLContext of the running environment
abort_signal: signal to abort the train
Returns: train result in Shareable
"""
return make_reply(ReturnCode.TASK_UNSUPPORTED)
def get_model_for_validation(self, model_name: str, fl_ctx: FLContext) -> Shareable:
"""Called to return the trained model from the Learner.
Args:
model_name: type of the model for validation
fl_ctx: FLContext of the running environment
Returns: trained model for validation
"""
return make_reply(ReturnCode.TASK_UNSUPPORTED)
def validate(self, data: Shareable, fl_ctx: FLContext, abort_signal: Signal) -> Shareable:
"""Called to perform validation. Can be called many times during the lifetime of the Learner.
Args:
data: the training input data (e.g. model weights)
fl_ctx: FLContext of the running environment
abort_signal: signal to abort the train
Returns: validate result in Shareable
"""
return make_reply(ReturnCode.TASK_UNSUPPORTED)
def abort(self, fl_ctx: FLContext):
"""Called (from another thread) to abort the current task (validate or train).
Note: this is to abort the current task only, not the Trainer. After aborting, the Learner.
may still be called to perform another task.
Args:
fl_ctx: FLContext of the running environment
"""
pass
def finalize(self, fl_ctx: FLContext):
"""Called to finalize the Learner (close/release resources gracefully).
After this call, the Learner will be destroyed.
Args:
fl_ctx: FLContext of the running environment
"""
pass
| NVFlare-main | nvflare/app_common/abstract/learner_spec.py |
# Copyright (c) 2021, 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 List
from nvflare.apis.dxo import DXO
from nvflare.apis.fl_component import FLComponent
from nvflare.apis.fl_context import FLContext
class ModelLocator(FLComponent):
def get_model_names(self, fl_ctx: FLContext) -> List[str]:
"""List the name of the models.
Args:
fl_ctx (FLContext): FL Context object
Returns:
List[str]: List of names for models
"""
pass
def locate_model(self, model_name, fl_ctx: FLContext) -> DXO:
"""Locate a single model by it's name.
Args:
model_name (str): Name of the model.
fl_ctx (FLContext): FL Context object.
Returns:
DXO: a DXO object
"""
pass
| NVFlare-main | nvflare/app_common/abstract/model_locator.py |
# Copyright (c) 2021, 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 abc import ABC, abstractmethod
from nvflare.apis.fl_context import FLContext
class ModelProcessor(ABC):
@abstractmethod
def extract_model(self, network, multi_processes: bool, model_vars: dict, fl_ctx: FLContext) -> dict:
"""Call to extract the current model from the training network.
Args:
network: training network
multi_processes: boolean to indicates if it's a multi-processes
model_vars: global model dict
fl_ctx: FLContext
Returns:
a dictionary representing the model
"""
pass
@abstractmethod
def apply_model(self, network, multi_processes: bool, model_params: dict, fl_ctx: FLContext, options=None):
"""Call to apply the model parameters to the training network.
Args:
network: training network
multi_processes: boolean to indicates if it's a multi-processes
model_params: model parameters to apply
fl_ctx: FLContext
options: optional information that can be used for this process
"""
pass
| NVFlare-main | nvflare/app_common/abstract/model_processor.py |
# Copyright (c) 2021, 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 List, Union
import numpy as np
from nvflare.apis.dxo import DXO, DataKind, MetaKey
from nvflare.apis.dxo_filter import DXOFilter
from nvflare.apis.fl_context import FLContext
from nvflare.apis.shareable import Shareable
class PercentilePrivacy(DXOFilter):
def __init__(self, percentile=10, gamma=0.01, data_kinds: List[str] = None):
"""Implementation of "largest percentile to share" privacy preserving policy.
Shokri and Shmatikov, Privacy-preserving deep learning, CCS '15
Args:
percentile (int, optional): Only abs diff greater than this percentile is updated.
Allowed range 0..100. Defaults to 10.
gamma (float, optional): The upper limit to truncate abs values of weight diff. Defaults to 0.01. Any weight diff with abs<gamma will become 0.
data_kinds: kinds of DXO to filter
"""
if not data_kinds:
data_kinds = [DataKind.WEIGHT_DIFF, DataKind.WEIGHTS]
super().__init__(supported_data_kinds=[DataKind.WEIGHTS, DataKind.WEIGHT_DIFF], data_kinds_to_filter=data_kinds)
# must be in 0..100, only update abs diff greater than percentile
self.percentile = percentile
# must be positive
self.gamma = gamma # truncate absolute value of delta W
def process_dxo(self, dxo: DXO, shareable: Shareable, fl_ctx: FLContext) -> Union[None, DXO]:
"""Compute the percentile on the abs delta_W.
Only share the params where absolute delta_W greater than
the percentile value
Args:
dxo: information from client
shareable: that the dxo belongs to
fl_ctx: context provided by workflow
Returns: filtered dxo
"""
self.log_debug(fl_ctx, "inside filter")
self.logger.debug("check gamma")
if self.gamma <= 0:
self.log_debug(fl_ctx, "no partial model: gamma: {}".format(self.gamma))
return None
if self.percentile < 0 or self.percentile > 100:
self.log_debug(fl_ctx, "no partial model: percentile: {}".format(self.percentile))
return None # do nothing
# invariant to local steps
model_diff = dxo.data
total_steps = dxo.get_meta_prop(MetaKey.NUM_STEPS_CURRENT_ROUND, 1)
delta_w = {name: model_diff[name] / total_steps for name in model_diff}
# abs delta
all_abs_values = np.concatenate([np.abs(delta_w[name].ravel()) for name in delta_w])
cutoff = np.percentile(a=all_abs_values, q=self.percentile, overwrite_input=False)
self.log_info(
fl_ctx,
f"Max abs delta_w: {np.max(all_abs_values)}, Min abs delta_w: {np.min(all_abs_values)},"
f"cutoff: {cutoff}, scale: {total_steps}.",
)
for name in delta_w:
diff_w = delta_w[name]
if np.ndim(diff_w) == 0: # single scalar, no clipping
delta_w[name] = diff_w * total_steps
continue
selector = (diff_w > -cutoff) & (diff_w < cutoff)
diff_w[selector] = 0.0
diff_w = np.clip(diff_w, a_min=-self.gamma, a_max=self.gamma)
delta_w[name] = diff_w * total_steps
dxo.data = delta_w
return dxo
| NVFlare-main | nvflare/app_common/filters/percentile_privacy.py |
# Copyright (c) 2021, 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 Union
import numpy as np
from nvflare.apis.dxo import DXO, DataKind, MetaKey
from nvflare.apis.dxo_filter import DXOFilter
from nvflare.apis.fl_context import FLContext
from nvflare.apis.shareable import Shareable
class SVTPrivacy(DXOFilter):
def __init__(
self, fraction=0.1, epsilon=0.1, noise_var=0.1, gamma=1e-5, tau=1e-6, data_kinds: [str] = None, replace=True
):
"""Implementation of the standard Sparse Vector Technique (SVT) differential privacy algorithm.
lambda_rho = gamma * 2.0 / epsilon
threshold = tau + np.random.laplace(scale=lambda_rho)
Args:
fraction (float, optional): used to determine dataset threshold. Defaults to 0.1.
epsilon (float, optional): Defaults to 0.1.
noise_var (float, optional): additive noise. Defaults to 0.1.
gamma (float, optional): Defaults to 1e-5.
tau (float, optional): Defaults to 1e-6.
data_kinds (str, optional): Defaults to None.
replace (bool): whether to sample with replacement. Defaults to True.
"""
if not data_kinds:
data_kinds = [DataKind.WEIGHT_DIFF, DataKind.WEIGHTS]
super().__init__(supported_data_kinds=[DataKind.WEIGHTS, DataKind.WEIGHT_DIFF], data_kinds_to_filter=data_kinds)
self.frac = fraction # fraction of the model to upload
self.eps_1 = epsilon
self.eps_2 = None # to be derived from eps_1
self.eps_3 = noise_var
self.gamma = gamma
self.tau = tau
self.replace = replace
def process_dxo(self, dxo: DXO, shareable: Shareable, fl_ctx: FLContext) -> Union[None, DXO]:
"""Compute the differentially private SVT.
Args:
dxo: information from client
shareable: that the dxo belongs to
fl_ctx: context provided by workflow
Returns: filtered result.
"""
self.log_debug(fl_ctx, "inside filter")
model_diff = dxo.data
total_steps = dxo.get_meta_prop(MetaKey.NUM_STEPS_CURRENT_ROUND, 1)
delta_w = np.concatenate([model_diff[name].ravel() / np.float64(total_steps) for name in sorted(model_diff)])
self.log_info(
fl_ctx,
"Delta_w: Max abs: {}, Min abs: {}, Median abs: {}.".format(
np.max(np.abs(delta_w)), np.min(np.abs(delta_w)), np.median(np.abs(delta_w))
),
)
# precompute thresholds
n_upload = np.minimum(np.ceil(np.float64(delta_w.size) * self.frac), np.float64(delta_w.size))
# eps_1: threshold with noise
lambda_rho = self.gamma * 2.0 / self.eps_1
threshold = self.tau + np.random.laplace(scale=lambda_rho)
# eps_2: query with noise
self.eps_2 = self.eps_1 * (2.0 * n_upload) ** (2.0 / 3.0)
lambda_nu = self.gamma * 4.0 * n_upload / self.eps_2
self.logger.info(
"total params: %s, epsilon: %s, "
"perparam budget %s, threshold tau: %s + f(eps_1) = %s, "
"clip gamma: %s",
delta_w.size,
self.eps_1,
self.eps_1 / n_upload,
self.tau,
threshold,
self.gamma,
)
# selecting weights with additive noise
accepted, candidate_idx = [], np.arange(delta_w.size)
_clipped_w = np.abs(np.clip(delta_w, a_min=-self.gamma, a_max=self.gamma))
while len(accepted) < n_upload:
nu_i = np.random.laplace(scale=lambda_nu, size=candidate_idx.shape)
above_threshold = (_clipped_w[candidate_idx] + nu_i) >= threshold
accepted += candidate_idx[above_threshold].tolist()
candidate_idx = candidate_idx[~above_threshold]
self.log_info(fl_ctx, "selected {} responses, requested {}".format(len(accepted), n_upload))
accepted = np.random.choice(accepted, size=np.int64(n_upload), replace=self.replace)
# eps_3 return with noise
noise = np.random.laplace(scale=self.gamma * 2.0 / self.eps_3, size=accepted.shape)
self.log_info(fl_ctx, "noise max: {}, median {}".format(np.max(np.abs(noise)), np.median(np.abs(noise))))
delta_w[accepted] = np.clip(delta_w[accepted] + noise, a_min=-self.gamma, a_max=self.gamma)
candidate_idx = list(set(np.arange(delta_w.size)) - set(accepted))
delta_w[candidate_idx] = 0.0
# resume original format
dp_w, _start = {}, 0
for name in sorted(model_diff):
if np.ndim(model_diff[name]) == 0:
dp_w[name] = model_diff[name]
_start += 1
continue
value = delta_w[_start : (_start + model_diff[name].size)]
dp_w[name] = value.reshape(model_diff[name].shape) * np.float64(total_steps)
_start += model_diff[name].size
# We update the shareable weights only. Headers are unchanged.
dxo.data = dp_w
return dxo
| NVFlare-main | nvflare/app_common/filters/svt_privacy.py |
# Copyright (c) 2021, 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 .exclude_vars import ExcludeVars
from .percentile_privacy import PercentilePrivacy
from .svt_privacy import SVTPrivacy
__all__ = ["PercentilePrivacy", "SVTPrivacy", "ExcludeVars"]
| NVFlare-main | nvflare/app_common/filters/__init__.py |
# Copyright (c) 2021, 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 re
from typing import List, Union
from nvflare.apis.dxo import DataKind
from nvflare.apis.dxo_filter import DXO, DXOFilter
from nvflare.apis.fl_context import FLContext
from nvflare.apis.shareable import Shareable
class ExcludeVars(DXOFilter):
def __init__(self, exclude_vars: Union[List[str], str, None] = None, data_kinds: List[str] = None):
"""Exclude/Remove variables from Shareable.
Args:
exclude_vars (Union[List[str], str, None] , optional): variables/layer names to be excluded.
data_kinds: kinds of DXO object to filter
Notes:
Based on different types of exclude_vars, this filter has different behavior:
if a list of variable/layer names, only specified variables will be excluded.
if a string, it will be converted into a regular expression, only matched variables will be excluded.
if not provided or other formats the Shareable remains unchanged.
"""
if not data_kinds:
data_kinds = [DataKind.WEIGHT_DIFF, DataKind.WEIGHTS]
super().__init__(supported_data_kinds=[DataKind.WEIGHTS, DataKind.WEIGHT_DIFF], data_kinds_to_filter=data_kinds)
self.exclude_vars = exclude_vars
self.skip = False
if self.exclude_vars is not None:
if not (isinstance(self.exclude_vars, list) or isinstance(self.exclude_vars, str)):
self.skip = True
self.logger.debug(
"Need to provide a list of layer names or a string for regex matching, but got {}".format(
type(self.exclude_vars)
)
)
return
if isinstance(self.exclude_vars, list):
for var in self.exclude_vars:
if not isinstance(var, str):
self.skip = True
self.logger.debug(
"encrypt_layers needs to be a list of layer names to encrypt, but contains element of type {}".format(
type(var)
)
)
return
self.logger.debug(f"Excluding {self.exclude_vars} from shareable")
elif isinstance(self.exclude_vars, str):
self.exclude_vars = re.compile(self.exclude_vars) if self.exclude_vars else None
if self.exclude_vars is None:
self.skip = True
self.logger.debug(f'Excluding all layers based on regex matches with "{self.exclude_vars}"')
else:
self.logger.debug("Not excluding anything")
self.skip = True
def process_dxo(self, dxo: DXO, shareable: Shareable, fl_ctx: FLContext) -> Union[None, DXO]:
"""Called by upper layer to remove variables in weights/weight_diff dictionary.
When the return code of shareable is not ReturnCode.OK, this
function will not perform any process and returns the shareable back.
Args:
dxo (DXO): DXO to be filtered.
shareable: that the dxo belongs to
fl_ctx (FLContext): only used for logging.
Returns: filtered dxo
"""
if self.skip:
return None
weights = dxo.data
# remove variables
n_excluded = 0
var_names = list(weights.keys()) # make a copy of keys
n_vars = len(var_names)
for var_name in var_names:
if (isinstance(self.exclude_vars, re.Pattern) and self.exclude_vars.search(var_name)) or (
isinstance(self.exclude_vars, list) and var_name in self.exclude_vars
):
self.log_debug(fl_ctx, f"Excluding {var_name}")
weights.pop(var_name, None)
n_excluded += 1
if isinstance(self.exclude_vars, re.Pattern) and n_excluded == 0:
self.log_warning(fl_ctx, f"No matching layers found with regex {self.exclude_vars}")
self.log_debug(fl_ctx, f"Excluded {n_excluded} of {n_vars} variables. {len(weights.keys())} remaining.")
dxo.data = weights
return dxo
| NVFlare-main | nvflare/app_common/filters/exclude_vars.py |
# Copyright (c) 2022, 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 List, Optional, Union
from nvflare.apis.dxo import DXO, DataKind
from nvflare.apis.dxo_filter import DXOFilter
from nvflare.apis.fl_context import FLContext
from nvflare.apis.shareable import Shareable
from nvflare.app_common.app_constant import StatisticsConstants as StC
from nvflare.app_common.statistics.statistics_privacy_cleanser import StatisticsPrivacyCleanser
from nvflare.fuel.utils import fobs
class StatisticsPrivacyFilter(DXOFilter):
def __init__(self, result_cleanser_ids: List[str]):
super().__init__(supported_data_kinds=[DataKind.STATISTICS], data_kinds_to_filter=[DataKind.STATISTICS])
self.result_cleanser_ids = result_cleanser_ids
def get_cleansers(self, result_checker_ids: List[str], fl_ctx: FLContext) -> List[StatisticsPrivacyCleanser]:
filters = []
for cleanser_id in result_checker_ids:
c = fl_ctx.get_engine().get_component(cleanser_id)
# disabled component return None
if c:
if not isinstance(c, StatisticsPrivacyCleanser):
msg = "component identified by {} type {} is not type of StatisticsPrivacyCleanser".format(
cleanser_id, type(c)
)
raise ValueError(msg)
filters.append(c)
return filters
def process_dxo(self, dxo: DXO, shareable: Shareable, fl_ctx: FLContext) -> Union[None, DXO]:
if dxo.data_kind == DataKind.STATISTICS:
self.log_info(fl_ctx, "start StatisticsPrivacyFilter")
cleansers: List[StatisticsPrivacyCleanser] = self.get_cleansers(self.result_cleanser_ids, fl_ctx)
client_name = fl_ctx.get_identity_name()
self.log_info(fl_ctx, f"apply StatisticPrivacyFilter for client {client_name}")
dxo1 = self.filter_stats_statistics(dxo, client_name, cleansers)
self.log_info(fl_ctx, "end StatisticsPrivacyFilter")
return dxo1
def filter_stats_statistics(
self, dxo: DXO, client_name: str, filters: List[StatisticsPrivacyCleanser]
) -> Optional[DXO]:
client_result = dxo.data
statistics_task = client_result[StC.STATISTICS_TASK_KEY]
statistics = fobs.loads(client_result[statistics_task])
statistics_modified = False
for f in filters:
(statistics, modified) = f.apply(statistics, client_name)
statistics_modified = statistics_modified or modified
dxo1 = dxo
if statistics_modified:
client_result[statistics_task] = fobs.dumps(statistics)
dxo1 = DXO(data_kind=DataKind.STATISTICS, data=client_result)
return dxo1
| NVFlare-main | nvflare/app_common/filters/statistics_privacy_filter.py |
# Copyright (c) 2021, 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 Union
from nvflare.apis.dxo import DXO, DataKind, MetaKey, from_shareable
from nvflare.apis.dxo_filter import DXOFilter
from nvflare.apis.fl_constant import FLContextKey
from nvflare.apis.fl_context import FLContext
from nvflare.apis.shareable import Shareable
class ConvertWeights(DXOFilter):
WEIGHTS_TO_DIFF = "weights_to_diff"
DIFF_TO_WEIGHTS = "diff_to_weights"
def __init__(self, direction: str):
"""Convert WEIGHTS to WEIGHT_DIFF or vice versa.
Args:
direction (str): control conversion direction. Either weights_to_diff or diff_to_weights.
Raises:
ValueError: when the direction string is neither weights_to_diff nor diff_to_weights
"""
DXOFilter.__init__(
self, supported_data_kinds=[DataKind.WEIGHT_DIFF, DataKind.WEIGHTS], data_kinds_to_filter=None
)
if direction not in (self.WEIGHTS_TO_DIFF, self.DIFF_TO_WEIGHTS):
raise ValueError(
f"invalid convert direction {direction}: must be in {(self.WEIGHTS_TO_DIFF, self.DIFF_TO_WEIGHTS)}"
)
self.direction = direction
def _get_base_weights(self, fl_ctx: FLContext):
task_data = fl_ctx.get_prop(FLContextKey.TASK_DATA, None)
if not isinstance(task_data, Shareable):
self.log_error(fl_ctx, f"invalid task data: expect Shareable but got {type(task_data)}")
return None
try:
dxo = from_shareable(task_data)
except ValueError:
self.log_error(fl_ctx, "invalid task data: no DXO")
return None
if dxo.data_kind != DataKind.WEIGHTS:
self.log_info(fl_ctx, f"ignored task: expect data to be WEIGHTS but got {dxo.data_kind}")
return None
processed_algo = dxo.get_meta_prop(MetaKey.PROCESSED_ALGORITHM, None)
if processed_algo:
self.log_info(fl_ctx, f"ignored task since its processed by {processed_algo}")
return None
return dxo.data
def process_dxo(self, dxo: DXO, shareable: Shareable, fl_ctx: FLContext) -> Union[None, DXO]:
"""Called by runners to perform weight conversion.
Args:
dxo (DXO): dxo to be processed.
shareable: the shareable that the dxo belongs to
fl_ctx (FLContext): this context must include TASK_DATA, which is another shareable containing base weights.
If not, the input shareable will be returned.
Returns: filtered result
"""
base_weights = self._get_base_weights(fl_ctx)
if not base_weights:
return None
processed_algo = dxo.get_meta_prop(MetaKey.PROCESSED_ALGORITHM, None)
if processed_algo:
self.log_info(fl_ctx, f"cannot process task result since its processed by {processed_algo}")
return None
if self.direction == self.WEIGHTS_TO_DIFF:
if dxo.data_kind != DataKind.WEIGHTS:
self.log_warning(fl_ctx, f"cannot process task result: expect WEIGHTS but got {dxo.data_kind}")
return None
new_weights = dxo.data
for k, _ in new_weights.items():
if k in base_weights:
new_weights[k] -= base_weights[k]
dxo.data_kind = DataKind.WEIGHT_DIFF
else:
# diff to weights
if dxo.data_kind != DataKind.WEIGHT_DIFF:
self.log_warning(fl_ctx, f"cannot process task result: expect WEIGHT_DIFF but got {dxo.data_kind}")
return None
new_weights = dxo.data
for k, _ in new_weights.items():
if k in base_weights:
new_weights[k] += base_weights[k]
dxo.data_kind = DataKind.WEIGHTS
return dxo
| NVFlare-main | nvflare/app_common/filters/convert_weights.py |
# Copyright (c) 2022, 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 List, Union
from nvflare.apis.dxo_filter import DXO, DXOFilter
from nvflare.apis.filter import ContentBlockedException
from nvflare.apis.fl_context import FLContext
from nvflare.apis.shareable import Shareable
class DXOBlocker(DXOFilter):
def __init__(self, data_kinds: List[str], allow_data_kinds: bool = False):
"""Block certain kinds of DXO objects.
Args:
allow_data_kinds: allow or block configured data kinds. If True, block everything not in
the list; If False, block everything in the configured list.
data_kinds: kinds of DXO object to block
"""
super().__init__(supported_data_kinds=[], data_kinds_to_filter=[]) # support all kinds
if not data_kinds:
raise ValueError("data_kinds must be non-empty")
if not isinstance(data_kinds, list):
raise ValueError(f"data_kinds must be a list but got {type(data_kinds)}")
if not all(isinstance(e, str) for e in data_kinds):
raise ValueError("data_kinds must be a list of str but contains invalid element")
self.configured_data_kinds = data_kinds
self.allow_data_kinds = allow_data_kinds
def process_dxo(self, dxo: DXO, shareable: Shareable, fl_ctx: FLContext) -> Union[None, DXO]:
"""
Args:
dxo (DXO): DXO to be filtered.
shareable: that the dxo belongs to
fl_ctx (FLContext): only used for logging.
Returns: filtered dxo
"""
if self.allow_data_kinds:
if dxo.data_kind in self.configured_data_kinds:
return None
else:
raise ContentBlockedException(f"DXO kind {dxo.data_kind} is blocked")
else:
if dxo.data_kind not in self.configured_data_kinds:
return None
else:
raise ContentBlockedException(f"DXO kind {dxo.data_kind} is blocked")
| NVFlare-main | nvflare/app_common/filters/dxo_blocker.py |
# Copyright (c) 2022, 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.
| NVFlare-main | nvflare/app_common/storages/__init__.py |
# Copyright (c) 2022, 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 ast
import json
import logging
import os
import shutil
import uuid
from pathlib import Path
from typing import List, Tuple
from nvflare.apis.storage import DATA, MANIFEST, META, StorageException, StorageSpec
from nvflare.apis.utils.format_check import validate_class_methods_args
from nvflare.security.logging import secure_format_exception
log = logging.getLogger(__name__)
def _write(path: str, content):
tmp_path = path + "_" + str(uuid.uuid4())
try:
Path(os.path.dirname(path)).mkdir(parents=True, exist_ok=True)
with open(tmp_path, "wb") as f:
f.write(content)
f.flush()
os.fsync(f.fileno())
except Exception as e:
if os.path.isfile(tmp_path):
os.remove(tmp_path)
raise StorageException(f"failed to write content: {secure_format_exception(e)}")
if os.path.exists(tmp_path):
os.rename(tmp_path, path)
def _read(path: str) -> bytes:
try:
with open(path, "rb") as f:
content = f.read()
except Exception as e:
raise StorageException(f"failed to read content: {secure_format_exception(e)}")
return content
def _object_exists(uri: str):
"""Checks whether an object exists at specified directory."""
data_exists = os.path.isfile(os.path.join(uri, "data"))
meta_exists = os.path.isfile(os.path.join(uri, "meta"))
return all((os.path.isabs(uri), os.path.isdir(uri), data_exists, meta_exists))
@validate_class_methods_args
class FilesystemStorage(StorageSpec):
def __init__(self, root_dir=os.path.abspath(os.sep), uri_root="/"):
"""Init FileSystemStorage.
Uses local filesystem to persist objects, with absolute paths as object URIs.
Args:
root_dir: the absolute path on the filesystem to store things
uri_root: serving as the root of the storage. All URIs are rooted at this uri_root.
"""
if not os.path.isabs(root_dir):
raise ValueError(f"root_dir {root_dir} must be an absolute path.")
if os.path.exists(root_dir) and not os.path.isdir(root_dir):
raise ValueError(f"root_dir {root_dir} exists but is not a directory.")
if not os.path.exists(root_dir):
os.makedirs(root_dir, exist_ok=False)
self.root_dir = root_dir
self.uri_root = uri_root
def _save_data(self, data, destination: str):
if isinstance(data, bytes):
_write(destination, data)
elif isinstance(data, str):
# path to file that contains data
if not os.path.exists(data):
raise FileNotFoundError(f"file {data} does not exist")
if not os.path.isfile(data):
raise ValueError(f"{data} is not a valid file")
shutil.copyfile(data, destination)
else:
raise ValueError(f"expect data to be bytes or file name but got {type(data)}")
def create_object(self, uri: str, data, meta: dict, overwrite_existing: bool = False):
"""Creates an object.
Args:
uri: URI of the object
data: content of the object
meta: meta of the object
overwrite_existing: whether to overwrite the object if already exists
Raises:
TypeError: if invalid argument types
StorageException:
- if error creating the object
- if object already exists and overwrite_existing is False
- if object will be at a non-empty directory
IOError: if error writing the object
"""
full_uri = os.path.join(self.root_dir, uri.lstrip(self.uri_root))
if _object_exists(full_uri) and not overwrite_existing:
raise StorageException("object {} already exists and overwrite_existing is False".format(uri))
if not _object_exists(full_uri) and os.path.isdir(full_uri) and os.listdir(full_uri):
raise StorageException("cannot create object {} at nonempty directory".format(uri))
data_path = os.path.join(full_uri, DATA)
meta_path = os.path.join(full_uri, META)
self._save_data(data, data_path)
try:
_write(meta_path, json.dumps(str(meta)).encode("utf-8"))
except Exception as e:
os.remove(data_path)
raise e
manifest = os.path.join(full_uri, MANIFEST)
manifest_json = '{"data": {"description": "job definition","format": "bytes"},\
"meta":{"description": "job meta.json","format": "text"}}'
_write(manifest, manifest_json.encode("utf-8"))
return full_uri
def update_object(self, uri: str, data, component_name: str = DATA):
"""Update the object
Args:
uri: URI of the object
data: content data of the component
component_name: component name
Raises StorageException when the object does not exit.
"""
full_dir_path = os.path.join(self.root_dir, uri.lstrip(self.uri_root))
if not os.path.isdir(full_dir_path):
raise StorageException(f"path {full_dir_path} is not a valid directory.")
if not StorageSpec.is_valid_component(component_name):
raise StorageException(f"{component_name } is not a valid component for storage object.")
component_path = os.path.join(full_dir_path, component_name)
self._save_data(data, component_path)
manifest = os.path.join(full_dir_path, MANIFEST)
with open(manifest) as manifest_file:
manifest_json = json.loads(manifest_file.read())
manifest_json[component_name] = {"format": "bytes"}
_write(manifest, json.dumps(manifest_json).encode("utf-8"))
def update_meta(self, uri: str, meta: dict, replace: bool):
"""Updates the meta of the specified object.
Args:
uri: URI of the object
meta: value of new meta
replace: whether to replace the current meta completely or partial update
Raises:
TypeError: if invalid argument types
StorageException: if object does not exist
IOError: if error writing the object
"""
full_uri = os.path.join(self.root_dir, uri.lstrip(self.uri_root))
if not _object_exists(full_uri):
raise StorageException("object {} does not exist".format(uri))
if replace:
_write(os.path.join(full_uri, META), json.dumps(str(meta)).encode("utf-8"))
else:
prev_meta = self.get_meta(uri)
prev_meta.update(meta)
_write(os.path.join(full_uri, META), json.dumps(str(prev_meta)).encode("utf-8"))
def list_objects(self, path: str) -> List[str]:
"""List all objects in the specified path.
Args:
path: the path uri to the objects
Returns:
list of URIs of objects
Raises:
TypeError: if invalid argument types
StorageException: if path does not exist or is not a valid directory.
"""
full_dir_path = os.path.join(self.root_dir, path.lstrip(self.uri_root))
if not os.path.isdir(full_dir_path):
raise StorageException(f"path {full_dir_path} is not a valid directory.")
return [
os.path.join(path, f) for f in os.listdir(full_dir_path) if _object_exists(os.path.join(full_dir_path, f))
]
def get_meta(self, uri: str) -> dict:
"""Gets meta of the specified object.
Args:
uri: URI of the object
Returns:
meta of the object.
Raises:
TypeError: if invalid argument types
StorageException: if object does not exist
"""
full_uri = os.path.join(self.root_dir, uri.lstrip(self.uri_root))
if not _object_exists(full_uri):
raise StorageException("object {} does not exist".format(uri))
return ast.literal_eval(json.loads(_read(os.path.join(full_uri, META)).decode("utf-8")))
def get_data(self, uri: str, component_name: str = DATA) -> bytes:
"""Gets data of the specified object.
Args:
uri: URI of the object
component_name: storage component name
Returns:
data of the object.
Raises:
TypeError: if invalid argument types
StorageException: if object does not exist
"""
full_uri = os.path.join(self.root_dir, uri.lstrip(self.uri_root))
if not StorageSpec.is_valid_component(component_name):
raise StorageException(f"{component_name } is not a valid component for storage object.")
if not _object_exists(full_uri):
raise StorageException("object {} does not exist".format(uri))
return _read(os.path.join(full_uri, component_name))
def get_data_for_download(self, uri: str, component_name: str = DATA, download_file: str = None):
full_uri = os.path.join(self.root_dir, uri.lstrip(self.uri_root))
if not StorageSpec.is_valid_component(component_name):
raise StorageException(f"{component_name } is not a valid component for storage object.")
if not _object_exists(full_uri):
raise StorageException("object {} does not exist".format(uri))
if os.path.exists(download_file):
os.remove(download_file)
src = os.path.join(full_uri, component_name)
if os.path.exists(src):
os.symlink(src, download_file)
else:
log.info(f"{src} does not exist, skipping the creation of the symlink {download_file} for download.")
def get_detail(self, uri: str) -> Tuple[dict, bytes]:
"""Gets both data and meta of the specified object.
Args:
uri: URI of the object
Returns:
meta and data of the object.
Raises:
TypeError: if invalid argument types
StorageException: if object does not exist
"""
full_uri = os.path.join(self.root_dir, uri.lstrip(self.uri_root))
if not _object_exists(full_uri):
raise StorageException("object {} does not exist".format(uri))
return self.get_meta(uri), self.get_data(uri)
def delete_object(self, uri: str):
"""Deletes the specified object.
Args:
uri: URI of the object
Raises:
TypeError: if invalid argument types
StorageException: if object does not exist
"""
full_uri = os.path.join(self.root_dir, uri.lstrip(self.uri_root))
if not _object_exists(full_uri):
raise StorageException("object {} does not exist".format(uri))
shutil.rmtree(full_uri)
return full_uri
| NVFlare-main | nvflare/app_common/storages/filesystem_storage.py |
# Copyright (c) 2023, 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.
| NVFlare-main | nvflare/app_common/metrics_exchange/__init__.py |
# Copyright (c) 2023, 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 Any
from nvflare.apis.analytix import AnalyticsDataType
from nvflare.fuel.utils.pipe.pipe import Message
from nvflare.fuel.utils.pipe.pipe_handler import PipeHandler
class MetricData:
def __init__(self, key, value, data_type: AnalyticsDataType, additional_args=None):
self.key = key
self.value = value
self.data_type = data_type
self.additional_args = {} if additional_args is None else additional_args
class MetricsExchanger:
def __init__(
self,
pipe_handler: PipeHandler,
topic: str = "metrics",
):
self._pipe_handler = pipe_handler
self._topic = topic
def log(self, key: str, value: Any, data_type: AnalyticsDataType, **kwargs):
data = MetricData(key=key, value=value, data_type=data_type, additional_args=kwargs)
req = Message.new_request(topic=self._topic, data=data)
self._pipe_handler.send_to_peer(req)
| NVFlare-main | nvflare/app_common/metrics_exchange/metrics_exchanger.py |
# Copyright (c) 2023, 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 time
from queue import Queue
from threading import Event, Thread
from typing import Optional
from nvflare.apis.event_type import EventType
from nvflare.apis.fl_component import FLComponent
from nvflare.apis.fl_context import FLContext
from nvflare.app_common.metrics_exchange.metrics_exchanger import MetricData, MetricsExchanger
from nvflare.app_common.tracking.tracker_types import LogWriterName
from nvflare.app_common.widgets.streaming import ANALYTIC_EVENT_TYPE, AnalyticsSender
from nvflare.fuel.utils.constants import Mode
from nvflare.fuel.utils.pipe.memory_pipe import MemoryPipe
from nvflare.fuel.utils.pipe.pipe import Message
from nvflare.fuel.utils.pipe.pipe_handler import PipeHandler, Topic
class MetricsRetriever(FLComponent):
def __init__(
self,
metrics_exchanger_id: str,
event_type=ANALYTIC_EVENT_TYPE,
writer_name=LogWriterName.TORCH_TB,
topic: str = "metrics",
get_poll_interval: float = 0.5,
read_interval: float = 0.1,
heartbeat_interval: float = 5.0,
heartbeat_timeout: float = 30.0,
):
"""Metrics retriever.
Args:
event_type (str): event type to fire (defaults to "analytix_log_stats").
writer_name: the log writer for syntax information (defaults to LogWriterName.TORCH_TB)
"""
super().__init__()
self.metrics_exchanger_id = metrics_exchanger_id
self.analytic_sender = AnalyticsSender(event_type=event_type, writer_name=writer_name)
self.x_queue = Queue()
self.y_queue = Queue()
self.read_interval = read_interval
self.heartbeat_interval = heartbeat_interval
self.heartbeat_timeout = heartbeat_timeout
self.pipe_handler = self._create_pipe_handler(mode=Mode.PASSIVE)
self._topic = topic
self._get_poll_interval = get_poll_interval
self.stop = Event()
self._receive_thread = Thread(target=self.receive_data)
self.fl_ctx = None
def _create_pipe_handler(self, *, mode):
memory_pipe = MemoryPipe(x_queue=self.x_queue, y_queue=self.y_queue, mode=mode)
pipe_handler = PipeHandler(
memory_pipe,
read_interval=self.read_interval,
heartbeat_interval=self.heartbeat_interval,
heartbeat_timeout=self.heartbeat_timeout,
)
pipe_handler.start()
return pipe_handler
def handle_event(self, event_type: str, fl_ctx: FLContext):
if event_type == EventType.ABOUT_TO_START_RUN:
engine = fl_ctx.get_engine()
self.analytic_sender.handle_event(event_type, fl_ctx)
# inserts MetricsExchanger into engine components
pipe_handler = self._create_pipe_handler(mode=Mode.ACTIVE)
metrics_exchanger = MetricsExchanger(pipe_handler=pipe_handler)
all_components = engine.get_all_components()
all_components[self.metrics_exchanger_id] = metrics_exchanger
self.fl_ctx = fl_ctx
self._receive_thread.start()
elif event_type == EventType.ABOUT_TO_END_RUN:
self.stop.set()
self._receive_thread.join()
def receive_data(self):
"""Receives data and sends with AnalyticsSender."""
while True:
if self.stop.is_set():
break
msg: Optional[Message] = self.pipe_handler.get_next()
if msg is not None:
if msg.topic == [Topic.END, Topic.PEER_GONE, Topic.ABORT]:
self.task_panic("abort task", self.fl_ctx)
elif msg.topic != self._topic:
self.task_panic(f"ignored '{msg.topic}' when waiting for '{self._topic}'", self.fl_ctx)
else:
data: MetricData = msg.data
# TODO: unpack the format and pass it into "add"
self.analytic_sender.add(
tag=data.key, value=data.value, data_type=data.data_type, **data.additional_args
)
time.sleep(self._get_poll_interval)
| NVFlare-main | nvflare/app_common/metrics_exchange/metrics_retriever.py |
# Copyright (c) 2022, 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 re
import threading
from typing import Optional
class WeightedAggregationHelper(object):
def __init__(self, exclude_vars: Optional[str] = None, weigh_by_local_iter: bool = True):
"""Perform weighted aggregation.
Args:
exclude_vars (str, optional): regex string to match excluded vars during aggregation. Defaults to None.
weigh_by_local_iter (bool, optional): Whether to weight the contributions by the number of iterations
performed in local training in the current round. Defaults to `True`.
Setting it to `False` can be useful in applications such as homomorphic encryption to reduce
the number of computations on encrypted ciphertext.
The aggregated sum will still be divided by the provided weights and `aggregation_weights` for the
resulting weighted sum to be valid.
"""
super().__init__()
self.lock = threading.Lock()
self.exclude_vars = re.compile(exclude_vars) if exclude_vars else None
self.weigh_by_local_iter = weigh_by_local_iter
self.reset_stats()
self.total = dict()
self.counts = dict()
self.history = list()
def reset_stats(self):
self.total = dict()
self.counts = dict()
self.history = list()
def add(self, data, weight, contributor_name, contribution_round):
"""Compute weighted sum and sum of weights."""
with self.lock:
for k, v in data.items():
if self.exclude_vars is not None and self.exclude_vars.search(k):
continue
if self.weigh_by_local_iter:
weighted_value = v * weight
else:
weighted_value = v # used in homomorphic encryption to reduce computations on ciphertext
current_total = self.total.get(k, None)
if current_total is None:
self.total[k] = weighted_value
self.counts[k] = weight
else:
self.total[k] = current_total + weighted_value
self.counts[k] = self.counts[k] + weight
self.history.append(
{
"contributor_name": contributor_name,
"round": contribution_round,
"weight": weight,
}
)
def get_result(self):
"""Divide weighted sum by sum of weights."""
with self.lock:
aggregated_dict = {k: v * (1.0 / self.counts[k]) for k, v in self.total.items()}
self.reset_stats()
return aggregated_dict
def get_history(self):
return self.history
def get_len(self):
return len(self.get_history())
| NVFlare-main | nvflare/app_common/aggregators/weighted_aggregation_helper.py |
# Copyright (c) 2022, 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 logging
from typing import Any, Dict, Optional
from nvflare.apis.dxo import DXO, DataKind, MetaKey
from nvflare.apis.fl_component import FLComponent
from nvflare.apis.fl_context import FLContext
from nvflare.app_common.aggregators.weighted_aggregation_helper import WeightedAggregationHelper
from nvflare.app_common.app_constant import AppConstants
class DXOAggregator(FLComponent):
def __init__(
self,
exclude_vars: Optional[str] = None,
aggregation_weights: Optional[Dict[str, Any]] = None,
expected_data_kind: DataKind = DataKind.WEIGHT_DIFF,
name_postfix: str = "",
weigh_by_local_iter: bool = True,
):
"""Perform accumulated weighted aggregation for one kind of corresponding DXO from contributors.
Args:
exclude_vars (str, optional): Regex to match excluded vars during aggregation. Defaults to None.
aggregation_weights (Dict[str, Any], optional): Aggregation weight for each contributor.
Defaults to None.
expected_data_kind (DataKind): Expected DataKind for this DXO.
name_postfix: optional postfix to give to class name and show in logger output.
weigh_by_local_iter (bool, optional): Whether to weight the contributions by the number of iterations
performed in local training in the current round. Defaults to `True`.
Setting it to `False` can be useful in applications such as homomorphic encryption to reduce
the number of computations on encrypted ciphertext.
The aggregated sum will still be divided by the provided weights and `aggregation_weights` for the
resulting weighted sum to be valid.
"""
super().__init__()
self.expected_data_kind = expected_data_kind
self.aggregation_weights = aggregation_weights or {}
self.logger.debug(f"aggregation weights control: {aggregation_weights}")
self.aggregation_helper = WeightedAggregationHelper(
exclude_vars=exclude_vars, weigh_by_local_iter=weigh_by_local_iter
)
self.warning_count = {}
self.warning_limit = 10
self.processed_algorithm = None
if name_postfix:
self._name += name_postfix
self.logger = logging.getLogger(self._name)
def reset_aggregation_helper(self):
if self.aggregation_helper:
self.aggregation_helper.reset_stats()
def accept(self, dxo: DXO, contributor_name, contribution_round, fl_ctx: FLContext) -> bool:
"""Store DXO and update aggregator's internal state
Args:
dxo: information from contributor
contributor_name: name of the contributor
contribution_round: round of the contribution
fl_ctx: context provided by workflow
Returns:
The boolean to indicate if DXO is accepted.
"""
if not isinstance(dxo, DXO):
self.log_error(fl_ctx, f"Expected DXO but got {type(dxo)}")
return False
if dxo.data_kind not in (DataKind.WEIGHT_DIFF, DataKind.WEIGHTS, DataKind.METRICS):
self.log_error(fl_ctx, "cannot handle data kind {}".format(dxo.data_kind))
return False
if dxo.data_kind != self.expected_data_kind:
self.log_error(fl_ctx, "expected {} but got {}".format(self.expected_data_kind, dxo.data_kind))
return False
processed_algorithm = dxo.get_meta_prop(MetaKey.PROCESSED_ALGORITHM)
if processed_algorithm is not None:
if self.processed_algorithm is None:
self.processed_algorithm = processed_algorithm
elif self.processed_algorithm != processed_algorithm:
self.log_error(
fl_ctx,
f"Only supports aggregation of data processed with the same algorithm ({self.processed_algorithm}) "
f"but got algorithm: {processed_algorithm}",
)
return False
current_round = fl_ctx.get_prop(AppConstants.CURRENT_ROUND)
if contribution_round != current_round:
self.log_warning(
fl_ctx,
f"discarding DXO from {contributor_name} at round: "
f"{contribution_round}. Current round is: {current_round}",
)
return False
self.log_debug(fl_ctx, f"current_round: {current_round}")
data = dxo.data
if data is None:
self.log_error(fl_ctx, "no data to aggregate")
return False
for item in self.aggregation_helper.get_history():
if contributor_name == item["contributor_name"]:
prev_round = item["round"]
self.log_warning(
fl_ctx,
f"discarding DXO from {contributor_name} at round: "
f"{contribution_round} as {prev_round} accepted already",
)
return False
n_iter = dxo.get_meta_prop(MetaKey.NUM_STEPS_CURRENT_ROUND)
if n_iter is None:
if self.warning_count.get(contributor_name, 0) <= self.warning_limit:
self.log_warning(
fl_ctx,
f"NUM_STEPS_CURRENT_ROUND missing in meta of DXO"
f" from {contributor_name} and set to default value, 1.0. "
f" This kind of message will show {self.warning_limit} times at most.",
)
if contributor_name in self.warning_count:
self.warning_count[contributor_name] = self.warning_count[contributor_name] + 1
else:
self.warning_count[contributor_name] = 0
n_iter = 1.0
float_n_iter = float(n_iter)
aggregation_weight = self.aggregation_weights.get(contributor_name)
if aggregation_weight is None:
if self.warning_count.get(contributor_name, 0) <= self.warning_limit:
self.log_warning(
fl_ctx,
f"Aggregation_weight missing for {contributor_name} and set to default value, 1.0"
f" This kind of message will show {self.warning_limit} times at most.",
)
if contributor_name in self.warning_count:
self.warning_count[contributor_name] = self.warning_count[contributor_name] + 1
else:
self.warning_count[contributor_name] = 0
aggregation_weight = 1.0
# aggregate
self.aggregation_helper.add(data, aggregation_weight * float_n_iter, contributor_name, contribution_round)
self.log_debug(fl_ctx, "End accept")
return True
def aggregate(self, fl_ctx: FLContext) -> DXO:
"""Called when workflow determines to generate DXO to send back to contributors
Args:
fl_ctx (FLContext): context provided by workflow
Returns:
DXO: the weighted mean of accepted DXOs from contributors
"""
self.log_debug(fl_ctx, f"Start aggregation with weights {self.aggregation_weights}")
current_round = fl_ctx.get_prop(AppConstants.CURRENT_ROUND)
self.log_info(fl_ctx, f"aggregating {self.aggregation_helper.get_len()} update(s) at round {current_round}")
self.log_debug(fl_ctx, f"complete history {self.aggregation_helper.get_len()}")
aggregated_dict = self.aggregation_helper.get_result()
self.log_debug(fl_ctx, "End aggregation")
dxo = DXO(data_kind=self.expected_data_kind, data=aggregated_dict)
if self.processed_algorithm is not None:
dxo.set_meta_prop(MetaKey.PROCESSED_ALGORITHM, self.processed_algorithm)
self.processed_algorithm = None
return dxo
| NVFlare-main | nvflare/app_common/aggregators/dxo_aggregator.py |
# Copyright (c) 2021, 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 .accumulate_model_aggregator import AccumulateWeightedAggregator
from .intime_accumulate_model_aggregator import InTimeAccumulateWeightedAggregator
__all__ = ["AccumulateWeightedAggregator", "InTimeAccumulateWeightedAggregator"]
| NVFlare-main | nvflare/app_common/aggregators/__init__.py |
# Copyright (c) 2023, 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 abc import ABC, abstractmethod
from typing import Dict
from nvflare.apis.dxo import DXO
from nvflare.apis.fl_component import FLComponent
from nvflare.apis.fl_context import FLContext
class Assembler(FLComponent, ABC):
"""Assembler class for aggregation functionality
This defines the functionality of assembling the collected submissions
for CollectAndAssembleAggragator
"""
def __init__(self, data_kind: str):
super().__init__()
self.expected_data_kind = data_kind
self.logger.debug(f"expected data kind: {self.expected_data_kind}")
self._collection: dict = {}
def initialize(self, fl_ctx: FLContext):
pass
@property
def collection(self):
return self._collection
def get_expected_data_kind(self):
return self.expected_data_kind
@abstractmethod
def get_model_params(self, dxo: DXO) -> dict:
"""Connects the assembler's _collection with CollectAndAssembleAggregator
Get the collected parameters from the main aggregator
Return:
A dict of parameters needed for further assembling
"""
raise NotImplementedError
@abstractmethod
def assemble(self, data: Dict[str, dict], fl_ctx: FLContext) -> DXO:
"""Assemble the collected submissions.
This will be specified according to the specific algorithm
E.g. global svm round on the collected local supporting vectors;
global k-means step on the local centroids and counts
Return:
A DXO containing all information ready to be returned to clients
"""
raise NotImplementedError
def reset(self) -> None:
# Reset parameters for next round,
# This will be performed at the end of each aggregation round,
# it can include, but not limited to, clearing the _collection
self._collection = {}
| NVFlare-main | nvflare/app_common/aggregators/assembler.py |
# Copyright (c) 2021, 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 Any, Dict, Union
from nvflare.apis.dxo import DXO, DataKind, from_shareable
from nvflare.apis.fl_constant import ReservedKey, ReturnCode
from nvflare.apis.fl_context import FLContext
from nvflare.apis.shareable import Shareable
from nvflare.app_common.abstract.aggregator import Aggregator
from nvflare.app_common.aggregators.dxo_aggregator import DXOAggregator
from nvflare.app_common.app_constant import AppConstants
def _is_nested_aggregation_weights(aggregation_weights):
if not aggregation_weights:
return False
if not isinstance(aggregation_weights, dict):
return False
first_value = next(iter(aggregation_weights.items()))[1]
if not isinstance(first_value, dict):
return False
return True
def _get_missing_keys(ref_dict: dict, dict_to_check: dict):
result = []
for k in ref_dict:
if k not in dict_to_check:
result.append(k)
return result
class InTimeAccumulateWeightedAggregator(Aggregator):
def __init__(
self,
exclude_vars: Union[str, Dict[str, str], None] = None,
aggregation_weights: Union[Dict[str, Any], Dict[str, Dict[str, Any]], None] = None,
expected_data_kind: Union[DataKind, Dict[str, DataKind]] = DataKind.WEIGHT_DIFF,
weigh_by_local_iter: bool = True,
):
"""Perform accumulated weighted aggregation.
This is often used as the default aggregation method and can be used for FedAvg. It parses the shareable and
aggregates the contained DXO(s).
Args:
exclude_vars (Union[str, Dict[str, str]], optional):
Regular expression string to match excluded vars during aggregation. Defaults to None.
Can be one string or a dict of {dxo_name: regex strings} corresponding to each aggregated DXO
when processing a DXO of `DataKind.COLLECTION`.
aggregation_weights (Union[Dict[str, Any], Dict[str, Dict[str, Any]]], optional):
Aggregation weight for each contributor. Defaults to None.
Can be one dict of {contrib_name: aggr_weight} or a dict of dicts corresponding to each aggregated DXO
when processing a DXO of `DataKind.COLLECTION`.
expected_data_kind (Union[DataKind, Dict[str, DataKind]]):
DataKind for DXO. Defaults to DataKind.WEIGHT_DIFF
Can be one DataKind or a dict of {dxo_name: DataKind} corresponding to each aggregated DXO
when processing a DXO of `DataKind.COLLECTION`. Only the keys in this dict will be processed.
weigh_by_local_iter (bool, optional): Whether to weight the contributions by the number of iterations
performed in local training in the current round. Defaults to `True`.
Setting it to `False` can be useful in applications such as homomorphic encryption to reduce
the number of computations on encrypted ciphertext.
The aggregated sum will still be divided by the provided weights and `aggregation_weights` for the
resulting weighted sum to be valid.
"""
super().__init__()
self.logger.debug(f"exclude vars: {exclude_vars}")
self.logger.debug(f"aggregation weights control: {aggregation_weights}")
self.logger.debug(f"expected data kind: {expected_data_kind}")
self._single_dxo_key = ""
self._weigh_by_local_iter = weigh_by_local_iter
# Check expected data kind
if isinstance(expected_data_kind, dict):
for k, v in expected_data_kind.items():
if v not in [DataKind.WEIGHT_DIFF, DataKind.WEIGHTS, DataKind.METRICS]:
raise ValueError(
f"expected_data_kind[{k}] = {v} is not {DataKind.WEIGHT_DIFF} or {DataKind.WEIGHTS} or {DataKind.METRICS}"
)
self.expected_data_kind = expected_data_kind
else:
if expected_data_kind not in [DataKind.WEIGHT_DIFF, DataKind.WEIGHTS, DataKind.METRICS]:
raise ValueError(
f"expected_data_kind = {expected_data_kind} is not {DataKind.WEIGHT_DIFF} or {DataKind.WEIGHTS} or {DataKind.METRICS}"
)
self.expected_data_kind = {self._single_dxo_key: expected_data_kind}
# Check exclude_vars
if exclude_vars:
if not isinstance(exclude_vars, dict) and not isinstance(exclude_vars, str):
raise ValueError(
f"exclude_vars = {exclude_vars} should be a regex string but got {type(exclude_vars)}."
)
if isinstance(exclude_vars, dict):
missing_keys = _get_missing_keys(expected_data_kind, exclude_vars)
if len(missing_keys) != 0:
raise ValueError(
"A dict exclude_vars should specify exclude_vars for every key in expected_data_kind. "
f"But missed these keys: {missing_keys}"
)
exclude_vars_dict = dict()
for k in self.expected_data_kind.keys():
if isinstance(exclude_vars, dict):
if k in exclude_vars:
if not isinstance(exclude_vars[k], str):
raise ValueError(
f"exclude_vars[{k}] = {exclude_vars[k]} should be a regex string but got {type(exclude_vars[k])}."
)
exclude_vars_dict[k] = exclude_vars[k]
else:
# assume same exclude vars for each entry of DXO collection.
exclude_vars_dict[k] = exclude_vars
if self._single_dxo_key in self.expected_data_kind:
exclude_vars_dict[self._single_dxo_key] = exclude_vars
self.exclude_vars = exclude_vars_dict
# Check aggregation weights
if _is_nested_aggregation_weights(aggregation_weights):
missing_keys = _get_missing_keys(expected_data_kind, aggregation_weights)
if len(missing_keys) != 0:
raise ValueError(
"A dict of dict aggregation_weights should specify aggregation_weights "
f"for every key in expected_data_kind. But missed these keys: {missing_keys}"
)
aggregation_weights = aggregation_weights or {}
aggregation_weights_dict = dict()
for k in self.expected_data_kind.keys():
if k in aggregation_weights:
aggregation_weights_dict[k] = aggregation_weights[k]
else:
# assume same aggregation weights for each entry of DXO collection.
aggregation_weights_dict[k] = aggregation_weights
self.aggregation_weights = aggregation_weights_dict
# Set up DXO aggregators
self.dxo_aggregators = dict()
for k in self.expected_data_kind.keys():
self.dxo_aggregators.update(
{
k: DXOAggregator(
exclude_vars=self.exclude_vars[k],
aggregation_weights=self.aggregation_weights[k],
expected_data_kind=self.expected_data_kind[k],
name_postfix=k,
weigh_by_local_iter=self._weigh_by_local_iter,
)
}
)
def accept(self, shareable: Shareable, fl_ctx: FLContext) -> bool:
"""Store shareable and update aggregator's internal state
Args:
shareable: information from contributor
fl_ctx: context provided by workflow
Returns:
The first boolean indicates if this shareable is accepted.
The second boolean indicates if aggregate can be called.
"""
try:
dxo = from_shareable(shareable)
except Exception:
self.log_exception(fl_ctx, "shareable data is not a valid DXO")
return False
if dxo.data_kind not in (DataKind.WEIGHT_DIFF, DataKind.WEIGHTS, DataKind.METRICS, DataKind.COLLECTION):
self.log_error(
fl_ctx,
f"cannot handle data kind {dxo.data_kind}, "
f"expecting DataKind.WEIGHT_DIFF, DataKind.WEIGHTS, or DataKind.COLLECTION.",
)
return False
contributor_name = shareable.get_peer_prop(key=ReservedKey.IDENTITY_NAME, default="?")
contribution_round = shareable.get_cookie(AppConstants.CONTRIBUTION_ROUND)
rc = shareable.get_return_code()
if rc and rc != ReturnCode.OK:
self.log_warning(fl_ctx, f"Contributor {contributor_name} returned rc: {rc}. Disregarding contribution.")
return False
# Accept expected DXO(s) in shareable
n_accepted = 0
for key in self.expected_data_kind.keys():
if key == self._single_dxo_key: # expecting a single DXO
sub_dxo = dxo
else: # expecting a collection of DXOs
sub_dxo = dxo.data.get(key)
if not isinstance(sub_dxo, DXO):
self.log_warning(fl_ctx, f"Collection does not contain DXO for key {key} but {type(sub_dxo)}.")
continue
accepted = self.dxo_aggregators[key].accept(
dxo=sub_dxo, contributor_name=contributor_name, contribution_round=contribution_round, fl_ctx=fl_ctx
)
if not accepted:
return False
else:
n_accepted += 1
if n_accepted > 0:
return True
else:
self.log_warning(fl_ctx, f"Did not accept any DXOs from {contributor_name} in round {contribution_round}!")
return False
def aggregate(self, fl_ctx: FLContext) -> Shareable:
"""Called when workflow determines to generate shareable to send back to contributors
Args:
fl_ctx (FLContext): context provided by workflow
Returns:
Shareable: the weighted mean of accepted shareables from contributors
"""
self.log_debug(fl_ctx, "Start aggregation")
result_dxo_dict = dict()
# Aggregate the expected DXO(s)
for key in self.expected_data_kind.keys():
aggregated_dxo = self.dxo_aggregators[key].aggregate(fl_ctx)
if key == self._single_dxo_key: # return single DXO with aggregation results
return aggregated_dxo.to_shareable()
self.log_info(fl_ctx, f"Aggregated contributions matching key '{key}'.")
result_dxo_dict.update({key: aggregated_dxo})
# return collection of DXOs with aggregation results
collection_dxo = DXO(data_kind=DataKind.COLLECTION, data=result_dxo_dict)
return collection_dxo.to_shareable()
| NVFlare-main | nvflare/app_common/aggregators/intime_accumulate_model_aggregator.py |
# Copyright (c) 2023, 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 nvflare.apis.dxo import DXO, DataKind, from_shareable
from nvflare.apis.fl_context import FLContext
from nvflare.apis.shareable import Shareable
from nvflare.app_common.abstract.aggregator import Aggregator
class DXOCollector(Aggregator):
def __init__(self):
Aggregator.__init__(self)
self.dxos = {}
def reset(self, fl_ctx: FLContext):
self.dxos = {}
def accept(self, shareable: Shareable, fl_ctx: FLContext):
try:
dxo = from_shareable(shareable)
except Exception:
self.log_exception(fl_ctx, "shareable data is not a valid DXO")
return False
peer_ctx = fl_ctx.get_peer_context()
client_name = peer_ctx.get_identity_name()
if not client_name:
self.log_error(fl_ctx, "no identity info in peer context!")
return False
self.dxos[client_name] = dxo
return True
def aggregate(self, fl_ctx: FLContext):
collection_dxo = DXO(data_kind=DataKind.COLLECTION, data=self.dxos)
return collection_dxo.to_shareable()
| NVFlare-main | nvflare/app_common/aggregators/dxo_collector.py |
# Copyright (c) 2021, 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 nvflare.fuel.utils.deprecated import deprecated
from .intime_accumulate_model_aggregator import InTimeAccumulateWeightedAggregator
@deprecated("Please use 'InTimeAccumulateWeightedAggregator'")
class AccumulateWeightedAggregator(InTimeAccumulateWeightedAggregator):
pass
| NVFlare-main | nvflare/app_common/aggregators/accumulate_model_aggregator.py |
# Copyright (c) 2023, 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 Optional
from nvflare.apis.dxo import DXO, from_shareable
from nvflare.apis.fl_constant import ReservedKey, ReturnCode
from nvflare.apis.fl_context import FLContext
from nvflare.apis.shareable import Shareable
from nvflare.app_common.abstract.aggregator import Aggregator
from nvflare.app_common.aggregators.assembler import Assembler
from nvflare.app_common.app_constant import AppConstants
class CollectAndAssembleAggregator(Aggregator):
"""Perform collection and flexible assemble aggregation
This is used for methods needing a special assemble mechanism on the client submissions.
It first collects all submissions from clients, then delegates the assembling functionality to assembler,
which is specific to a particular algorithm.
Note that the aggregation in this case is not in-time, since the assembling function may not be arithmetic mean.
"""
def __init__(self, assembler_id: str):
super().__init__()
self.assembler_id = assembler_id
self.assembler: Optional[Assembler] = None
def accept(self, shareable: Shareable, fl_ctx: FLContext) -> bool:
if not self.assembler:
self.assembler = fl_ctx.get_engine().get_component(self.assembler_id)
contributor_name = shareable.get_peer_prop(key=ReservedKey.IDENTITY_NAME, default="?")
dxo = self._get_contribution(shareable, fl_ctx)
if dxo is None or dxo.data is None:
self.log_error(fl_ctx, "no data to aggregate")
return False
current_round = fl_ctx.get_prop(AppConstants.CURRENT_ROUND)
return self._accept_contribution(contributor_name, current_round, dxo, fl_ctx)
def _accept_contribution(self, contributor: str, current_round: int, dxo: DXO, fl_ctx: FLContext) -> bool:
collection = self.assembler.collection
if contributor not in collection:
collection[contributor] = self.assembler.get_model_params(dxo)
accepted = True
else:
self.log_info(
fl_ctx,
f"Discarded: Current round: {current_round} " + f"contributions already include client: {contributor}",
)
accepted = False
return accepted
def _get_contribution(self, shareable: Shareable, fl_ctx: FLContext) -> Optional[DXO]:
contributor_name = shareable.get_peer_prop(key=ReservedKey.IDENTITY_NAME, default="?")
try:
dxo = from_shareable(shareable)
except Exception:
self.log_exception(fl_ctx, "shareable data is not a valid DXO")
return None
rc = shareable.get_return_code()
if rc and rc != ReturnCode.OK:
self.log_warning(
fl_ctx,
f"Contributor {contributor_name} returned rc: {rc}. Disregarding contribution.",
)
return None
expected_data_kind = self.assembler.get_expected_data_kind()
if dxo.data_kind != expected_data_kind:
self.log_error(
fl_ctx,
"expected {} but got {}".format(expected_data_kind, dxo.data_kind),
)
return None
contribution_round = shareable.get_cookie(AppConstants.CONTRIBUTION_ROUND)
current_round = fl_ctx.get_prop(AppConstants.CURRENT_ROUND)
if contribution_round != current_round:
self.log_warning(
fl_ctx,
f"discarding DXO from {contributor_name} at round: "
f"{contribution_round}. Current round is: {current_round}",
)
return None
return dxo
def aggregate(self, fl_ctx: FLContext) -> Shareable:
self.log_debug(fl_ctx, "Start aggregation")
current_round = fl_ctx.get_prop(AppConstants.CURRENT_ROUND)
collection = self.assembler.collection
site_num = len(collection)
self.log_info(fl_ctx, f"aggregating {site_num} update(s) at round {current_round}")
dxo = self.assembler.assemble(data=collection, fl_ctx=fl_ctx)
# Reset assembler for next round
self.assembler.reset()
self.log_debug(fl_ctx, "End aggregation")
return dxo.to_shareable()
| NVFlare-main | nvflare/app_common/aggregators/collect_and_assemble_aggregator.py |
# Copyright (c) 2022, 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.
| NVFlare-main | nvflare/app_common/decomposers/__init__.py |
# Copyright (c) 2022, 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.
"""Decomposers for types from app_common and Machine Learning libraries."""
import os
from abc import ABC
from io import BytesIO
from typing import Any
import numpy as np
from nvflare.app_common.abstract.fl_model import FLModel
from nvflare.app_common.abstract.learnable import Learnable
from nvflare.app_common.abstract.model import ModelLearnable
from nvflare.app_common.widgets.event_recorder import _CtxPropReq, _EventReq, _EventStats
from nvflare.fuel.utils import fobs
from nvflare.fuel.utils.fobs import Decomposer
from nvflare.fuel.utils.fobs.datum import DatumManager
from nvflare.fuel.utils.fobs.decomposer import DictDecomposer
class FLModelDecomposer(fobs.Decomposer):
def supported_type(self):
return FLModel
def decompose(self, b: FLModel, manager: DatumManager = None) -> Any:
return [
b.params_type,
b.params,
b.optimizer_params,
b.metrics,
b.current_round,
b.total_rounds,
b.meta,
]
def recompose(self, data: list, manager: DatumManager = None) -> FLModel:
return FLModel(
params_type=data[0],
params=data[1],
optimizer_params=data[2],
metrics=data[3],
current_round=data[4],
total_rounds=data[5],
meta=data[6],
)
class ModelLearnableDecomposer(fobs.Decomposer):
def supported_type(self):
return ModelLearnable
def decompose(self, target: ModelLearnable, manager: DatumManager = None) -> Any:
return target.copy()
def recompose(self, data: Any, manager: DatumManager = None) -> ModelLearnable:
obj = ModelLearnable()
for k, v in data.items():
obj[k] = v
return obj
class NumpyScalarDecomposer(fobs.Decomposer, ABC):
"""Decomposer base class for all numpy types with item method."""
def decompose(self, target: Any, manager: DatumManager = None) -> Any:
return target.item()
def recompose(self, data: Any, manager: DatumManager = None) -> np.ndarray:
return self.supported_type()(data)
class Float64ScalarDecomposer(NumpyScalarDecomposer):
def supported_type(self):
return np.float64
class Float32ScalarDecomposer(NumpyScalarDecomposer):
def supported_type(self):
return np.float32
class Int64ScalarDecomposer(NumpyScalarDecomposer):
def supported_type(self):
return np.int64
class Int32ScalarDecomposer(NumpyScalarDecomposer):
def supported_type(self):
return np.int32
class NumpyArrayDecomposer(Decomposer):
def supported_type(self):
return np.ndarray
def decompose(self, target: np.ndarray, manager: DatumManager = None) -> Any:
stream = BytesIO()
np.save(stream, target, allow_pickle=False)
return stream.getvalue()
def recompose(self, data: Any, manager: DatumManager = None) -> np.ndarray:
stream = BytesIO(data)
return np.load(stream, allow_pickle=False)
def register():
if register.registered:
return
fobs.register(DictDecomposer(Learnable))
fobs.register(DictDecomposer(ModelLearnable))
fobs.register(FLModelDecomposer)
fobs.register_data_classes(
_CtxPropReq,
_EventReq,
_EventStats,
)
fobs.register_folder(os.path.dirname(__file__), __package__)
register.registered = True
register.registered = False
| NVFlare-main | nvflare/app_common/decomposers/common_decomposers.py |
# Copyright (c) 2022, 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 Union
from nvflare.apis.client import Client
from nvflare.apis.fl_context import FLContext
from nvflare.apis.impl.controller import ClientTask, Controller, Task
from nvflare.apis.shareable import Shareable
from nvflare.apis.signal import Signal
from nvflare.app_common.abstract.response_processor import ResponseProcessor
class BroadcastAndProcess(Controller):
def __init__(
self,
processor: Union[str, ResponseProcessor],
task_name: str,
min_responses_required: int = 0,
wait_time_after_min_received: int = 10,
timeout: int = 0,
clients=None,
):
"""This controller broadcast a task to specified clients to collect responses, and uses the
ResponseProcessor object to process the client responses.
Args:
processor: the processor that implements logic for client responses and final check.
It must be a component id (str), or a ResponseProcessor object.
task_name: name of the task to be sent to client to collect responses
min_responses_required: min number responses required from clients. 0 means all.
wait_time_after_min_received: how long to wait after min responses are received from clients
timeout: timeout of the task. 0 means never time out
clients: list of clients to send the task to. None means all clients.
"""
Controller.__init__(self)
if not (isinstance(processor, str) or isinstance(processor, ResponseProcessor)):
raise TypeError(f"value of processor must be a str or ResponseProcessor but got {type(processor)}")
self.processor = processor
self.task_name = task_name
self.min_responses_required = min_responses_required
self.wait_time_after_min_received = wait_time_after_min_received
self.timeout = timeout
self.clients = clients
def start_controller(self, fl_ctx: FLContext) -> None:
self.log_info(fl_ctx, "Initializing BroadcastAndProcess.")
if isinstance(self.processor, str):
checker_id = self.processor
# the processor is a component id - get the processor component
engine = fl_ctx.get_engine()
if not engine:
self.system_panic("Engine not found. BroadcastAndProcess exiting.", fl_ctx)
return
self.processor = engine.get_component(checker_id)
if not isinstance(self.processor, ResponseProcessor):
self.system_panic(
f"component {checker_id} must be a ResponseProcessor type object but got {type(self.processor)}",
fl_ctx,
)
def control_flow(self, abort_signal: Signal, fl_ctx: FLContext) -> None:
task_data = self.processor.create_task_data(self.task_name, fl_ctx)
if not isinstance(task_data, Shareable):
self.system_panic(
f"ResponseProcessor {type(self.processor)} failed to return valid task data: "
f"expect Shareable but got {type(task_data)}",
fl_ctx,
)
return
task = Task(
name=self.task_name,
data=task_data,
timeout=self.timeout,
result_received_cb=self._process_client_response,
)
self.broadcast_and_wait(
task=task,
wait_time_after_min_received=self.wait_time_after_min_received,
fl_ctx=fl_ctx,
abort_signal=abort_signal,
targets=self.clients,
min_responses=self.min_responses_required,
)
success = self.processor.final_process(fl_ctx)
if not success:
self.system_panic(reason=f"ResponseProcessor {type(self.processor)} failed final check!", fl_ctx=fl_ctx)
def _process_client_response(self, client_task: ClientTask, fl_ctx: FLContext) -> None:
task = client_task.task
response = client_task.result
client = client_task.client
ok = self.processor.process_client_response(
client=client, task_name=task.name, response=response, fl_ctx=fl_ctx
)
# Cleanup task result
client_task.result = None
if not ok:
self.system_panic(
reason=f"ResponseProcessor {type(self.processor)} failed to check client {client.name}", fl_ctx=fl_ctx
)
def stop_controller(self, fl_ctx: FLContext):
pass
def process_result_of_unknown_task(
self, client: Client, task_name: str, client_task_id: str, result: Shareable, fl_ctx: FLContext
):
pass
| NVFlare-main | nvflare/app_common/workflows/broadcast_and_process.py |
# Copyright (c) 2022, 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 copy
import numpy as np
from nvflare.apis.dxo import DXO, DataKind, from_shareable
from nvflare.apis.fl_context import FLContext
from nvflare.apis.impl.controller import Task
from nvflare.apis.signal import Signal
from nvflare.app_common.abstract.model import model_learnable_to_dxo
from nvflare.app_common.app_constant import AlgorithmConstants, AppConstants
from nvflare.app_common.app_event_type import AppEventType
from nvflare.app_common.workflows.scatter_and_gather import ScatterAndGather
from nvflare.security.logging import secure_format_exception
class ScatterAndGatherScaffold(ScatterAndGather):
def __init__(
self,
min_clients: int = 1000,
num_rounds: int = 5,
start_round: int = 0,
wait_time_after_min_received: int = 10,
aggregator_id=AppConstants.DEFAULT_AGGREGATOR_ID,
persistor_id=AppConstants.DEFAULT_PERSISTOR_ID,
shareable_generator_id=AppConstants.DEFAULT_SHAREABLE_GENERATOR_ID,
train_task_name=AppConstants.TASK_TRAIN,
train_timeout: int = 0,
ignore_result_error: bool = False,
task_check_period: float = 0.5,
persist_every_n_rounds: int = 1,
snapshot_every_n_rounds: int = 1,
):
"""The controller for ScatterAndGatherScaffold workflow.
The model persistor (persistor_id) is used to load the initial global model which is sent to all clients.
Each client sends it's updated weights after local training which is aggregated (aggregator_id). The
shareable generator is used to convert the aggregated weights to shareable and shareable back to weight.
The model_persistor also saves the model after training.
Args:
min_clients (int, optional): The minimum number of clients responses before
SAG starts to wait for `wait_time_after_min_received`. Note that SAG will move forward when all
available clients have responded regardless of this value. Defaults to 1000.
num_rounds (int, optional): The total number of training rounds. Defaults to 5.
start_round (int, optional): Start round for training. Defaults to 0.
wait_time_after_min_received (int, optional): Time to wait before beginning aggregation after
minimum number of clients responses has been received. Defaults to 10.
aggregator_id (str, optional): ID of the aggregator component. Defaults to "aggregator".
persistor_id (str, optional): ID of the persistor component. Defaults to "persistor".
shareable_generator_id (str, optional): ID of the shareable generator. Defaults to "shareable_generator".
train_task_name (str, optional): Name of the train task. Defaults to "train".
train_timeout (int, optional): Time to wait for clients to do local training.
ignore_result_error (bool, optional): whether this controller can proceed if client result has errors.
Defaults to False.
task_check_period (float, optional): interval for checking status of tasks. Defaults to 0.5.
persist_every_n_rounds (int, optional): persist the global model every n rounds. Defaults to 1.
If n is 0 then no persist.
snapshot_every_n_rounds (int, optional): persist the server state every n rounds. Defaults to 1.
If n is 0 then no persist.
"""
super().__init__(
min_clients=min_clients,
num_rounds=num_rounds,
start_round=start_round,
wait_time_after_min_received=wait_time_after_min_received,
aggregator_id=aggregator_id,
persistor_id=persistor_id,
shareable_generator_id=shareable_generator_id,
train_task_name=train_task_name,
train_timeout=train_timeout,
ignore_result_error=ignore_result_error,
task_check_period=task_check_period,
persist_every_n_rounds=persist_every_n_rounds,
snapshot_every_n_rounds=snapshot_every_n_rounds,
)
# for SCAFFOLD
self.aggregator_ctrl = None
self._global_ctrl_weights = None
def start_controller(self, fl_ctx: FLContext) -> None:
super().start_controller(fl_ctx=fl_ctx)
self.log_info(fl_ctx, "Initializing ScatterAndGatherScaffold workflow.")
# for SCAFFOLD
if not self._global_weights:
self.system_panic("Global weights not available!", fl_ctx)
return
self._global_ctrl_weights = copy.deepcopy(self._global_weights["weights"])
# Initialize correction term with zeros
for k in self._global_ctrl_weights.keys():
self._global_ctrl_weights[k] = np.zeros_like(self._global_ctrl_weights[k])
# TODO: Print some stats of the correction magnitudes
def control_flow(self, abort_signal: Signal, fl_ctx: FLContext) -> None:
try:
self.log_info(fl_ctx, "Beginning ScatterAndGatherScaffold training phase.")
self._phase = AppConstants.PHASE_TRAIN
fl_ctx.set_prop(AppConstants.PHASE, self._phase, private=True, sticky=False)
fl_ctx.set_prop(AppConstants.NUM_ROUNDS, self._num_rounds, private=True, sticky=False)
self.fire_event(AppEventType.TRAINING_STARTED, fl_ctx)
if self._current_round is None:
self._current_round = self._start_round
while self._current_round < self._start_round + self._num_rounds:
if self._check_abort_signal(fl_ctx, abort_signal):
return
self.log_info(fl_ctx, f"Round {self._current_round} started.")
fl_ctx.set_prop(AppConstants.GLOBAL_MODEL, self._global_weights, private=True, sticky=True)
fl_ctx.set_prop(AppConstants.CURRENT_ROUND, self._current_round, private=True, sticky=True)
self.fire_event(AppEventType.ROUND_STARTED, fl_ctx)
# Create train_task
# get DXO with global model weights
dxo_global_weights = model_learnable_to_dxo(self._global_weights)
# add global SCAFFOLD controls using a DXO collection
dxo_global_ctrl = DXO(data_kind=DataKind.WEIGHT_DIFF, data=self._global_ctrl_weights)
dxo_dict = {
AppConstants.MODEL_WEIGHTS: dxo_global_weights,
AlgorithmConstants.SCAFFOLD_CTRL_GLOBAL: dxo_global_ctrl,
}
dxo_collection = DXO(data_kind=DataKind.COLLECTION, data=dxo_dict)
data_shareable = dxo_collection.to_shareable()
# add meta information
data_shareable.set_header(AppConstants.CURRENT_ROUND, self._current_round)
data_shareable.set_header(AppConstants.NUM_ROUNDS, self._num_rounds)
data_shareable.add_cookie(AppConstants.CONTRIBUTION_ROUND, self._current_round)
train_task = Task(
name=self.train_task_name,
data=data_shareable,
props={},
timeout=self._train_timeout,
before_task_sent_cb=self._prepare_train_task_data,
result_received_cb=self._process_train_result,
)
self.broadcast_and_wait(
task=train_task,
min_responses=self._min_clients,
wait_time_after_min_received=self._wait_time_after_min_received,
fl_ctx=fl_ctx,
abort_signal=abort_signal,
)
if self._check_abort_signal(fl_ctx, abort_signal):
return
self.fire_event(AppEventType.BEFORE_AGGREGATION, fl_ctx)
aggr_result = self.aggregator.aggregate(fl_ctx)
# extract aggregated weights and controls
collection_dxo = from_shareable(aggr_result)
dxo_aggr_result = collection_dxo.data.get(AppConstants.MODEL_WEIGHTS)
if not dxo_aggr_result:
self.log_error(fl_ctx, "Aggregated model weights are missing!")
return
dxo_ctrl_aggr_result = collection_dxo.data.get(AlgorithmConstants.SCAFFOLD_CTRL_DIFF)
if not dxo_ctrl_aggr_result:
self.log_error(fl_ctx, "Aggregated model weight controls are missing!")
return
fl_ctx.set_prop(AppConstants.AGGREGATION_RESULT, aggr_result, private=True, sticky=False)
self.fire_event(AppEventType.AFTER_AGGREGATION, fl_ctx)
if self._check_abort_signal(fl_ctx, abort_signal):
return
# update global model using shareable generator
self.fire_event(AppEventType.BEFORE_SHAREABLE_TO_LEARNABLE, fl_ctx)
self._global_weights = self.shareable_gen.shareable_to_learnable(dxo_aggr_result.to_shareable(), fl_ctx)
# update SCAFFOLD global controls
ctr_diff = dxo_ctrl_aggr_result.data
for v_name, v_value in ctr_diff.items():
self._global_ctrl_weights[v_name] += v_value
fl_ctx.set_prop(
AlgorithmConstants.SCAFFOLD_CTRL_GLOBAL, self._global_ctrl_weights, private=True, sticky=True
)
fl_ctx.set_prop(AppConstants.GLOBAL_MODEL, self._global_weights, private=True, sticky=True)
fl_ctx.sync_sticky()
self.fire_event(AppEventType.AFTER_SHAREABLE_TO_LEARNABLE, fl_ctx)
if self._check_abort_signal(fl_ctx, abort_signal):
return
if self._persist_every_n_rounds != 0 and (self._current_round + 1) % self._persist_every_n_rounds == 0:
self.log_info(fl_ctx, "Start persist model on server.")
self.fire_event(AppEventType.BEFORE_LEARNABLE_PERSIST, fl_ctx)
self.persistor.save(self._global_weights, fl_ctx)
self.fire_event(AppEventType.AFTER_LEARNABLE_PERSIST, fl_ctx)
self.log_info(fl_ctx, "End persist model on server.")
self.fire_event(AppEventType.ROUND_DONE, fl_ctx)
self.log_info(fl_ctx, f"Round {self._current_round} finished.")
self._current_round += 1
# need to persist snapshot after round increased because the global weights should be set to
# the last finished round's result
if self._snapshot_every_n_rounds != 0 and self._current_round % self._snapshot_every_n_rounds == 0:
self._engine.persist_components(fl_ctx, completed=False)
self._phase = AppConstants.PHASE_FINISHED
self.log_info(fl_ctx, "Finished ScatterAndGatherScaffold Training.")
except Exception as e:
error_msg = f"Exception in ScatterAndGatherScaffold control_flow: {secure_format_exception(e)}"
self.log_exception(fl_ctx, error_msg)
self.system_panic(error_msg, fl_ctx)
| NVFlare-main | nvflare/app_common/workflows/scatter_and_gather_scaffold.py |
# Copyright (c) 2021, 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 gc
import random
from nvflare.apis.client import Client
from nvflare.apis.fl_context import FLContext
from nvflare.apis.impl.controller import ClientTask, Controller, Task
from nvflare.apis.shareable import Shareable
from nvflare.apis.signal import Signal
from nvflare.app_common.abstract.learnable_persistor import LearnablePersistor
from nvflare.app_common.abstract.shareable_generator import ShareableGenerator
from nvflare.app_common.app_constant import AppConstants
from nvflare.app_common.app_event_type import AppEventType
from nvflare.security.logging import secure_format_exception
class RelayOrder:
FIXED = "FIXED"
RANDOM = "RANDOM"
RANDOM_WITHOUT_SAME_IN_A_ROW = "RANDOM_WITHOUT_SAME_IN_A_ROW"
SUPPORTED_ORDERS = (RelayOrder.FIXED, RelayOrder.RANDOM, RelayOrder.RANDOM_WITHOUT_SAME_IN_A_ROW)
class CyclicController(Controller):
def __init__(
self,
num_rounds: int = 5,
task_assignment_timeout: int = 10,
persistor_id="persistor",
shareable_generator_id="shareable_generator",
task_name="train",
task_check_period: float = 0.5,
persist_every_n_rounds: int = 1,
snapshot_every_n_rounds: int = 1,
order: str = RelayOrder.FIXED,
):
"""A sample implementation to demonstrate how to use relay method for Cyclic Federated Learning.
Args:
num_rounds (int, optional): number of rounds this controller should perform. Defaults to 5.
task_assignment_timeout (int, optional): timeout (in sec) to determine if one client fails to
request the task which it is assigned to . Defaults to 10.
persistor_id (str, optional): id of the persistor so this controller can save a global model.
Defaults to "persistor".
shareable_generator_id (str, optional): id of shareable generator. Defaults to "shareable_generator".
task_name (str, optional): the task name that clients know how to handle. Defaults to "train".
task_check_period (float, optional): interval for checking status of tasks. Defaults to 0.5.
persist_every_n_rounds (int, optional): persist the global model every n rounds. Defaults to 1.
If n is 0 then no persist.
snapshot_every_n_rounds (int, optional): persist the server state every n rounds. Defaults to 1.
If n is 0 then no persist.
order (str, optional): the order of relay.
If FIXED means the same order for every round.
If RANDOM means random order for every round.
If RANDOM_WITHOUT_SAME_IN_A_ROW means every round the order gets shuffled but a client will never be
run twice in a row (in different round).
Raises:
TypeError: when any of input arguments does not have correct type
"""
super().__init__(task_check_period=task_check_period)
if not isinstance(num_rounds, int):
raise TypeError("num_rounds must be int but got {}".format(type(num_rounds)))
if not isinstance(task_assignment_timeout, int):
raise TypeError("task_assignment_timeout must be int but got {}".format(type(task_assignment_timeout)))
if not isinstance(persistor_id, str):
raise TypeError("persistor_id must be a string but got {}".format(type(persistor_id)))
if not isinstance(shareable_generator_id, str):
raise TypeError("shareable_generator_id must be a string but got {}".format(type(shareable_generator_id)))
if not isinstance(task_name, str):
raise TypeError("task_name must be a string but got {}".format(type(task_name)))
if order not in SUPPORTED_ORDERS:
raise ValueError(f"order must be in {SUPPORTED_ORDERS}")
self._num_rounds = num_rounds
self._start_round = 0
self._end_round = self._start_round + self._num_rounds
self._current_round = 0
self._last_learnable = None
self.persistor_id = persistor_id
self.shareable_generator_id = shareable_generator_id
self.task_assignment_timeout = task_assignment_timeout
self.task_name = task_name
self.persistor = None
self.shareable_generator = None
self._persist_every_n_rounds = persist_every_n_rounds
self._snapshot_every_n_rounds = snapshot_every_n_rounds
self._participating_clients = None
self._last_client = None
self._order = order
def start_controller(self, fl_ctx: FLContext):
self.log_debug(fl_ctx, "starting controller")
self.persistor = self._engine.get_component(self.persistor_id)
self.shareable_generator = self._engine.get_component(self.shareable_generator_id)
if not isinstance(self.persistor, LearnablePersistor):
self.system_panic(
f"Persistor {self.persistor_id} must be a Persistor instance, but got {type(self.persistor)}", fl_ctx
)
if not isinstance(self.shareable_generator, ShareableGenerator):
self.system_panic(
f"Shareable generator {self.shareable_generator_id} must be a Shareable Generator instance,"
f"but got {type(self.shareable_generator)}",
fl_ctx,
)
self._last_learnable = self.persistor.load(fl_ctx)
fl_ctx.set_prop(AppConstants.GLOBAL_MODEL, self._last_learnable, private=True, sticky=True)
fl_ctx.set_prop(AppConstants.NUM_ROUNDS, self._num_rounds, private=True, sticky=True)
self.fire_event(AppEventType.INITIAL_MODEL_LOADED, fl_ctx)
self._participating_clients = self._engine.get_clients()
if len(self._participating_clients) <= 1:
self.system_panic("Not enough client sites.", fl_ctx)
self._last_client = None
def _get_relay_orders(self):
targets = list(self._participating_clients)
if self._order == RelayOrder.RANDOM:
random.shuffle(targets)
elif self._order == RelayOrder.RANDOM_WITHOUT_SAME_IN_A_ROW:
random.shuffle(targets)
if self._last_client == targets[0]:
targets = targets.append(targets.pop(0))
self._last_client = targets[-1]
return targets
def _process_result(self, client_task: ClientTask, fl_ctx: FLContext):
# submitted shareable is stored in client_task.result
# we need to update task.data with that shareable so the next target
# will get the updated shareable
task = client_task.task
# update the global learnable with the received result (shareable)
# e.g. the received result could be weight_diffs, the learnable could be full weights.
self._last_learnable = self.shareable_generator.shareable_to_learnable(client_task.result, fl_ctx)
# prepare task shareable data for next client
task.data = self.shareable_generator.learnable_to_shareable(self._last_learnable, fl_ctx)
task.data.set_header(AppConstants.CURRENT_ROUND, self._current_round)
task.data.add_cookie(AppConstants.CONTRIBUTION_ROUND, self._current_round)
def control_flow(self, abort_signal: Signal, fl_ctx: FLContext):
try:
self.log_debug(fl_ctx, "Cyclic starting.")
for self._current_round in range(self._start_round, self._end_round):
if abort_signal.triggered:
return
self.log_debug(fl_ctx, "Starting current round={}.".format(self._current_round))
fl_ctx.set_prop(AppConstants.CURRENT_ROUND, self._current_round, private=True, sticky=True)
# Task for one cyclic
targets = self._get_relay_orders()
targets_names = [t.name for t in targets]
self.log_debug(fl_ctx, f"Relay on {targets_names}")
shareable = self.shareable_generator.learnable_to_shareable(self._last_learnable, fl_ctx)
shareable.set_header(AppConstants.CURRENT_ROUND, self._current_round)
shareable.add_cookie(AppConstants.CONTRIBUTION_ROUND, self._current_round)
task = Task(
name=self.task_name,
data=shareable,
result_received_cb=self._process_result,
)
self.relay_and_wait(
task=task,
targets=targets,
task_assignment_timeout=self.task_assignment_timeout,
fl_ctx=fl_ctx,
dynamic_targets=False,
abort_signal=abort_signal,
)
if self._persist_every_n_rounds != 0 and (self._current_round + 1) % self._persist_every_n_rounds == 0:
self.log_info(fl_ctx, "Start persist model on server.")
self.fire_event(AppEventType.BEFORE_LEARNABLE_PERSIST, fl_ctx)
self.persistor.save(self._last_learnable, fl_ctx)
self.fire_event(AppEventType.AFTER_LEARNABLE_PERSIST, fl_ctx)
self.log_info(fl_ctx, "End persist model on server.")
if (
self._snapshot_every_n_rounds != 0
and (self._current_round + 1) % self._snapshot_every_n_rounds == 0
):
# Call the self._engine to persist the snapshot of all the FLComponents
self._engine.persist_components(fl_ctx, completed=False)
self.log_debug(fl_ctx, "Ending current round={}.".format(self._current_round))
gc.collect()
self.log_debug(fl_ctx, "Cyclic ended.")
except Exception as e:
error_msg = f"Cyclic control_flow exception: {secure_format_exception(e)}"
self.log_error(fl_ctx, error_msg)
self.system_panic(error_msg, fl_ctx)
def stop_controller(self, fl_ctx: FLContext):
self.persistor.save(learnable=self._last_learnable, fl_ctx=fl_ctx)
self.log_debug(fl_ctx, "controller stopped")
def process_result_of_unknown_task(
self,
client: Client,
task_name: str,
client_task_id: str,
result: Shareable,
fl_ctx: FLContext,
):
self.log_warning(fl_ctx, f"Dropped result of unknown task: {task_name} from client {client.name}.")
def get_persist_state(self, fl_ctx: FLContext) -> dict:
return {
"current_round": self._current_round,
"end_round": self._end_round,
"last_learnable": self._last_learnable,
}
def restore(self, state_data: dict, fl_ctx: FLContext):
try:
self._current_round = state_data.get("current_round")
self._end_round = state_data.get("end_round")
self._last_learnable = state_data.get("last_learnable")
self._start_round = self._current_round
finally:
pass
| NVFlare-main | nvflare/app_common/workflows/cyclic_ctl.py |
# Copyright (c) 2021, 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 Any
from nvflare.apis.client import Client
from nvflare.apis.controller_spec import OperatorMethod, TaskOperatorKey
from nvflare.apis.fl_constant import ReturnCode
from nvflare.apis.fl_context import FLContext
from nvflare.apis.impl.controller import ClientTask, Controller, Task
from nvflare.apis.shareable import Shareable
from nvflare.apis.signal import Signal
from nvflare.app_common.abstract.aggregator import Aggregator
from nvflare.app_common.abstract.learnable_persistor import LearnablePersistor
from nvflare.app_common.abstract.model import ModelLearnable, make_model_learnable
from nvflare.app_common.abstract.shareable_generator import ShareableGenerator
from nvflare.app_common.app_constant import AppConstants
from nvflare.app_common.app_event_type import AppEventType
from nvflare.security.logging import secure_format_exception
from nvflare.widgets.info_collector import GroupInfoCollector, InfoCollector
def _check_non_neg_int(data: Any, name: str):
if not isinstance(data, int):
raise ValueError(f"{name} must be int but got {type(data)}")
if data < 0:
raise ValueError(f"{name} must be greater than or equal to 0.")
class ScatterAndGather(Controller):
def __init__(
self,
min_clients: int = 1000,
num_rounds: int = 5,
start_round: int = 0,
wait_time_after_min_received: int = 10,
aggregator_id=AppConstants.DEFAULT_AGGREGATOR_ID,
persistor_id="",
shareable_generator_id=AppConstants.DEFAULT_SHAREABLE_GENERATOR_ID,
train_task_name=AppConstants.TASK_TRAIN,
train_timeout: int = 0,
ignore_result_error: bool = False,
allow_empty_global_weights: bool = False,
task_check_period: float = 0.5,
persist_every_n_rounds: int = 1,
snapshot_every_n_rounds: int = 1,
):
"""The controller for ScatterAndGather Workflow.
The ScatterAndGather workflow defines FederatedAveraging on all clients.
The model persistor (persistor_id) is used to load the initial global model which is sent to all clients.
Each client sends it's updated weights after local training which is aggregated (aggregator_id). The
shareable generator is used to convert the aggregated weights to shareable and shareable back to weight.
The model_persistor also saves the model after training.
Args:
min_clients (int, optional): The minimum number of clients responses before
SAG starts to wait for `wait_time_after_min_received`. Note that SAG will move forward when all
available clients have responded regardless of this value. Defaults to 1000.
num_rounds (int, optional): The total number of training rounds. Defaults to 5.
start_round (int, optional): Start round for training. Defaults to 0.
wait_time_after_min_received (int, optional): Time to wait before beginning aggregation after
minimum number of clients responses has been received. Defaults to 10.
aggregator_id (str, optional): ID of the aggregator component. Defaults to "aggregator".
persistor_id (str, optional): ID of the persistor component. Defaults to "persistor".
shareable_generator_id (str, optional): ID of the shareable generator. Defaults to "shareable_generator".
train_task_name (str, optional): Name of the train task. Defaults to "train".
train_timeout (int, optional): Time to wait for clients to do local training.
ignore_result_error (bool, optional): whether this controller can proceed if client result has errors.
Defaults to False.
allow_empty_global_weights (bool, optional): whether to allow empty global weights. Some pipelines can have
empty global weights at first round, such that clients start training from scratch without any global info.
Defaults to False.
task_check_period (float, optional): interval for checking status of tasks. Defaults to 0.5.
persist_every_n_rounds (int, optional): persist the global model every n rounds. Defaults to 1.
If n is 0 then no persist.
snapshot_every_n_rounds (int, optional): persist the server state every n rounds. Defaults to 1.
If n is 0 then no persist.
Raises:
TypeError: when any of input arguments does not have correct type
ValueError: when any of input arguments is out of range
"""
super().__init__(task_check_period=task_check_period)
# Check arguments
if not isinstance(min_clients, int):
raise TypeError("min_clients must be int but got {}".format(type(min_clients)))
elif min_clients <= 0:
raise ValueError("min_clients must be greater than 0.")
_check_non_neg_int(num_rounds, "num_rounds")
_check_non_neg_int(start_round, "start_round")
_check_non_neg_int(wait_time_after_min_received, "wait_time_after_min_received")
_check_non_neg_int(train_timeout, "train_timeout")
_check_non_neg_int(persist_every_n_rounds, "persist_every_n_rounds")
_check_non_neg_int(snapshot_every_n_rounds, "snapshot_every_n_rounds")
if not isinstance(aggregator_id, str):
raise TypeError("aggregator_id must be a string but got {}".format(type(aggregator_id)))
if not isinstance(persistor_id, str):
raise TypeError("persistor_id must be a string but got {}".format(type(persistor_id)))
if not isinstance(shareable_generator_id, str):
raise TypeError("shareable_generator_id must be a string but got {}".format(type(shareable_generator_id)))
if not isinstance(train_task_name, str):
raise TypeError("train_task_name must be a string but got {}".format(type(train_task_name)))
if not isinstance(task_check_period, (int, float)):
raise TypeError(f"task_check_period must be an int or float but got {type(task_check_period)}")
elif task_check_period <= 0:
raise ValueError("task_check_period must be greater than 0.")
self.aggregator_id = aggregator_id
self.persistor_id = persistor_id
self.shareable_generator_id = shareable_generator_id
self.train_task_name = train_task_name
self.aggregator = None
self.persistor = None
self.shareable_gen = None
# config data
self._min_clients = min_clients
self._num_rounds = num_rounds
self._wait_time_after_min_received = wait_time_after_min_received
self._start_round = start_round
self._train_timeout = train_timeout
self._persist_every_n_rounds = persist_every_n_rounds
self._snapshot_every_n_rounds = snapshot_every_n_rounds
self.ignore_result_error = ignore_result_error
self.allow_empty_global_weights = allow_empty_global_weights
# workflow phases: init, train, validate
self._phase = AppConstants.PHASE_INIT
self._global_weights = make_model_learnable({}, {})
self._current_round = None
def start_controller(self, fl_ctx: FLContext) -> None:
self.log_info(fl_ctx, "Initializing ScatterAndGather workflow.")
self._phase = AppConstants.PHASE_INIT
self.aggregator = self._engine.get_component(self.aggregator_id)
if not isinstance(self.aggregator, Aggregator):
self.system_panic(
f"aggregator {self.aggregator_id} must be an Aggregator type object but got {type(self.aggregator)}",
fl_ctx,
)
return
self.shareable_gen = self._engine.get_component(self.shareable_generator_id)
if not isinstance(self.shareable_gen, ShareableGenerator):
self.system_panic(
f"Shareable generator {self.shareable_generator_id} must be a ShareableGenerator type object, "
f"but got {type(self.shareable_gen)}",
fl_ctx,
)
return
if self.persistor_id:
self.persistor = self._engine.get_component(self.persistor_id)
if not isinstance(self.persistor, LearnablePersistor):
self.system_panic(
f"Model Persistor {self.persistor_id} must be a LearnablePersistor type object, "
f"but got {type(self.persistor)}",
fl_ctx,
)
return
# initialize global model
fl_ctx.set_prop(AppConstants.START_ROUND, self._start_round, private=True, sticky=True)
fl_ctx.set_prop(AppConstants.NUM_ROUNDS, self._num_rounds, private=True, sticky=False)
if self.persistor:
self._global_weights = self.persistor.load(fl_ctx)
if not isinstance(self._global_weights, ModelLearnable):
self.system_panic(
reason=f"Expected global weights to be of type `ModelLearnable` but received {type(self._global_weights)}",
fl_ctx=fl_ctx,
)
return
if self._global_weights.is_empty():
if not self.allow_empty_global_weights:
# if empty not allowed, further check whether it is available from fl_ctx
self._global_weights = fl_ctx.get_prop(AppConstants.GLOBAL_MODEL)
if not isinstance(self._global_weights, ModelLearnable):
self.system_panic(
reason=f"Expected global weights to be of type `ModelLearnable` but received {type(self._global_weights)}",
fl_ctx=fl_ctx,
)
return
fl_ctx.set_prop(AppConstants.GLOBAL_MODEL, self._global_weights, private=True, sticky=True)
self.fire_event(AppEventType.INITIAL_MODEL_LOADED, fl_ctx)
def control_flow(self, abort_signal: Signal, fl_ctx: FLContext) -> None:
try:
self.log_info(fl_ctx, "Beginning ScatterAndGather training phase.")
self._phase = AppConstants.PHASE_TRAIN
fl_ctx.set_prop(AppConstants.PHASE, self._phase, private=True, sticky=False)
fl_ctx.set_prop(AppConstants.NUM_ROUNDS, self._num_rounds, private=True, sticky=False)
self.fire_event(AppEventType.TRAINING_STARTED, fl_ctx)
if self._current_round is None:
self._current_round = self._start_round
while self._current_round < self._start_round + self._num_rounds:
if self._check_abort_signal(fl_ctx, abort_signal):
return
self.log_info(fl_ctx, f"Round {self._current_round} started.")
fl_ctx.set_prop(AppConstants.GLOBAL_MODEL, self._global_weights, private=True, sticky=True)
fl_ctx.set_prop(AppConstants.CURRENT_ROUND, self._current_round, private=True, sticky=True)
self.fire_event(AppEventType.ROUND_STARTED, fl_ctx)
# Create train_task
data_shareable: Shareable = self.shareable_gen.learnable_to_shareable(self._global_weights, fl_ctx)
data_shareable.set_header(AppConstants.CURRENT_ROUND, self._current_round)
data_shareable.set_header(AppConstants.NUM_ROUNDS, self._num_rounds)
data_shareable.add_cookie(AppConstants.CONTRIBUTION_ROUND, self._current_round)
operator = {
TaskOperatorKey.OP_ID: self.train_task_name,
TaskOperatorKey.METHOD: OperatorMethod.BROADCAST,
TaskOperatorKey.TIMEOUT: self._train_timeout,
TaskOperatorKey.AGGREGATOR: self.aggregator_id,
}
train_task = Task(
name=self.train_task_name,
data=data_shareable,
operator=operator,
props={},
timeout=self._train_timeout,
before_task_sent_cb=self._prepare_train_task_data,
result_received_cb=self._process_train_result,
)
self.broadcast_and_wait(
task=train_task,
min_responses=self._min_clients,
wait_time_after_min_received=self._wait_time_after_min_received,
fl_ctx=fl_ctx,
abort_signal=abort_signal,
)
if self._check_abort_signal(fl_ctx, abort_signal):
return
self.log_info(fl_ctx, "Start aggregation.")
self.fire_event(AppEventType.BEFORE_AGGREGATION, fl_ctx)
aggr_result = self.aggregator.aggregate(fl_ctx)
fl_ctx.set_prop(AppConstants.AGGREGATION_RESULT, aggr_result, private=True, sticky=False)
self.fire_event(AppEventType.AFTER_AGGREGATION, fl_ctx)
self.log_info(fl_ctx, "End aggregation.")
if self._check_abort_signal(fl_ctx, abort_signal):
return
self.fire_event(AppEventType.BEFORE_SHAREABLE_TO_LEARNABLE, fl_ctx)
self._global_weights = self.shareable_gen.shareable_to_learnable(aggr_result, fl_ctx)
fl_ctx.set_prop(AppConstants.GLOBAL_MODEL, self._global_weights, private=True, sticky=True)
fl_ctx.sync_sticky()
self.fire_event(AppEventType.AFTER_SHAREABLE_TO_LEARNABLE, fl_ctx)
if self._check_abort_signal(fl_ctx, abort_signal):
return
if self.persistor:
if (
self._persist_every_n_rounds != 0
and (self._current_round + 1) % self._persist_every_n_rounds == 0
) or self._current_round == self._start_round + self._num_rounds - 1:
self.log_info(fl_ctx, "Start persist model on server.")
self.fire_event(AppEventType.BEFORE_LEARNABLE_PERSIST, fl_ctx)
self.persistor.save(self._global_weights, fl_ctx)
self.fire_event(AppEventType.AFTER_LEARNABLE_PERSIST, fl_ctx)
self.log_info(fl_ctx, "End persist model on server.")
self.fire_event(AppEventType.ROUND_DONE, fl_ctx)
self.log_info(fl_ctx, f"Round {self._current_round} finished.")
self._current_round += 1
# need to persist snapshot after round increased because the global weights should be set to
# the last finished round's result
if self._snapshot_every_n_rounds != 0 and self._current_round % self._snapshot_every_n_rounds == 0:
self._engine.persist_components(fl_ctx, completed=False)
self._phase = AppConstants.PHASE_FINISHED
self.log_info(fl_ctx, "Finished ScatterAndGather Training.")
except Exception as e:
error_msg = f"Exception in ScatterAndGather control_flow: {secure_format_exception(e)}"
self.log_exception(fl_ctx, error_msg)
self.system_panic(error_msg, fl_ctx)
def stop_controller(self, fl_ctx: FLContext):
self._phase = AppConstants.PHASE_FINISHED
def handle_event(self, event_type: str, fl_ctx: FLContext):
super().handle_event(event_type, fl_ctx)
if event_type == InfoCollector.EVENT_TYPE_GET_STATS:
collector = fl_ctx.get_prop(InfoCollector.CTX_KEY_STATS_COLLECTOR, None)
if collector:
if not isinstance(collector, GroupInfoCollector):
raise TypeError("collector must be GroupInfoCollector but got {}".format(type(collector)))
collector.add_info(
group_name=self._name,
info={"phase": self._phase, "current_round": self._current_round, "num_rounds": self._num_rounds},
)
def _prepare_train_task_data(self, client_task: ClientTask, fl_ctx: FLContext) -> None:
fl_ctx.set_prop(AppConstants.TRAIN_SHAREABLE, client_task.task.data, private=True, sticky=False)
self.fire_event(AppEventType.BEFORE_TRAIN_TASK, fl_ctx)
def _process_train_result(self, client_task: ClientTask, fl_ctx: FLContext) -> None:
result = client_task.result
client_name = client_task.client.name
self._accept_train_result(client_name=client_name, result=result, fl_ctx=fl_ctx)
# Cleanup task result
client_task.result = None
def process_result_of_unknown_task(
self, client: Client, task_name, client_task_id, result: Shareable, fl_ctx: FLContext
) -> None:
if self._phase == AppConstants.PHASE_TRAIN and task_name == self.train_task_name:
self._accept_train_result(client_name=client.name, result=result, fl_ctx=fl_ctx)
self.log_info(fl_ctx, f"Result of unknown task {task_name} sent to aggregator.")
else:
self.log_error(fl_ctx, "Ignoring result from unknown task.")
def _accept_train_result(self, client_name: str, result: Shareable, fl_ctx: FLContext) -> bool:
rc = result.get_return_code()
# Raise errors if bad peer context or execution exception.
if rc and rc != ReturnCode.OK:
if self.ignore_result_error:
self.log_warning(
fl_ctx,
f"Ignore the train result from {client_name} at round {self._current_round}. Train result error code: {rc}",
)
return False
else:
self.system_panic(
f"Result from {client_name} is bad, error code: {rc}. "
f"{self.__class__.__name__} exiting at round {self._current_round}.",
fl_ctx=fl_ctx,
)
return False
fl_ctx.set_prop(AppConstants.CURRENT_ROUND, self._current_round, private=True, sticky=True)
fl_ctx.set_prop(AppConstants.TRAINING_RESULT, result, private=True, sticky=False)
self.fire_event(AppEventType.BEFORE_CONTRIBUTION_ACCEPT, fl_ctx)
accepted = self.aggregator.accept(result, fl_ctx)
accepted_msg = "ACCEPTED" if accepted else "REJECTED"
self.log_info(
fl_ctx, f"Contribution from {client_name} {accepted_msg} by the aggregator at round {self._current_round}."
)
fl_ctx.set_prop(AppConstants.AGGREGATION_ACCEPTED, accepted, private=True, sticky=False)
self.fire_event(AppEventType.AFTER_CONTRIBUTION_ACCEPT, fl_ctx)
return accepted
def _check_abort_signal(self, fl_ctx, abort_signal: Signal):
if abort_signal.triggered:
self._phase = AppConstants.PHASE_FINISHED
self.log_info(fl_ctx, f"Abort signal received. Exiting at round {self._current_round}.")
return True
return False
def get_persist_state(self, fl_ctx: FLContext) -> dict:
return {
"current_round": self._current_round,
"start_round": self._start_round,
"num_rounds": self._num_rounds,
"global_weights": self._global_weights,
}
def restore(self, state_data: dict, fl_ctx: FLContext):
try:
self._current_round = state_data.get("current_round")
self._start_round = state_data.get("start_round")
self._num_rounds = state_data.get("num_rounds")
self._global_weights = state_data.get("global_weights")
finally:
pass
| NVFlare-main | nvflare/app_common/workflows/scatter_and_gather.py |
# Copyright (c) 2021, 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.
| NVFlare-main | nvflare/app_common/workflows/__init__.py |