fl_sim.utils#
This module contains various utilities for the fl-sim package.
fl_sim.utils.loggers#
This module contains various loggers.
- class fl_sim.utils.loggers.BaseLogger[源代码]#
-
Abstract base class of all loggers.
- epoch_end(epoch: int) None[源代码]#
Actions to be performed at the end of each epoch.
- 参数:
epoch (int) -- The number of the current epoch.
- 返回类型:
None
- epoch_start(epoch: int) None[源代码]#
Actions to be performed at the start of each epoch.
- 参数:
epoch (int) -- The number of the current epoch.
- 返回类型:
None
- abstract classmethod from_config(config: Dict[str, Any]) Any[源代码]#
Create a logger instance from a configuration.
- abstract log_metrics(client_id: int | None, metrics: Dict[str, Real | Tensor], step: int | None = None, epoch: int | None = None, part: str = 'val') None[源代码]#
Log metrics.
- 参数:
client_id (int) -- Index of the client,
Nonefor the server.metrics (dict) -- The metrics to be logged.
step (int, optional) -- The current number of (global) steps of training.
epoch (int, optional) -- The current epoch number of training.
part (str, default "val") -- The part of the training data the metrics computed from, can be
"train"or"val"or"test", etc.
- 返回类型:
None
- class fl_sim.utils.loggers.JsonLogger(algorithm: str, dataset: str, model: str, fmt: str = 'json', log_dir: str | Path | None = None, log_suffix: str | None = None, verbose: int = 1)[源代码]#
基类:
BaseLoggerLogger that logs to a JSON file, or a yaml file.
The structure is as follows for example:
- 参数:
algorithm (str) -- Used to form the prefix of the log file.
dataset (str) -- Used to form the prefix of the log file.
model (str) -- Used to form the prefix of the log file.
fmt ({"json", "yaml"}, optional) -- Format of the log file.
log_dir (str or pathlib.Path, optional) -- Directory to save the log file
log_suffix (str, optional) -- Suffix of the log file.
verbose (int, default 1) -- The verbosity level. Not used in this logger, but is kept for compatibility with other loggers.
- classmethod from_config(config: Dict[str, Any]) JsonLogger[源代码]#
Create a
JsonLoggerinstance from a configuration.- 参数:
config (dict) --
Configuration for the logger. The following keys are used:
"algorithm":str, name of the algorithm."dataset":str, name of the dataset."model":str, name of the model."fmt": {"json", "yaml"}, optional, format of the log file, default:"json"."log_dir":strorpathlib.Path, optional, directory to save the log file."log_suffix":str, optional, suffix of the log file.
- 返回:
A
JsonLoggerinstance.- 返回类型:
- log_metrics(client_id: int | None, metrics: Dict[str, Real | Tensor], step: int | None = None, epoch: int | None = None, part: str = 'val') None[源代码]#
Log metrics.
- 参数:
client_id (int) -- Index of the client,
Nonefor the server.metrics (dict) -- The metrics to be logged.
step (int, optional) -- The current number of (global) steps of training.
epoch (int, optional) -- The current epoch number of training.
part (str, default "val") -- The part of the training data the metrics computed from, can be
"train"or"val"or"test", etc.
- 返回类型:
None
- class fl_sim.utils.loggers.LoggerManager(algorithm: str, dataset: str, model: str, log_dir: str | Path | None = None, log_suffix: str | None = None, verbose: int = 1, silent: bool = False)[源代码]#
基类:
ReprMixinManager for loggers.
- 参数:
algorithm (str) -- Used to form the prefix of the log file.
dataset (str) -- Used to form the prefix of the log file.
model (str) -- Used to form the prefix of the log file.
log_dir (str or pathlib.Path, optional) -- Directory to save the log file
log_suffix (str, optional) -- Suffix of the log file.
verbose (int, default 1) -- The verbosity level.
- epoch_end(epoch: int) None[源代码]#
Actions to be performed at the end of each epoch.
- 参数:
epoch (int) -- The number of the current epoch.
- 返回类型:
None
- epoch_start(epoch: int) None[源代码]#
Actions to be performed at the start of each epoch.
- 参数:
epoch (int) -- The number of the current epoch.
- 返回类型:
None
- classmethod from_config(config: Dict[str, Any]) LoggerManager[源代码]#
Create a
LoggerManagerinstance from a configuration.- 参数:
config (dict) --
Configuration of the logger manager. The following keys are used:
"algorithm":str, algorithm name."dataset":str, dataset name."model":str, model name."log_dir":strorpathlib.Path, optional, directory to save the log files."log_suffix":str, optional, suffix of the log files."txt_logger":bool, optional, whether to add aTxtLoggerinstance."json_logger":bool, optional, whether to add aJsonLoggerinstance."fmt": {"json", "yaml"}, optional, format of the json log file, default:"json", valid when"json_logger"isTrue."verbose":int, optional, verbosity level of the logger manager,"silent":bool, optional, whether to suppress the output to the console.
- 返回:
A
LoggerManagerinstance.- 返回类型:
- log_metrics(client_id: int | None, metrics: Dict[str, Real | Tensor], step: int | None = None, epoch: int | None = None, part: str = 'val') None[源代码]#
Log a message.
- property loggers: List[BaseLogger]#
The list of loggers.
- class fl_sim.utils.loggers.TxtLogger(algorithm: str, dataset: str, model: str, log_dir: str | Path | None = None, log_suffix: str | None = None, verbose: int = 1, silent: bool = False)[源代码]#
基类:
BaseLoggerLogger that logs to a text file.
- 参数:
algorithm (str) -- Used to form the prefix of the log file.
dataset (str) -- Used to form the prefix of the log file.
model (str) -- Used to form the prefix of the log file.
log_dir (str or pathlib.Path, optional) -- Directory to save the log file. If
None, use the default log directory. If not absolute, useDEFAULT_LOG_DIR/log_dir.log_suffix (str, optional) -- Suffix of the log file.
verbose (int, default 1) -- The verbosity level.
- epoch_end(epoch: int) None[源代码]#
Actions to be performed at the end of each epoch.
- 参数:
epoch (int) -- The number of the current epoch.
- 返回类型:
None
- epoch_start(epoch: int) None[源代码]#
Actions to be performed at the start of each epoch.
- 参数:
epoch (int) -- The number of the current epoch.
- 返回类型:
None
- classmethod from_config(config: Dict[str, Any]) TxtLogger[源代码]#
Create a
TxtLoggerinstance from a configuration.
- log_metrics(client_id: int | None, metrics: Dict[str, Real | Tensor], step: int | None = None, epoch: int | None = None, part: str = 'val') None[源代码]#
Log metrics.
- 参数:
client_id (int) -- Index of the client,
Nonefor the server.metrics (dict) -- The metrics to be logged.
step (int, optional) -- The current number of (global) steps of training.
epoch (int, optional) -- The current epoch number of training.
part (str, default "val") -- The part of the training data the metrics computed from, can be
"train"or"val"or"test", etc.
- 返回类型:
None
fl_sim.utils.imports#
This module contains utilities for dynamic imports.
- fl_sim.utils.imports.load_module_from_file(file_path: str | Path) ModuleType[源代码]#
Load a module from a file.
- 参数:
file_path (str or pathlib.Path) -- The path of the file.
- 返回:
The loaded module.
- 返回类型:
fl_sim.utils.misc#
This module provides miscellaneous utilities.
- fl_sim.utils.misc.add_kwargs(func: callable, **kwargs: Any) callable[源代码]#
Add keyword arguments to a function.
This function is used to add keyword arguments to a function in order to make it compatible with other functions。
- 参数:
func (callable) -- The function to be decorated.
kwargs (dict) -- The keyword arguments to be added.
- 返回:
The decorated function, with the keyword arguments added.
- 返回类型:
callable
- fl_sim.utils.misc.aggregate_results_from_json_log(d: dict | str | Path, part: str = 'val', metric: str = 'acc') ndarray[源代码]#
Aggregate the federated results from json log.
- 参数:
d (dict or str or pathlib.Path) -- The dict of the json/yaml log, or the path to the json/yaml log file.
part (str, default "train") -- The part of the log to aggregate.
metric (str, default "acc") -- The metric to aggregate.
- 返回:
The aggregated results (curve).
- 返回类型:
备注
The parameter d should be a dict similar to the following structure:
- fl_sim.utils.misc.clear_logs(pattern: str = '*', directory: str | Path | None = None) None[源代码]#
Clear given log files in given directory.
- 参数:
pattern (str, optional) -- Pattern of log files to be cleared, by default "*" The searching will be executed by
pathlib.Path.rglob().directory (str or Path, optional) -- Directory to be searched, by default the default log directory
LOG_DIRwill be used. If the given directory is not absolute, it will be joined withLOG_DIR.
- fl_sim.utils.misc.compute_clustering_metrics(y_true: ndarray, y_pred: ndarray) Dict[str, float][源代码]#
Compute clustering metrics, including ARI, NMI, and clustering accuracy.
- fl_sim.utils.misc.compute_sparsity(model_or_tensor: Module | Tensor) float[源代码]#
Compute the sparsity of a model or tensor.
- 参数:
model_or_tensor (torch.nn.Module or torch.Tensor) -- A model or tensor.
- 返回:
The sparsity of the model or tensor.
- 返回类型:
- fl_sim.utils.misc.default_dict_to_dict(d: defaultdict | dict | list | tuple) dict | list[源代码]#
Convert default dict to dict.
- fl_sim.utils.misc.execute_cmd(cmd: str | List[str], raise_error: bool = True) Tuple[int, List[str]][源代码]#
Execute shell command using Popen.
- fl_sim.utils.misc.find_longest_common_substring(strings: Sequence[str], min_len: int | None = None, ignore: str | None = None) str[源代码]#
Find the longest common substring of a list of strings.
- fl_sim.utils.misc.get_scheduler(scheduler_name: str, optimizer: Optimizer, config: dict | None) _LRScheduler[源代码]#
Get learning rate scheduler.
- 参数:
scheduler_name (str) -- Name of the scheduler.
optimizer (torch.optim.Optimizer) -- Optimizer.
config (dict) -- Configuration of the scheduler.
- 返回:
Learning rate scheduler.
- 返回类型:
torch.optim.lr_scheduler._LRScheduler
- fl_sim.utils.misc.get_scheduler_info(scheduler_name: str) dict[源代码]#
Get information of the scheduler, including the required and optional configs.
- fl_sim.utils.misc.is_notebook() bool[源代码]#
Check if the current environment is a notebook (Jupyter or Colab).
Implementation adapted from [1].
- 参数:
None
- 返回:
Whether the code is running in a notebook
- 返回类型:
引用
- fl_sim.utils.misc.make_serializable(x: ndarray | generic | dict | list | tuple) list | dict | Number[源代码]#
Make an object serializable.
This function is used to convert all numpy arrays to list in an object, and also convert numpy data types to python data types in the object, so that it can be serialized by
json.- 参数:
x (Union[numpy.ndarray, numpy.generic, dict, list, tuple]) -- Input data, which can be numpy array (or numpy data type), or dict, list, tuple containing numpy arrays (or numpy data type).
- 返回:
Converted data.
- 返回类型:
Union[list, dict, numbers.Number]
示例
>>> import numpy as np >>> from fl_sim.utils.misc import make_serializable >>> x = np.array([1, 2, 3]) >>> make_serializable(x) [1, 2, 3] >>> x = {"a": np.array([1, 2, 3]), "b": np.array([4, 5, 6])} >>> make_serializable(x) {'a': [1, 2, 3], 'b': [4, 5, 6]} >>> x = [np.array([1, 2, 3]), np.array([4, 5, 6])] >>> make_serializable(x) [[1, 2, 3], [4, 5, 6]] >>> x = (np.array([1, 2, 3]), np.array([4, 5, 6]).mean()) >>> obj = make_serializable(x) >>> obj [[1, 2, 3], 5.0] >>> type(obj[1]), type(x[1]) (float, numpy.float64)