tsukimiso 0.1.2__py3-none-any.whl

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.
tsukimiso/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ from .context import TkmArguments
2
+ from .trainer import TkmTrainer
3
+ from .datasets import FedDatasetsClassification
4
+
5
+
6
+ __all__ = [
7
+ "TkmArguments",
8
+ "TkmTrainer",
9
+ "FedDatasetsClassification",
10
+ ]
tsukimiso/context.py ADDED
@@ -0,0 +1,48 @@
1
+ from dataclasses import dataclass
2
+ from omegaconf import OmegaConf
3
+
4
+
5
+ @dataclass
6
+ class TkmArguments:
7
+ repo_name: str
8
+ server_url: str = "localhost:9200"
9
+ ws_max_size: int = 1048576000
10
+ random_seed: int = 42
11
+ device: str = "cpu"
12
+ log_output_path: str = "./log"
13
+
14
+ # train args
15
+ round: int = 10
16
+ batch_size: int = 100
17
+ inner_loop: int = 100
18
+
19
+ # DP
20
+ dp: bool = False
21
+ dp_target_eps: float|int = 8.0
22
+ dp_target_delta: float|int|None = None
23
+
24
+ # data args
25
+ data_cache_dir: str = "./data_cache"
26
+ partition_method: str = "hetero"
27
+ partition_alpha: float = 10.0
28
+
29
+ # poc-mode
30
+ worker_num: int = 1
31
+
32
+ @classmethod
33
+ def from_yml(cls, yml_path: str):
34
+ """ reader config YAML file
35
+
36
+ Args:
37
+ yml_path: config YAML file
38
+
39
+ Returns:
40
+ TkmArguments from YAML config file
41
+
42
+ """
43
+ loaded = OmegaConf.load(yml_path)
44
+ read_conf = TkmArguments(**loaded)
45
+
46
+ base_conf = OmegaConf.structured(TkmArguments)
47
+ merged = OmegaConf.merge(base_conf, read_conf)
48
+ return cls(**merged)
@@ -0,0 +1,28 @@
1
+ # Federated Datasets
2
+
3
+ This module provides functionality for data partitioning methods used in Federated learning trials.
4
+ The implementation method was referred to in [FedML](https://github.com/FedML-AI/FedML).
5
+
6
+ ## Function
7
+ * FedDatasetsClassification: Partitioning the dataset for classification tasks
8
+
9
+ ## Usage
10
+ Class Dataloader of PyTorch is returned.
11
+
12
+ ```python
13
+ from omegaconf import OmegaConf
14
+ from torchvision import datasets
15
+ from torchvision.transforms import ToTensor
16
+ from tsukimiso import FedDatasetsClassification
17
+
18
+ conf = OmegaConf.load("./config.yml")
19
+
20
+ train_data = datasets.CIFAR10(root=conf.data.data_cache_dir, train=True, download=True, transform=ToTensor())
21
+ valid_data = datasets.CIFAR10(root=conf.data.data_cache_dir, train=False, download=True, transform=ToTensor())
22
+ fed_datasets = FedDatasetsClassification(conf.common.client_num, conf.train.batch_size, conf.train.inner_loop,
23
+ conf.data.partition_method, conf.data.partition_alpha,
24
+ train_data, valid_data, 10)
25
+
26
+ # gotten Class Dataloader for federated
27
+ dataloader_for_client1 = fed_datasets.fed_dataset(1)
28
+ ```
@@ -0,0 +1,5 @@
1
+ from .cassification import FedDatasetsClassification
2
+
3
+ __all__ = [
4
+ "FedDatasetsClassification"
5
+ ]
@@ -0,0 +1,110 @@
1
+ import numpy as np
2
+ from typing import Dict
3
+ from torch.utils.data import Dataset, DataLoader
4
+ from .datasets_mixin import FedDatasetsBase, FedInnerLoopSampler
5
+
6
+
7
+ class FedDatasetsClassification(FedDatasetsBase):
8
+ def __init__(self, clients_num: int, batch_size: int, inner_loop: int, partition_method: str, partition_alpha: float,
9
+ train_data: Dataset, valid_data: Dataset, class_num: int, min_len=10):
10
+ """ Dataset build Tool for Federate-learning classification
11
+
12
+ Args:
13
+ clients_num: client num
14
+ batch_size: batch size
15
+ inner_loop: How often every N steps should communication take place?
16
+ partition_method: partition method (hetero or homo)
17
+ partition_alpha: partition alpha
18
+ train_data: train data in PyTorch format
19
+ valid_data: valid data in PyTorch format
20
+ class_num: class num
21
+ min_len: minimum number of datasets
22
+ """
23
+ super().__init__(batch_size, clients_num, train_data, valid_data, class_num)
24
+ self._partition_method = partition_method
25
+ self._partition_alpha = partition_alpha
26
+
27
+ indices = self._partition_data(self._train_data, self._train_data_num, min_len)
28
+ self._fed_train_data_loader, self._fed_train_data_num = self._build_datasets(batch_size, inner_loop, self._train_data, indices)
29
+
30
+ indices = self._partition_data(self._valid_data, self._valid_data_num, min_len)
31
+ self._fed_valid_data_loader, _ = self._build_datasets(batch_size, inner_loop, self._valid_data, indices)
32
+
33
+ def _partition_data(self, dataset: Dataset, n_data: int, min_len: int) -> dict:
34
+ """ data partitioning
35
+
36
+ Args:
37
+ dataset: dataset in PyTorch format
38
+ n_data: data num on dataset
39
+ min_len: minimum number of datasets
40
+
41
+ Returns:
42
+
43
+ """
44
+ net_data_idx_map = {}
45
+ np.random.seed(self._random_seed)
46
+ target = np.array(dataset.targets)
47
+
48
+ if self._partition_method == "hetero":
49
+ min_size = 0
50
+ while min_size < min_len:
51
+ idx_batch = [[] for _ in range(self._clients_num)]
52
+ # for each class in the dataset
53
+ for k in range(self._class_num):
54
+ idx_k = np.where(target == k)[0]
55
+ np.random.shuffle(idx_k)
56
+ proportions = np.random.dirichlet(np.repeat(self._partition_alpha, self._clients_num))
57
+ # Balance
58
+ proportions = np.array(
59
+ [
60
+ p * (len(idx_j) < n_data / self._clients_num)
61
+ for p, idx_j in zip(proportions, idx_batch)
62
+ ]
63
+ )
64
+ proportions = proportions / proportions.sum()
65
+ proportions = (np.cumsum(proportions) * len(idx_k)).astype(int)[:-1]
66
+ idx_batch = [
67
+ idx_j + idx.tolist()
68
+ for idx_j, idx in zip(idx_batch, np.split(idx_k, proportions))
69
+ ]
70
+ min_size = min([len(idx_j) for idx_j in idx_batch])
71
+
72
+ for j in range(self._clients_num):
73
+ np.random.shuffle(idx_batch[j])
74
+ net_data_idx_map[j] = idx_batch[j]
75
+ self._logger.info("partition data hetero alpha= %.1f CL=%d: datasize= %d / %d" %
76
+ (self._partition_alpha, j, len(net_data_idx_map[j]), n_data))
77
+
78
+ else:
79
+ # partition_method = homo
80
+ total_num = n_data
81
+ indices = np.random.permutation(total_num)
82
+ batch_indices = np.array_split(indices, self._clients_num)
83
+ net_data_idx_map = {i: batch_indices[i].tolist() for i in range(self._clients_num)}
84
+ for i in range(self._clients_num):
85
+ self._logger.info("partition data homo CL=%d: datasize= %d / %d" %
86
+ (i, len(net_data_idx_map[i]), n_data))
87
+ return net_data_idx_map
88
+
89
+ def _build_datasets(self, batch_size: int, inner_loop: int, dataset: Dataset, indices: Dict) -> tuple[dict, dict]:
90
+ """ building dataset
91
+
92
+ Args:
93
+ batch_size: batch size
94
+ inner_loop: inner loop
95
+ dataset: dataset in PyTorch format
96
+ indices: indices of dataset
97
+
98
+ Returns:
99
+ (dataloaders in PyTprch format, datasizes)
100
+
101
+ """
102
+ dataloader = {}
103
+ datasize = {}
104
+
105
+ for client_idx in range(self._clients_num):
106
+ _sampler = FedInnerLoopSampler(batch_size, inner_loop, indices[client_idx])
107
+ dataloader[client_idx] = DataLoader(dataset=dataset, batch_size=self._batch_size, sampler=_sampler)
108
+ datasize[client_idx] = len(indices[client_idx])
109
+
110
+ return dataloader, datasize
@@ -0,0 +1,102 @@
1
+ from typing import List
2
+ from logging import getLogger
3
+ from abc import ABCMeta
4
+ from torch.utils.data import Dataset, DataLoader, sampler
5
+
6
+
7
+ class FedDatasetsBase(metaclass=ABCMeta):
8
+ def __init__(self, batch_size, clients_num, train_data: Dataset, valid_data: Dataset, class_num=0, random_seed=0):
9
+ """ Dataset build Tool for Federate-learning
10
+
11
+ Args:
12
+ batch_size: batch size
13
+ clients_num: client num
14
+ train_data: train data in PyTorch format
15
+ valid_data: valid data in PyTorch format
16
+ class_num: class num
17
+ random_seed: random seed
18
+ """
19
+ self._train_data = train_data
20
+ self._valid_data = valid_data
21
+ self._class_num = class_num
22
+ self._batch_size = batch_size
23
+ self._clients_num = clients_num
24
+ self._random_seed = random_seed
25
+
26
+ self._train_data_loader = DataLoader(dataset=self._train_data, batch_size=self._batch_size,
27
+ shuffle=True, drop_last=True)
28
+ self._valid_data_loader = DataLoader(dataset=self._valid_data, batch_size=self._batch_size,
29
+ shuffle=False, drop_last=True)
30
+ self._train_data_num = len(self._train_data)
31
+ self._valid_data_num = len(self._valid_data)
32
+
33
+ self._fed_train_data_num = {}
34
+ self._fed_train_data_loader = {}
35
+ self._fed_valid_data_loader = {}
36
+
37
+ self._logger = getLogger("FedDatasets")
38
+
39
+ def fed_dataset(self, client_id: int) -> dict:
40
+ """ datasets for federate-learning
41
+
42
+ Args:
43
+ client_id: client id
44
+
45
+ Returns:
46
+ dict: train_dataloader, valid_dataloader, train_num
47
+
48
+ """
49
+ return {
50
+ "train_dataloader": self._fed_train_data_loader[client_id],
51
+ "valid_dataloader": self._fed_valid_data_loader[client_id],
52
+ "train_num": self._fed_train_data_num[client_id]
53
+ }
54
+
55
+ @property
56
+ def train_data_loader(self) -> DataLoader:
57
+ return self._train_data_loader
58
+
59
+ @property
60
+ def valid_data_loader(self) -> DataLoader:
61
+ return self._valid_data_loader
62
+
63
+ @property
64
+ def class_num(self):
65
+ return self._class_num
66
+
67
+
68
+ class FedInnerLoopSampler(sampler.Sampler[int]):
69
+ def __init__(self, batch_size: int, inner_loop: int, indices: List):
70
+ """ Sampler for inner loop of federate-learning
71
+
72
+ Args:
73
+ batch_size: batch size
74
+ inner_loop: inner loop
75
+ indices: dataset indices
76
+ """
77
+ super().__init__()
78
+ self._n_data = len(indices)
79
+ self._batch_size = batch_size
80
+ self._inner_loop = inner_loop
81
+
82
+ self._indices = []
83
+ self._data_indices = indices
84
+ self._n_data_batch = self._batch_size * self._inner_loop if self._inner_loop is not None else self._n_data
85
+ self._n_offset = 0
86
+
87
+ def __len__(self):
88
+ return self._n_data_batch
89
+
90
+ def __iter__(self):
91
+ # Removal of used data
92
+ self._indices = self._indices[self._n_offset:]
93
+ self._n_offset = 0 # reset start index
94
+
95
+ # Prepare at least 1 epoch's worth of data in the index list that stores the data call order.
96
+ while len(self._indices) <= self._n_data_batch:
97
+ self._indices += self._data_indices
98
+
99
+ sidx, eidx = self._n_offset, self._n_offset + self._n_data_batch
100
+ indices = self._indices[sidx:eidx].copy()
101
+ self._n_offset = eidx
102
+ yield from indices
tsukimiso/pb/README.md ADDED
@@ -0,0 +1,6 @@
1
+ # FroseAi protobuf
2
+ ### Build
3
+
4
+ ```shell
5
+ protoc --python_out=. ./tsukimiso.proto
6
+ ```
@@ -0,0 +1,3 @@
1
+ from .tsukimiso_pb2 import TkmParams, TkmMetrics
2
+
3
+ __all__ = ["TkmParams", "TkmMetrics"]
@@ -0,0 +1,15 @@
1
+ syntax = "proto3";
2
+
3
+ message TkmMetrics {
4
+ string name = 1;
5
+ float value = 2;
6
+ }
7
+
8
+ message TkmParams {
9
+ string id = 1;
10
+ string op = 2;
11
+ int32 round = 3;
12
+ bytes params = 4;
13
+
14
+ repeated TkmMetrics metrics = 5;
15
+ }
@@ -0,0 +1,27 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Generated by the protocol buffer compiler. DO NOT EDIT!
3
+ # source: tsukimiso.proto
4
+ """Generated protocol buffer code."""
5
+ from google.protobuf.internal import builder as _builder
6
+ from google.protobuf import descriptor as _descriptor
7
+ from google.protobuf import descriptor_pool as _descriptor_pool
8
+ from google.protobuf import symbol_database as _symbol_database
9
+ # @@protoc_insertion_point(imports)
10
+
11
+ _sym_db = _symbol_database.Default()
12
+
13
+
14
+
15
+
16
+ DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x0ftsukimiso.proto\")\n\nTkmMetrics\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x02\"`\n\tTkmParams\x12\n\n\x02id\x18\x01 \x01(\t\x12\n\n\x02op\x18\x02 \x01(\t\x12\r\n\x05round\x18\x03 \x01(\x05\x12\x0e\n\x06params\x18\x04 \x01(\x0c\x12\x1c\n\x07metrics\x18\x05 \x03(\x0b\x32\x0b.TkmMetricsb\x06proto3')
17
+
18
+ _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
19
+ _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'tsukimiso_pb2', globals())
20
+ if _descriptor._USE_C_DESCRIPTORS == False:
21
+
22
+ DESCRIPTOR._options = None
23
+ _TKMMETRICS._serialized_start=19
24
+ _TKMMETRICS._serialized_end=60
25
+ _TKMPARAMS._serialized_start=62
26
+ _TKMPARAMS._serialized_end=158
27
+ # @@protoc_insertion_point(module_scope)
tsukimiso/server.py ADDED
@@ -0,0 +1,135 @@
1
+ import uvicorn
2
+ import torch
3
+ from starlette.endpoints import WebSocketEndpoint
4
+ from safetensors.torch import save, load
5
+ from starlette.applications import Starlette
6
+ from starlette.routing import WebSocketRoute
7
+ from .pb import TkmParams
8
+
9
+
10
+ class TkmSrvAggregator(WebSocketEndpoint):
11
+ encoding = "bytes"
12
+ _active_conn = {}
13
+
14
+ async def on_connect(self, websocket):
15
+ """ WebSocket connection handler
16
+
17
+ Args:
18
+ websocket: starlette WebSocket object
19
+
20
+ Returns: None
21
+
22
+ """
23
+ await websocket.accept()
24
+ self._active_conn[websocket] = {
25
+ "id": None,
26
+ "params": None,
27
+ "received": False
28
+ }
29
+
30
+ async def on_receive(self, websocket, data: bytes):
31
+ """ WebSocket receive handler
32
+
33
+ Args:
34
+ websocket: starlette WebSocket object
35
+ data: received bytes
36
+
37
+ Returns: None
38
+
39
+ """
40
+ msg = TkmParams()
41
+ msg.ParseFromString(data)
42
+ self._active_conn[websocket]["id"] = msg.id
43
+
44
+ if msg.op == "hello":
45
+ pass
46
+
47
+ elif msg.op == "update":
48
+ self._active_conn[websocket]["params"] = load(msg.params)
49
+ self._active_conn[websocket]["received"] = True
50
+
51
+ if self._is_all_received():
52
+ msg.params = self.aggregate()
53
+ await self.broadcast(msg.SerializeToString())
54
+
55
+ self._clear_all_received()
56
+
57
+ async def on_disconnect(self, websocket, close_code):
58
+ """ WebSocket disconnect handler
59
+
60
+ Args:
61
+ websocket: starlette WebSocket object
62
+ close_code: close code
63
+
64
+ Returns: None
65
+
66
+ """
67
+ self._active_conn.pop(websocket, None)
68
+
69
+ @classmethod
70
+ async def broadcast(cls, message: bytes):
71
+ """ broadband on WebSocket
72
+
73
+ Args:
74
+ message: send message
75
+
76
+ Returns: None
77
+
78
+ """
79
+ for connection in cls._active_conn:
80
+ await connection.send_bytes(message)
81
+
82
+ @classmethod
83
+ def client_num(cls) -> int:
84
+ """
85
+
86
+ Returns: client num
87
+
88
+ """
89
+ return len(cls._active_conn)
90
+
91
+ @classmethod
92
+ def _is_all_received(cls):
93
+ """
94
+
95
+ Returns: all received? (true or false)
96
+
97
+ """
98
+ return all(conn["received"] for conn in cls._active_conn.values())
99
+
100
+ @classmethod
101
+ def _clear_all_received(cls):
102
+ """ clear all received flag
103
+
104
+ Returns: None
105
+
106
+ """
107
+ for conn in cls._active_conn.values():
108
+ conn["received"] = False
109
+
110
+ @classmethod
111
+ def aggregate(cls) -> bytes:
112
+ """ aggregate
113
+
114
+ Returns: aggregated params in safetensors format
115
+
116
+ """
117
+ with torch.no_grad():
118
+ average_params = {}
119
+ sample_rate = 1 / cls.client_num()
120
+ for i, conn in enumerate(cls._active_conn.values()):
121
+ p = conn["params"]
122
+ for k, v in p.items():
123
+ if i == 0:
124
+ average_params[k] = v * sample_rate
125
+ else:
126
+ average_params[k] += v * sample_rate
127
+
128
+ return save(average_params)
129
+
130
+
131
+ app = Starlette(routes=[WebSocketRoute("/ws", TkmSrvAggregator)])
132
+
133
+
134
+ def run(host: str = "127.0.0.1", port: int = 9200, ws_max_size: int = 1024 * 1024 * 1024):
135
+ uvicorn.run(app, host=host, port=port, ws_max_size=ws_max_size, ws_ping_interval=120., ws_ping_timeout=120.)
tsukimiso/trainer.py ADDED
@@ -0,0 +1,198 @@
1
+ import websocket
2
+ import torch
3
+ import uuid
4
+ from torch import nn
5
+ from torch.utils.data import DataLoader
6
+ from torch.optim import Optimizer
7
+ from opacus.optimizers.optimizer import DPOptimizer
8
+ from logging import getLogger
9
+ from abc import ABCMeta, abstractmethod
10
+ from opacus import PrivacyEngine
11
+ from opacus.accountants.utils import get_noise_multiplier
12
+ from opacus.utils.batch_memory_manager import BatchMemoryManager
13
+ from safetensors.torch import save, load
14
+ from tsukimiso.context import TkmArguments
15
+ from tsukimiso.pb import TkmParams
16
+
17
+
18
+ class TkmTrainer(metaclass=ABCMeta):
19
+ def __init__(self, args: TkmArguments, model: nn.Module, optimizer: Optimizer, loss_func: nn.Module,
20
+ train_dataloader: DataLoader, valid_dataloader: DataLoader):
21
+ """ Tsukimiso trainer
22
+
23
+ Args:
24
+ args: args on TkmArguments
25
+ model: model in PyTorch format
26
+ optimizer: optimizer in PyTorch format
27
+ loss_func: loss function in PyTorch format
28
+ train_dataloader: train dataloader in PyTorch format
29
+ valid_dataloader: valid dataloader in PyTorch format
30
+ """
31
+ self._logger = getLogger("TkmTrainer")
32
+ self._client_id = str(uuid.uuid4())
33
+ self._device = args.device
34
+ self._round = 0
35
+ self._comm_round = args.round
36
+ self._repo_name = args.repo_name
37
+ self._server_url = args.server_url
38
+ self._loss_func = loss_func
39
+ self._batch_size = args.batch_size
40
+ self._dp_on = args.dp
41
+
42
+ self._model = model
43
+ self._optimizer = optimizer
44
+ self._train_dataloader = train_dataloader
45
+ self._valid_dataloader = valid_dataloader
46
+
47
+ if self._dp_on:
48
+ self._noise_multiplier = get_noise_multiplier(
49
+ target_epsilon=args.dp_target_eps,
50
+ target_delta=args.dp_target_delta if args.dp_target_delta is not None else 1 / len(train_dataloader.dataset),
51
+ sample_rate=args.batch_size / len(train_dataloader.dataset),
52
+ epochs=self._comm_round,
53
+ accountant="rdp"
54
+ )
55
+ print(f"Calculated Noise Multiplier (σ): {self._noise_multiplier:.4f}")
56
+ privacy_engine = PrivacyEngine()
57
+ self._model, self._optimizer, self._train_dataloader = privacy_engine.make_private(
58
+ module=self._model,
59
+ optimizer=self._optimizer,
60
+ data_loader=self._train_dataloader,
61
+ noise_multiplier=self._noise_multiplier,
62
+ max_grad_norm=1.0,
63
+ )
64
+
65
+ ws_target_url = "ws://%s/ws" % self.server_url
66
+ self._ws = websocket.create_connection(ws_target_url)
67
+ self.hello()
68
+
69
+ def run(self):
70
+ """ Tsukimiso trainer run
71
+
72
+ Returns: None
73
+
74
+ """
75
+ self.model.to(self.device)
76
+
77
+ for _ in range(self._comm_round):
78
+ if self._dp_on:
79
+ with BatchMemoryManager(
80
+ data_loader=self.train_dataloader,
81
+ max_physical_batch_size=self._batch_size,
82
+ optimizer=self.optimizer
83
+ ) as memory_safe_data_loader:
84
+ self._train_dataloader = memory_safe_data_loader
85
+ self.model.train()
86
+ train_metrics = self.train()
87
+ else:
88
+ self.model.train()
89
+ train_metrics = self.train()
90
+
91
+ self.model.eval()
92
+ valid_metrics = self.valid()
93
+ print("[Rnd=%d Cl:%s] tra: %s / val: %s" % (self._round, self.client_id, str(train_metrics), str(valid_metrics)))
94
+
95
+ self.update()
96
+
97
+ @abstractmethod
98
+ def train(self) -> dict:
99
+ pass
100
+
101
+ @abstractmethod
102
+ def valid(self) -> dict:
103
+ pass
104
+
105
+ @property
106
+ def model(self) -> nn.Module:
107
+ return self._model
108
+
109
+ @property
110
+ def optimizer(self) -> torch.optim.Optimizer|DPOptimizer:
111
+ return self._optimizer
112
+
113
+ @property
114
+ def loss_func(self) -> nn.Module:
115
+ return self._loss_func
116
+
117
+ @property
118
+ def repo_name(self) -> str:
119
+ return self._repo_name
120
+
121
+ @property
122
+ def server_url(self) -> str:
123
+ return self._server_url
124
+
125
+ @property
126
+ def client_id(self) -> str:
127
+ return self._client_id
128
+
129
+ @property
130
+ def device(self):
131
+ return self._device
132
+
133
+ @property
134
+ def train_dataloader(self) -> DataLoader:
135
+ return self._train_dataloader
136
+
137
+ @property
138
+ def valid_dataloader(self) -> DataLoader:
139
+ return self._valid_dataloader
140
+
141
+ @property
142
+ def round(self) -> int:
143
+ return self._round
144
+
145
+ @torch.no_grad()
146
+ def hello(self) -> None:
147
+ """ send hello message to Tsukimiso server
148
+
149
+ Returns: None
150
+
151
+ """
152
+ # send hello
153
+ msg = TkmParams()
154
+ msg.op = "hello"
155
+ self._ws.send(msg.SerializeToString(), websocket.ABNF.OPCODE_BINARY)
156
+
157
+ @torch.no_grad()
158
+ def update(self) -> None:
159
+ """ send update message to Tsukimiso server
160
+
161
+ Returns: None
162
+
163
+ """
164
+ # send update
165
+ msg = TkmParams()
166
+ msg.op = "update"
167
+ msg.id = self._client_id
168
+ msg.params = self.update_pt2st()
169
+ self._ws.send(msg.SerializeToString(), websocket.ABNF.OPCODE_BINARY)
170
+
171
+ # get aggregated model
172
+ message = self._ws.recv()
173
+ msg.ParseFromString(message)
174
+ self.update_st2pt(msg.params)
175
+
176
+ self._round += 1
177
+
178
+ def update_pt2st(self) -> bytes:
179
+ """ update PyTorch model to safetensors
180
+
181
+ Returns: model parameters in safetensors format
182
+
183
+ """
184
+ state_dict = self.model.cpu().state_dict()
185
+ return save(state_dict)
186
+
187
+ def update_st2pt(self, buf: bytes) -> None:
188
+ """ update safetensors model to PyTorch model
189
+
190
+ Args:
191
+ buf: safetensors object(bytes)
192
+
193
+ Returns: None (Expand directly into a class object)
194
+
195
+ """
196
+ state_dict = load(buf)
197
+ self.model.load_state_dict(state_dict)
198
+ self.model.to(self.device)
@@ -0,0 +1,23 @@
1
+ Metadata-Version: 2.5
2
+ Name: tsukimiso
3
+ Version: 0.1.2
4
+ Summary: An OSS federated learning framework designed for production use
5
+ License-File: LICENSE
6
+ Requires-Python: >=3.12
7
+ Requires-Dist: numpy
8
+ Requires-Dist: omegaconf
9
+ Requires-Dist: opacus
10
+ Requires-Dist: protobuf
11
+ Requires-Dist: pydantic
12
+ Requires-Dist: pyyaml
13
+ Requires-Dist: requests
14
+ Requires-Dist: safetensors
15
+ Requires-Dist: starlette
16
+ Requires-Dist: torch
17
+ Requires-Dist: torchvision
18
+ Requires-Dist: uvicorn[standard]
19
+ Requires-Dist: websocket-client
20
+ Description-Content-Type: text/markdown
21
+
22
+ # tsukimiso
23
+
@@ -0,0 +1,17 @@
1
+ tsukimiso/__init__.py,sha256=6f7gxoMYuDE3o2Do9N1dCXu0Fg8enc07r8cVWsY3f2o,201
2
+ tsukimiso/context.py,sha256=EAIXXdYXZpliKNJdL4VPPfhkuzwL_mN6JKhz4PmWG-U,1094
3
+ tsukimiso/server.py,sha256=fPVOaAwXgLFDT9MT--zdGB8ARB2wELNnjyxo7y6YvvE,3410
4
+ tsukimiso/trainer.py,sha256=OvQ19JpDNaoLCCLCouWFF5Wt-lsTCx18VcLXIzZKQKk,6012
5
+ tsukimiso/datasets/README.md,sha256=n_eYKsAqgdrjOZSOq8Y0NDVIS9VaTFHWqiNBl1bxias,1161
6
+ tsukimiso/datasets/__init__.py,sha256=Qc5C-NCfrbC0Nz_hbwmVptXX1Qd9LDn8lunyMuLRyb8,100
7
+ tsukimiso/datasets/cassification.py,sha256=b_2F0lJTdOhjq8OUZWC2HFKH2OGEvy9BdqMYjIW608k,4857
8
+ tsukimiso/datasets/datasets_mixin.py,sha256=ekItZ8Tuo9U_eFPY-GHfCWvKlxsYyDZ4B7LsiHmwhL0,3492
9
+ tsukimiso/pb/README.md,sha256=0SiofU_JeWH0nUlNJS7LZofd-DX_aJ69APHnsazVRRk,83
10
+ tsukimiso/pb/__init__.py,sha256=LTehiUaylZMhkYY_zVqtkbFP-jbZNiOo-GCASVw127A,88
11
+ tsukimiso/pb/tsukimiso.proto,sha256=M6Vpu4bfaC17zfYG1m2RSAsSWQKcx-g8Bo9bnnoMHkY,213
12
+ tsukimiso/pb/tsukimiso_pb2.py,sha256=Py9vSNyjbEYYS_9bInXRF5acBXfMTrqQoK7FhTZunyc,1246
13
+ tsukimiso-0.1.2.dist-info/METADATA,sha256=3gmF3Lhd2UFL0qFAx7Tsy9NBmIOY-rAN_Hoe5LSMvWY,553
14
+ tsukimiso-0.1.2.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
15
+ tsukimiso-0.1.2.dist-info/entry_points.txt,sha256=tymg3BgyqGNR15uSlkurXCJ3UdXxj8LD0voI2EzrbiI,51
16
+ tsukimiso-0.1.2.dist-info/licenses/LICENSE,sha256=GUG9fY9PrEsAAYQ7lnsYFNiQMZVW_3ASX0FIbiS9Rqw,11348
17
+ tsukimiso-0.1.2.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ tsukimiso = tsukimiso.server:run
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Masahiko Hashimoto
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.