125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368 | class Lightning:
DEFAULT_MODEL_WEIGHT = 1
BYPASS_MODEL_WEIGHT = 0
def __init__(self, model, data, config=None):
# self.model = torch.compile(model, mode="reduce-overhead")
self.model = model
self.data = data
self.config = config
self._trainer = None
self.epochs = 1
self.round = 0
self.experiment_name = self.config.participant["scenario_args"]["name"]
self.idx = self.config.participant["device_args"]["idx"]
self.log_dir = os.path.join(self.config.participant["tracking_args"]["log_dir"], self.experiment_name)
self._logger = None
self.create_logger()
enable_deterministic(self.config)
@property
def logger(self):
return self._logger
def get_round(self):
return self.round
def set_model(self, model):
self.model = model
def set_data(self, data):
self.data = data
def create_logger(self):
if self.config.participant["tracking_args"]["local_tracking"] == "csv":
nebulalogger = CSVLogger(f"{self.log_dir}", name="metrics", version=f"participant_{self.idx}")
elif self.config.participant["tracking_args"]["local_tracking"] == "basic":
logger_config = None
if self._logger is not None:
logger_config = self._logger.get_logger_config()
nebulalogger = NebulaTensorBoardLogger(
self.config.participant["scenario_args"]["start_time"],
f"{self.log_dir}",
name="metrics",
version=f"participant_{self.idx}",
log_graph=False,
)
# Restore logger configuration
nebulalogger.set_logger_config(logger_config)
elif self.config.participant["tracking_args"]["local_tracking"] == "advanced":
nebulalogger = NebulaLogger(
config=self.config,
engine=self,
scenario_start_time=self.config.participant["scenario_args"]["start_time"],
repo=f"{self.config.participant['tracking_args']['log_dir']}",
experiment=self.experiment_name,
run_name=f"participant_{self.idx}",
train_metric_prefix="train_",
test_metric_prefix="test_",
val_metric_prefix="val_",
log_system_params=False,
)
# nebulalogger_aim = NebulaLogger(config=self.config, engine=self, scenario_start_time=self.config.participant["scenario_args"]["start_time"], repo=f"aim://nebula-frontend:8085",
# experiment=self.experiment_name, run_name=f"participant_{self.idx}",
# train_metric_prefix='train_', test_metric_prefix='test_', val_metric_prefix='val_', log_system_params=False)
self.config.participant["tracking_args"]["run_hash"] = nebulalogger.experiment.hash
else:
nebulalogger = None
self._logger = nebulalogger
def create_trainer(self):
# Create a new trainer and logger for each round
self.create_logger()
num_gpus = torch.cuda.device_count()
if self.config.participant["device_args"]["accelerator"] == "gpu" and num_gpus > 0:
gpu_index = self.config.participant["device_args"]["idx"] % num_gpus
logging_training.info(f"Creating trainer with accelerator GPU ({gpu_index})")
self._trainer = Trainer(
callbacks=[ModelSummary(max_depth=1), NebulaProgressBar()],
max_epochs=self.epochs,
accelerator=self.config.participant["device_args"]["accelerator"],
devices=[gpu_index],
logger=self._logger,
enable_checkpointing=False,
enable_model_summary=False,
# deterministic=True
)
else:
logging_training.info("Creating trainer with accelerator CPU")
self._trainer = Trainer(
callbacks=[ModelSummary(max_depth=1), NebulaProgressBar()],
max_epochs=self.epochs,
accelerator=self.config.participant["device_args"]["accelerator"],
devices="auto",
logger=self._logger,
enable_checkpointing=False,
enable_model_summary=False,
# deterministic=True
)
logging_training.info(f"Trainer strategy: {self._trainer.strategy}")
def validate_neighbour_model(self, neighbour_model_param):
avg_loss = 0
running_loss = 0
bootstrap_dataloader = self.data.bootstrap_dataloader()
num_samples = 0
neighbour_model = copy.deepcopy(self.model)
neighbour_model.load_state_dict(neighbour_model_param)
# enable evaluation mode, prevent memory leaks.
# no need to switch back to training since model is not further used.
if torch.cuda.is_available():
neighbour_model = neighbour_model.to("cuda")
neighbour_model.eval()
# bootstrap_dataloader = bootstrap_dataloader.to('cuda')
with torch.no_grad():
for inputs, labels in bootstrap_dataloader:
if torch.cuda.is_available():
inputs = inputs.to("cuda")
labels = labels.to("cuda")
outputs = neighbour_model(inputs)
loss = F.cross_entropy(outputs, labels)
running_loss += loss.item()
num_samples += inputs.size(0)
avg_loss = running_loss / len(bootstrap_dataloader)
logging_training.info(f"Computed neighbor loss over {num_samples} data samples")
return avg_loss
def get_hash_model(self):
"""
Returns:
str: SHA256 hash of model parameters
"""
return hashlib.sha256(self.serialize_model(self.model)).hexdigest()
def set_epochs(self, epochs):
self.epochs = epochs
def serialize_model(self, model):
# From https://pytorch.org/docs/stable/notes/serialization.html
try:
buffer = io.BytesIO()
with gzip.GzipFile(fileobj=buffer, mode="wb") as f:
torch.save(model, f, pickle_protocol=pickle.HIGHEST_PROTOCOL)
serialized_data = buffer.getvalue()
buffer.close()
del buffer
return serialized_data
except Exception as e:
raise ParameterSerializeError("Error serializing model") from e
def deserialize_model(self, data):
# From https://pytorch.org/docs/stable/notes/serialization.html
try:
buffer = io.BytesIO(data)
with gzip.GzipFile(fileobj=buffer, mode="rb") as f:
params_dict = torch.load(f)
buffer.close()
del buffer
return OrderedDict(params_dict)
except Exception as e:
raise ParameterDeserializeError("Error decoding parameters") from e
def set_model_parameters(self, params, initialize=False):
try:
self.model.load_state_dict(params)
except Exception as e:
raise ParameterSettingError("Error setting parameters") from e
def get_model_parameters(self, bytes=False, initialize=False):
if bytes:
return self.serialize_model(self.model.state_dict())
return self.model.state_dict()
async def train(self):
try:
self.create_trainer()
logging.info(f"{'=' * 10} [Training] Started (check training logs for progress) {'=' * 10}")
await asyncio.to_thread(self._train_sync)
logging.info(f"{'=' * 10} [Training] Finished (check training logs for progress) {'=' * 10}")
except Exception as e:
logging_training.error(f"Error training model: {e}")
logging_training.error(traceback.format_exc())
def _train_sync(self):
try:
self._trainer.fit(self.model, self.data)
except Exception as e:
logging_training.error(f"Error in _train_sync: {e}")
tb = traceback.format_exc()
logging_training.error(f"Traceback: {tb}")
# If "raise", the exception will be managed by the main thread
async def test(self):
try:
self.create_trainer()
logging.info(f"{'=' * 10} [Testing] Started (check training logs for progress) {'=' * 10}")
await asyncio.to_thread(self._test_sync)
logging.info(f"{'=' * 10} [Testing] Finished (check training logs for progress) {'=' * 10}")
except Exception as e:
logging_training.error(f"Error testing model: {e}")
logging_training.error(traceback.format_exc())
def _test_sync(self):
try:
self._trainer.test(self.model, self.data, verbose=True)
except Exception as e:
logging_training.error(f"Error in _test_sync: {e}")
tb = traceback.format_exc()
logging_training.error(f"Traceback: {tb}")
# If "raise", the exception will be managed by the main thread
def cleanup(self):
if self._trainer is not None:
self._trainer._teardown()
del self._trainer
if self.data is not None:
self.data.teardown()
gc.collect()
torch.cuda.empty_cache()
def get_model_weight(self):
weight = self.data.model_weight
if weight is None:
raise ValueError("Model weight not set. Please call setup('fit') before requesting model weight.")
return weight
def on_round_start(self):
self.data.setup()
self._logger.log_data({"Round": self.round})
# self.reporter.enqueue_data("Round", self.round)
def on_round_end(self):
self._logger.global_step = self._logger.global_step + self._logger.local_step
self._logger.local_step = 0
self.round += 1
self.model.on_round_end()
logging.info("Flushing memory cache at the end of round...")
self.cleanup()
def on_learning_cycle_end(self):
self._logger.log_data({"Round": self.round})
|