syft-flwr 0.1.6__tar.gz → 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of syft-flwr might be problematic. Click here for more details.

Files changed (27) hide show
  1. {syft_flwr-0.1.6 → syft_flwr-0.2.0}/.gitignore +4 -1
  2. syft_flwr-0.2.0/PKG-INFO +26 -0
  3. syft_flwr-0.2.0/README.md +10 -0
  4. {syft_flwr-0.1.6 → syft_flwr-0.2.0}/pyproject.toml +13 -8
  5. {syft_flwr-0.1.6 → syft_flwr-0.2.0}/src/syft_flwr/__init__.py +1 -1
  6. syft_flwr-0.2.0/src/syft_flwr/consts.py +2 -0
  7. syft_flwr-0.2.0/src/syft_flwr/flower_client.py +187 -0
  8. {syft_flwr-0.1.6 → syft_flwr-0.2.0}/src/syft_flwr/flower_server.py +12 -4
  9. syft_flwr-0.2.0/src/syft_flwr/grid.py +494 -0
  10. {syft_flwr-0.1.6 → syft_flwr-0.2.0}/src/syft_flwr/mounts.py +1 -1
  11. {syft_flwr-0.1.6 → syft_flwr-0.2.0}/src/syft_flwr/run_simulation.py +124 -24
  12. syft_flwr-0.2.0/src/syft_flwr/utils.py +81 -0
  13. syft_flwr-0.1.6/PKG-INFO +0 -24
  14. syft_flwr-0.1.6/README.md +0 -8
  15. syft_flwr-0.1.6/src/syft_flwr/flower_client.py +0 -87
  16. syft_flwr-0.1.6/src/syft_flwr/grid.py +0 -221
  17. syft_flwr-0.1.6/src/syft_flwr/utils.py +0 -36
  18. {syft_flwr-0.1.6 → syft_flwr-0.2.0}/LICENSE +0 -0
  19. {syft_flwr-0.1.6 → syft_flwr-0.2.0}/src/syft_flwr/bootstrap.py +0 -0
  20. {syft_flwr-0.1.6 → syft_flwr-0.2.0}/src/syft_flwr/cli.py +0 -0
  21. {syft_flwr-0.1.6 → syft_flwr-0.2.0}/src/syft_flwr/config.py +0 -0
  22. {syft_flwr-0.1.6 → syft_flwr-0.2.0}/src/syft_flwr/flwr_compatibility.py +0 -0
  23. {syft_flwr-0.1.6 → syft_flwr-0.2.0}/src/syft_flwr/run.py +0 -0
  24. {syft_flwr-0.1.6 → syft_flwr-0.2.0}/src/syft_flwr/serde.py +0 -0
  25. {syft_flwr-0.1.6 → syft_flwr-0.2.0}/src/syft_flwr/strategy/__init__.py +0 -0
  26. {syft_flwr-0.1.6 → syft_flwr-0.2.0}/src/syft_flwr/strategy/fedavg.py +0 -0
  27. {syft_flwr-0.1.6 → syft_flwr-0.2.0}/src/syft_flwr/templates/main.py.tpl +0 -0
@@ -185,4 +185,7 @@ checkpoints/
185
185
  **/dataset/
186
186
 
187
187
  # Ruff cache
188
- .ruff_cache/
188
+ .ruff_cache/
189
+
190
+ # AI stuff
191
+ .claude/
@@ -0,0 +1,26 @@
1
+ Metadata-Version: 2.4
2
+ Name: syft-flwr
3
+ Version: 0.2.0
4
+ Summary: syft_flwr is an open source framework that facilitate federated learning projects using Flower over the SyftBox protocol
5
+ License-File: LICENSE
6
+ Requires-Python: >=3.10
7
+ Requires-Dist: flwr-datasets[vision]>=0.5.0
8
+ Requires-Dist: flwr[simulation]>=1.20.0
9
+ Requires-Dist: loguru>=0.7.3
10
+ Requires-Dist: safetensors>=0.6.2
11
+ Requires-Dist: syft-rds>=0.2.1
12
+ Requires-Dist: tomli-w>=1.2.0
13
+ Requires-Dist: tomli>=2.2.1
14
+ Requires-Dist: typing-extensions>=4.13.0
15
+ Description-Content-Type: text/markdown
16
+
17
+ # syft_flwr
18
+
19
+ `syft_flwr` is an open source framework that facilitate federated learning (FL) projects using [Flower](https://github.com/adap/flower) over the [SyftBox](https://github.com/OpenMined/syftbox) protocol
20
+
21
+ ![FL Training Process](notebooks/fl-diabetes-prediction/images/fltraining.gif)
22
+
23
+ ## Example Usages
24
+ Please look at the `notebooks/` folder for example use cases:
25
+ - [FL diabetes prediction](notebooks/fl-diabetes-prediction/README.md) shows how to train a federated model over distributed machines for multiple rounds
26
+ - [Federated analytics](notebooks/federated-analytics-diabetes/README.md) shows how to query statistics from private datasets from distributed machines and then aggregate them
@@ -0,0 +1,10 @@
1
+ # syft_flwr
2
+
3
+ `syft_flwr` is an open source framework that facilitate federated learning (FL) projects using [Flower](https://github.com/adap/flower) over the [SyftBox](https://github.com/OpenMined/syftbox) protocol
4
+
5
+ ![FL Training Process](notebooks/fl-diabetes-prediction/images/fltraining.gif)
6
+
7
+ ## Example Usages
8
+ Please look at the `notebooks/` folder for example use cases:
9
+ - [FL diabetes prediction](notebooks/fl-diabetes-prediction/README.md) shows how to train a federated model over distributed machines for multiple rounds
10
+ - [Federated analytics](notebooks/federated-analytics-diabetes/README.md) shows how to query statistics from private datasets from distributed machines and then aggregate them
@@ -1,18 +1,18 @@
1
1
  [project]
2
2
  name = "syft-flwr"
3
- version = "0.1.6"
3
+ version = "0.2.0"
4
4
  description = "syft_flwr is an open source framework that facilitate federated learning projects using Flower over the SyftBox protocol"
5
5
  readme = "README.md"
6
- requires-python = ">=3.9.2"
6
+ requires-python = ">=3.10"
7
7
  dependencies = [
8
- "flwr[simulation]==1.17.0",
8
+ "syft-rds>=0.2.1",
9
+ "flwr[simulation]>=1.20.0",
9
10
  "flwr-datasets[vision]>=0.5.0",
10
11
  "loguru>=0.7.3",
11
- "safetensors>=0.5.0",
12
+ "safetensors>=0.6.2",
12
13
  "typing-extensions>=4.13.0",
13
14
  "tomli>=2.2.1",
14
15
  "tomli-w>=1.2.0",
15
- "syft-rds==0.1.5",
16
16
  ]
17
17
 
18
18
  [project.scripts]
@@ -20,10 +20,15 @@ syft_flwr = "syft_flwr.cli:main"
20
20
 
21
21
  [tool.uv]
22
22
  dev-dependencies = [
23
- "ipykernel>=6.29.5",
23
+ "ipykernel>=6.30.1",
24
24
  "ipywidgets>=8.1.7",
25
- "pytest>=8.3.4",
26
- "pre-commit>=4.0.1",
25
+ "pytest>=8.4.1",
26
+ "pre-commit>=4.3.0",
27
+ "torch>=2.0.0",
28
+ "imblearn>=0.0",
29
+ "jupyterlab",
30
+ "pytest-xdist>=3.8.0",
31
+ "pytest-asyncio>=1.1.0",
27
32
  ]
28
33
 
29
34
  [build-system]
@@ -1,4 +1,4 @@
1
- __version__ = "0.1.6"
1
+ __version__ = "0.2.0"
2
2
 
3
3
  from syft_flwr.bootstrap import bootstrap
4
4
  from syft_flwr.run import run
@@ -0,0 +1,2 @@
1
+ # Environment variable to control encryption
2
+ SYFT_FLWR_ENCRYPTION_ENABLED = "SYFT_FLWR_ENCRYPTION_ENABLED"
@@ -0,0 +1,187 @@
1
+ import base64
2
+ import sys
3
+ import traceback
4
+
5
+ from flwr.client import ClientApp
6
+ from flwr.common import Context
7
+ from flwr.common.constant import ErrorCode, MessageType
8
+ from flwr.common.message import Error, Message
9
+ from loguru import logger
10
+ from syft_event import SyftEvents
11
+ from syft_event.types import Request
12
+ from typing_extensions import Optional, Union
13
+
14
+ from syft_flwr.flwr_compatibility import RecordDict, create_flwr_message
15
+ from syft_flwr.serde import bytes_to_flower_message, flower_message_to_bytes
16
+ from syft_flwr.utils import setup_client
17
+
18
+
19
+ class MessageHandler:
20
+ """Handles message processing for Flower client."""
21
+
22
+ def __init__(
23
+ self, client_app: ClientApp, context: Context, encryption_enabled: bool
24
+ ):
25
+ self.client_app = client_app
26
+ self.context = context
27
+ self.encryption_enabled = encryption_enabled
28
+
29
+ def prepare_reply(self, data: bytes) -> Union[str, bytes]:
30
+ """Prepare reply data based on encryption setting."""
31
+ if self.encryption_enabled:
32
+ logger.info(f"🔒 Preparing ENCRYPTED reply, size: {len(data)/2**20:.2f} MB")
33
+ return base64.b64encode(data).decode("utf-8")
34
+ else:
35
+ logger.info(f"📤 Preparing PLAINTEXT reply, size: {len(data)/2**20:.2f} MB")
36
+ return data
37
+
38
+ def process_message(self, message: Message) -> Union[str, bytes]:
39
+ """Process normal Flower message and return reply."""
40
+ logger.info(f"Processing message with metadata: {message.metadata}")
41
+ reply_message = self.client_app(message=message, context=self.context)
42
+ reply_bytes = flower_message_to_bytes(reply_message)
43
+ return self.prepare_reply(reply_bytes)
44
+
45
+ def create_error_reply(
46
+ self, message: Optional[Message], error: Error
47
+ ) -> Union[str, bytes]:
48
+ """Create error reply message."""
49
+ error_reply = create_flwr_message(
50
+ content=RecordDict(),
51
+ reply_to=message,
52
+ message_type=message.metadata.message_type if message else MessageType.TASK,
53
+ src_node_id=message.metadata.dst_node_id if message else 0,
54
+ dst_node_id=message.metadata.src_node_id if message else 0,
55
+ group_id=message.metadata.group_id if message else "",
56
+ run_id=message.metadata.run_id if message else 0,
57
+ error=error,
58
+ )
59
+ error_bytes = flower_message_to_bytes(error_reply)
60
+ logger.info(f"Error reply size: {len(error_bytes)/2**20:.2f} MB")
61
+ return self.prepare_reply(error_bytes)
62
+
63
+
64
+ class RequestProcessor:
65
+ """Processes incoming requests and handles encryption/decryption."""
66
+
67
+ def __init__(
68
+ self, message_handler: MessageHandler, box: SyftEvents, client_email: str
69
+ ):
70
+ self.message_handler = message_handler
71
+ self.box = box
72
+ self.client_email = client_email
73
+
74
+ def decode_request_body(self, request_body: Union[bytes, str]) -> bytes:
75
+ """Decode request body, handling base64 if encrypted."""
76
+ if not self.message_handler.encryption_enabled:
77
+ return request_body
78
+
79
+ try:
80
+ # Convert to string if bytes
81
+ if isinstance(request_body, bytes):
82
+ request_body_str = request_body.decode("utf-8")
83
+ else:
84
+ request_body_str = request_body
85
+ # Decode base64
86
+ decoded = base64.b64decode(request_body_str)
87
+ logger.debug("🔓 Decoded base64 message")
88
+ return decoded
89
+ except Exception:
90
+ # Not base64 or decoding failed, use as-is
91
+ return request_body
92
+
93
+ def is_stop_signal(self, message: Message) -> bool:
94
+ """Check if message is a stop signal."""
95
+ if message.metadata.message_type != MessageType.SYSTEM:
96
+ return False
97
+
98
+ # Check for stop action in config
99
+ if "config" in message.content and "action" in message.content["config"]:
100
+ return message.content["config"]["action"] == "stop"
101
+
102
+ # Alternative stop signal format
103
+ return message.metadata.group_id == "final"
104
+
105
+ def process(self, request: Request) -> Optional[Union[str, bytes]]:
106
+ """Process incoming request and return response."""
107
+ original_sender = request.headers.get("X-Syft-Original-Sender", "unknown")
108
+ encryption_status = (
109
+ "🔐 ENCRYPTED"
110
+ if self.message_handler.encryption_enabled
111
+ else "📥 PLAINTEXT"
112
+ )
113
+
114
+ logger.info(
115
+ f"{encryption_status} Received request from {original_sender}, "
116
+ f"id: {request.id}, size: {len(request.body) / 1024 / 1024:.2f} MB"
117
+ )
118
+
119
+ # Parse message
120
+ try:
121
+ request_body = self.decode_request_body(request.body)
122
+ message = bytes_to_flower_message(request_body)
123
+
124
+ if self.message_handler.encryption_enabled:
125
+ logger.debug(
126
+ f"🔓 Successfully decrypted message from {original_sender}"
127
+ )
128
+ except Exception as e:
129
+ logger.error(
130
+ f"❌ Failed to deserialize message from {original_sender}: {e}"
131
+ )
132
+ error = Error(
133
+ code=ErrorCode.CLIENT_APP_RAISED_EXCEPTION,
134
+ reason=f"Message deserialization failed: {e}",
135
+ )
136
+ return self.message_handler.create_error_reply(None, error)
137
+
138
+ # Handle message
139
+ try:
140
+ # Check for stop signal
141
+ if self.is_stop_signal(message):
142
+ logger.info("Received stop signal")
143
+ self.box._stop_event.set()
144
+ return None
145
+
146
+ # Process normal message
147
+ return self.message_handler.process_message(message)
148
+
149
+ except Exception as e:
150
+ error_message = f"Client: '{self.client_email}'. Error: {str(e)}. Traceback: {traceback.format_exc()}"
151
+ logger.error(error_message)
152
+
153
+ error = Error(
154
+ code=ErrorCode.CLIENT_APP_RAISED_EXCEPTION, reason=error_message
155
+ )
156
+ self.box._stop_event.set()
157
+ return self.message_handler.create_error_reply(message, error)
158
+
159
+
160
+ def syftbox_flwr_client(client_app: ClientApp, context: Context, app_name: str):
161
+ """Run the Flower ClientApp with SyftBox."""
162
+ # Setup
163
+ client, encryption_enabled, syft_flwr_app_name = setup_client(app_name)
164
+ box = SyftEvents(app_name=syft_flwr_app_name, client=client)
165
+
166
+ logger.info(f"Started SyftBox Flower Client on: {box.client.email}")
167
+ logger.info(f"syft_flwr app name: {syft_flwr_app_name}")
168
+
169
+ # Create handlers
170
+ message_handler = MessageHandler(client_app, context, encryption_enabled)
171
+ processor = RequestProcessor(message_handler, box, box.client.email)
172
+
173
+ # Register message handler
174
+ @box.on_request(
175
+ "/messages", auto_decrypt=encryption_enabled, encrypt_reply=encryption_enabled
176
+ )
177
+ def handle_messages(request: Request) -> Optional[Union[str, bytes]]:
178
+ return processor.process(request)
179
+
180
+ # Run
181
+ try:
182
+ box.run_forever()
183
+ except Exception as e:
184
+ logger.error(
185
+ f"Fatal error in syftbox_flwr_client: {str(e)}\n{traceback.format_exc()}"
186
+ )
187
+ sys.exit(1)
@@ -1,12 +1,13 @@
1
1
  import traceback
2
2
  from random import randint
3
3
 
4
- from loguru import logger
5
-
6
4
  from flwr.common import Context
7
5
  from flwr.server import ServerApp
8
6
  from flwr.server.run_serverapp import run as run_server
7
+ from loguru import logger
8
+
9
9
  from syft_flwr.grid import SyftGrid
10
+ from syft_flwr.utils import setup_client
10
11
 
11
12
 
12
13
  def syftbox_flwr_server(
@@ -16,10 +17,17 @@ def syftbox_flwr_server(
16
17
  app_name: str,
17
18
  ) -> Context:
18
19
  """Run the Flower ServerApp with SyftBox."""
19
- syft_flwr_app_name = f"flwr/{app_name}"
20
- syft_grid = SyftGrid(app_name=syft_flwr_app_name, datasites=datasites)
20
+ client, _, syft_flwr_app_name = setup_client(app_name)
21
+
22
+ # Construct the SyftGrid
23
+ syft_grid = SyftGrid(
24
+ app_name=syft_flwr_app_name, datasites=datasites, client=client
25
+ )
26
+
27
+ # Set the run id (random for now)
21
28
  run_id = randint(0, 1000)
22
29
  syft_grid.set_run(run_id)
30
+
23
31
  logger.info(f"Started SyftBox Flower Server on: {syft_grid._client.email}")
24
32
  logger.info(f"syft_flwr app name: {syft_flwr_app_name}")
25
33