itwinai.loggersο
itwinai wrappers for well-known ML loggers.
A logger allows to save objects of different kinds:
Object |
Description |
|---|---|
|
Number, usually representing a ML metric of interest (e.g., loss, accuracy). |
|
PyTorch object (e.g., tensor). |
|
File on the local filesystem to be stored by the logger. |
|
Matplotlib of Plotly figure |
|
PIL image or numpy array storing an image. |
|
Hyper-parameter (e.g., learning rate, batch size, number of layers)
as a primitive Python type.
|
|
Running text (string). |
|
Python dictionary. |
|
ML model. At the moment only |
|
Best ML model. At the moment only |
|
Dataset object (e.g., objects of type |
|
WandB
watch: Hook into the torch model to collect gradients andthe topology. More info.
|
|
Flops per batch, used by |
|
Flops per batch, used by |
|
Flops per epoch, used by |
|
System metrics, used by |
|
Carbon footprint information, used
by |
|
Execution time, used by |
|
Provenance documents, used by |
- class itwinai.loggers.LogMixin[source]ο
Bases:
ABC- abstract log(item: Any | List[Any], identifier: str | List[str], kind: str = 'metric', step: int | None = None, batch_idx: int | None = None, **kwargs) None[source]ο
Log
itemwithidentifiername ofkindtype atsteptime step.- Parameters:
item (Union[Any, List[Any]]) β element to be logged (e.g., metric).
identifier (Union[str, List[str]]) β unique identifier for the element to log(e.g., name of a metric).
kind (str, optional) β type of the item to be logged. Must be one among the list of self.supported_kinds. Defaults to βmetricβ.
step (Optional[int], optional) β logging step. Defaults to None.
batch_idx (Optional[int], optional) β DataLoader batch counter (i.e., batch idx), if available. Defaults to None.
- itwinai.loggers.check_initialized(method: Callable) Callable[source]ο
Decorator for logger methods to check whether the logger was correctly initialized before calling the method.
- itwinai.loggers.check_not_initialized(method: Callable) Callable[source]ο
Decorator for
create_logger_contextmethod to prevent double initialization of a logger.
- class itwinai.loggers.Logger(savedir: Path | str = 'mllogs', log_freq: int | Literal['epoch', 'batch'] = 'epoch', log_on_workers: int | List[int] = 0, experiment_id: str | None = None, run_id: int | str | None = None)[source]ο
Bases:
LogMixinBase class for logger
- Parameters:
savedir (Union[Path, str], optional) β filesystem location where logs are stored. Defaults to βmllogsβ.
log_freq (Union[int, Literal['epoch', 'batch']], optional) β
how often should the logger fulfill calls to the log() method:
When set to βepochβ, the logger logs only if
batch_idxis not passed to thelogmethod.When an integer is given, the logger logs if
batch_idxis a multiple oflog_freq.When set to
'batch', the logger logs always.
Defaults to βepochβ.
log_on_workers (Optional[Union[int, List[int]]]) β if -1, log on all workers; if int log on worker with rank equal to log_on_workers; if List[int], log on workers which rank is in the list. Defaults to 0 (the global rank of the main worker).
- supported_kinds: Tuple[str]ο
Supported logging βkindβs.
- worker_rank: int = 0ο
Current worker global rank
- is_initialized: bool = Falseο
Flag to check whether the logger was correctly initialized
- savedir: Pathο
Location on filesystem where to store data.
- property experiment_id: str | Noneο
Return the experiment id.
- property run_id: int | str | Noneο
Return the id of the current run.
- property log_freq: int | Literal['epoch', 'batch']ο
Get
log_feq, namely how often should the logger fulfill or ignore calls to the log() method.
- start_logging(rank: int = 0)[source]ο
Start logging context.
- Parameters:
rank (int) β global rank of current process, used in distributed environments. Defaults to 0.
Example:
>>> with my_logger.start_logging(): >>> my_logger.log(123, 'value', kind='metric', step=0)
- abstract create_logger_context(rank: int = 0, **kwargs) Any[source]ο
Initializes the logger context.
- Parameters:
rank (int) β global rank of current process, used in distributed environments. Defaults to 0.
- abstract save_hyperparameters(params: Dict[str, Any]) None[source]ο
Save hyperparameters.
- Parameters:
params (Dict[str, Any]) β hyperparameters dictionary.
- serialize(obj: Any, identifier: str) str[source]ο
Serializes object to disk and returns its path.
- Parameters:
obj (Any) β item to save.
identifier (str) β identifier of the item to log (expected to be a path under
self.savedir).
- Returns:
local path of the serialized object to be logged.
- Return type:
str
- should_log(batch_idx: int | None = None) bool[source]ο
Determines whether the logger should fulfill or ignore calls to the log() method, depending on the
log_freqproperty:When
log_freqis set to βepochβ, the logger logs only ifbatch_idxis not passed to thelogmethod.When
log_freqis an integer is given, the logger logs ifbatch_idxis a multiple oflog_freq.When
log_freqis set to'batch', the logger logs always.
It also takes into account whether logging on the current worker rank is allowed by
self.log_on_workers.- Parameters:
batch_idx (Optional[int]) β the dataloader batch idx, if available. Defaults to None.
- Returns:
True if the logger should log, False otherwise.
- Return type:
bool
- class itwinai.loggers.ConsoleLogger(savedir: Path | str = 'mllogs', log_freq: int | Literal['epoch', 'batch'] = 'epoch', log_on_workers: int | List[int] = 0)[source]ο
Bases:
LoggerSimplified logger.
- Parameters:
savedir (Union[Path, str], optional) β where to store artifacts. Defaults to βmllogsβ.
log_freq (Union[int, Literal['epoch', 'batch']], optional) β determines whether the logger should fulfill or ignore calls to the log() method. See
Logger.should_logmethod for more details. Defaults to βepochβ.log_on_workers (Optional[Union[int, List[int]]]) β if -1, log on all workers; if int log on worker with rank equal to log_on_workers; if List[int], log on workers which rank is in the list. Defaults to 0 (the global rank of the main worker).
- supported_kinds: Tuple[str] = ('torch', 'artifact', 'metric')ο
Supported kinds in the
logmethod
- create_logger_context(rank: int = 0, **kwargs)[source]ο
Initializes the logger context.
- Parameters:
rank (int) β global rank of current process, used in distributed environments. Defaults to 0.
- save_hyperparameters(params: Dict[str, Any]) None[source]ο
Save hyperparameters. Do nothing.
- Parameters:
params (Dict[str, Any]) β hyperparameters dictionary.
- log(item: Any | List[Any], identifier: str | List[str], kind: str = 'metric', step: int | None = None, batch_idx: int | None = None, **kwargs) None[source]ο
Print metrics to stdout and save artifacts to the filesystem.
- Parameters:
item (Union[Any, List[Any]]) β element to be logged (e.g., metric).
identifier (Union[str, List[str]]) β unique identifier for the element to log(e.g., name of a metric).
kind (str, optional) β type of the item to be logged. Must be one among the list of
self.supported_kinds. Defaults to βmetricβ.step (Optional[int], optional) β logging step. Defaults to None.
batch_idx (Optional[int], optional) β DataLoader batch counter (i.e., batch idx), if available. Defaults to None.
kwargs β keyword arguments to pass to the logger.
- class itwinai.loggers.MLFlowLogger(savedir: Path | str = 'mllogs', experiment_name: str = 'unnamed-experiment', tracking_uri: str | None = None, run_description: str | None = None, run_name: str | None = None, log_freq: int | Literal['epoch', 'batch'] = 'epoch', log_on_workers: int | List[int] = 0)[source]ο
Bases:
LoggerAbstraction around MLFlow logger.
- Parameters:
savedir (Union[Path, str], optional) β path on local filesystem where logs are stored. Defaults to βmllogsβ.
experiment_name (str, optional) β experiment name. Defaults to
itwinai.loggers.BASE_EXP_NAME.tracking_uri (Optional[str], optional) β MLFLow tracking URI. Overrides
savedirif given. Defaults to None.run_description (Optional[str], optional) β run description. Defaults to None.
run_name (Optional[str], optional) β run name. Defaults to None.
log_freq (Union[int, Literal['epoch', 'batch']], optional) β determines whether the logger should fulfill or ignore calls to the log() method. See
Logger.should_logmethod for more details. Defaults to βepochβ.log_on_workers (Optional[Union[int, List[int]]]) β if -1, log on all workers; if int log on worker with rank equal to log_on_workers; if List[int], log on workers which rank is in the list. Defaults to 0 (the global rank of the main worker).
- supported_kinds: Tuple[str] = ('metric', 'figure', 'image', 'artifact', 'torch', 'dict', 'param', 'text', 'model', 'dataset')ο
Supported kinds in the
logmethod
- active_run: mlflow.ActiveRunο
Current MLFLow experimentβs run.
- tracking_uri: strο
- create_logger_context(rank: int = 0, **kwargs) mlflow.ActiveRun | None[source]ο
Initializes the logger context. Start MLFLow run.
- Parameters:
rank (int) β global rank of current process, used in distributed environments. Defaults to 0.
kwargs β
run_id(Optional[str]): MLFlow run ID to attach to. Defaults to None.run_name(Optional[str]): name of the MLFlow run. Defaults to None.parent_run_id(Optional[str]): parent run ID to attach to.
- Returns:
active MLFlow run.
- Return type:
mlflow.ActiveRun
- save_hyperparameters(params: Dict[str, Any]) None[source]ο
Save hyperparameters as MLFlow parameters.
- Parameters:
params (Dict[str, Any]) β hyperparameters dictionary.
- log(item: Any | List[Any], identifier: str | List[str], kind: str = 'metric', step: int | None = None, batch_idx: int | None = None, **kwargs) None[source]ο
Log with MLFlow.
- Parameters:
item (Union[Any, List[Any]]) β element to be logged (e.g., metric).
identifier (Union[str, List[str]]) β unique identifier for the element to log(e.g., name of a metric).
kind (str, optional) β type of the item to be logged. Must be one among the list of
self.supported_kinds. Defaults to βmetricβ.step (Optional[int], optional) β logging step. Defaults to None.
batch_idx (Optional[int], optional) β DataLoader batch counter (i.e., batch idx), if available. Defaults to None.
kwargs β keyword arguments to pass to the logger.
- resolve_experiment_id() str[source]ο
Sets experiment id by the experiment_name of the logger if not set. Returns the experiment id.
- property experiment_id: strο
Return the experiment id.
- class itwinai.loggers.WandBLogger(savedir: Path | str = 'mllogs', project_name: str = 'unnamed-experiment', log_freq: int | Literal['epoch', 'batch'] = 'epoch', log_on_workers: int | List[int] = 0, offline_mode: bool = False)[source]ο
Bases:
LoggerAbstraction around WandB logger.
- Parameters:
savedir (Union[Path, str], optional) β location on local filesystem where logs are stored. Defaults to βmllogsβ.
project_name (str, optional) β experiment name. Defaults to
itwinai.loggers.BASE_EXP_NAME.log_freq (Union[int, Literal['epoch', 'batch']], optional) β determines whether the logger should fulfill or ignore calls to the log() method. See
Logger.should_logmethod for more details. Defaults to βepochβ.log_on_workers (Optional[Union[int, List[int]]]) β if -1, log on all workers; if int log on worker with rank equal to log_on_workers; if List[int], log on workers which rank is in the list. Defaults to 0 (the global rank of the main worker).
offline_mode (str, optional) β Use this option if working on compute node without internet access. Saves logs locally. Defaults to βFalseβ.
- supported_kinds: Tuple[str] = ('watch', 'metric', 'figure', 'image', 'torch', 'dict', 'param', 'text')ο
Supported kinds in the
logmethod
- create_logger_context(rank: int = 0, **kwargs) None[source]ο
Initializes the logger context. Init WandB run.
- Parameters:
rank (int) β global rank of current process, used in distributed environments. Defaults to 0.
- save_hyperparameters(params: Dict[str, Any]) None[source]ο
Save hyperparameters.
- Parameters:
params (Dict[str, Any]) β hyperparameters dictionary.
- log(item: Any | List[Any], identifier: str | List[str], kind: str = 'metric', step: int | None = None, batch_idx: int | None = None, **kwargs) None[source]ο
Log with WandB. Wrapper of https://docs.wandb.ai/ref/python/log
- Parameters:
item (Union[Any, List[Any]]) β element to be logged (e.g., metric).
identifier (Union[str, List[str]]) β unique identifier for the element to log(e.g., name of a metric).
kind (str, optional) β type of the item to be logged. Must be one among the list of
self.supported_kinds. Defaults to βmetricβ.step (Optional[int], optional) β ignored by
WandBLogger.batch_idx (Optional[int], optional) β DataLoader batch counter (i.e., batch idx), if available. Defaults to None.
kwargs β keyword arguments to pass to the logger.
- class itwinai.loggers.TensorBoardLogger(savedir: Path | str = 'mllogs', log_freq: int | Literal['epoch', 'batch'] = 'epoch', framework: Literal['tensorflow', 'pytorch'] = 'pytorch', log_on_workers: int | List[int] = 0)[source]ο
Bases:
LoggerAbstraction around TensorBoard logger, both for PyTorch and TensorFlow.
- Parameters:
savedir (Union[Path, str], optional) β location on local filesystem where logs are stored. Defaults to βmllogsβ.
log_freq (Union[int, Literal['epoch', 'batch']], optional) β determines whether the logger should fulfill or ignore calls to the log() method. See
Logger.should_logmethod for more details. Defaults to βepochβ.framework (Literal['tensorflow', 'pytorch'], optional) β whether to log PyTorch or TensorFlow ML data. Defaults to βpytorchβ.
log_on_workers (Optional[Union[int, List[int]]]) β if -1, log on all workers; if int log on worker with rank equal to log_on_workers; if List[int], log on workers which rank is in the list. Defaults to 0 (the global rank of the main worker).
- Raises:
ValueError β when
frameworkis not recognized.
- supported_kinds: Tuple[str] = ('metric', 'image', 'text', 'figure', 'torch')ο
Supported kinds in the
logmethod
- create_logger_context(rank: int = 0, **kwargs) None[source]ο
Initializes the logger context. Init Tensorboard run.
- Parameters:
rank (int) β global rank of current process, used in distributed environments. Defaults to 0.
- save_hyperparameters(params: Dict[str, Any]) None[source]ο
Save hyperparameters.
- Parameters:
params (Dict[str, Any]) β hyperparameters dictionary.
- log(item: Any | List[Any], identifier: str | List[str], kind: str = 'metric', step: int | None = None, batch_idx: int | None = None, **kwargs) None[source]ο
Log with Tensorboard.
- Parameters:
item (Union[Any, List[Any]]) β element to be logged (e.g., metric).
identifier (Union[str, List[str]]) β unique identifier for the element to log(e.g., name of a metric).
kind (str, optional) β type of the item to be logged. Must be one among the list of
self.supported_kinds. Defaults to βmetricβ.step (Optional[int], optional) β logging step. Defaults to None.
batch_idx (Optional[int], optional) β DataLoader batch counter (i.e., batch idx), if available. Defaults to None.
kwargs β keyword arguments to pass to the logger.
- class itwinai.loggers.LoggersCollection(loggers: List[Logger])[source]ο
Bases:
LoggerWrapper of a set of loggers, allowing to use them simultaneously.
- Parameters:
loggers (List[Logger]) β List of itwinai loggers. Only one logger of each type is
collection. (allowed in the)
- Raises:
ValueError β when multiple loggers of the same type are passed.
- supported_kinds: Tuple[str]ο
Supported kinds are delegated to the loggers in the collection.
- should_log(batch_idx: int | None = None) bool[source]ο
Transparent method which delegates the Logger.should_log` to individual loggers. Always returns True.
- Parameters:
batch_idx (int, optional) β dataloader batch index.
None. (Defaults to)
- Returns:
always True.
- Return type:
bool
- log(item: Any | List[Any], identifier: str | List[str], kind: str = 'metric', step: int | None = None, batch_idx: int | None = None, **kwargs) None[source]ο
Log on all loggers.
- Parameters:
item (Union[Any, List[Any]]) β element to be logged (e.g., metric).
identifier (Union[str, List[str]]) β unique identifier for the element to log(e.g., name of a metric).
kind (str, optional) β type of the item to be logged. Must be one among the list of
self.supported_kinds. Defaults to βmetricβ.step (Optional[int], optional) β logging step. Defaults to None.
batch_idx (Optional[int], optional) β DataLoader batch counter (i.e., batch idx), if available. Defaults to None.
kwargs β keyword arguments to pass to the logger.
- class itwinai.loggers.Prov4MLLogger(prov_user_namespace: str = 'www.example.org', experiment_name: str = 'experiment_name', provenance_save_dir: str = 'mllogs/prov_logs', save_after_n_logs: int | None = 100, create_graph: bool | None = True, create_svg: bool | None = True, log_freq: int | Literal['epoch', 'batch'] = 'epoch', log_on_workers: int | List[int] = 0)[source]ο
Bases:
LoggerAbstraction around Prov4ML logger.
- Parameters:
prov_user_namespace (str, optional) β location to where provenance files will be uploaded. Defaults to βwww.example.orgβ.
experiment_name (str, optional) β experiment name. Defaults to βexperiment_nameβ.
provenance_save_dir (Union[Path, str], optional) β path where to store provenance files and logs. Defaults to βprovβ.
save_after_n_logs (Optional[int], optional) β how often to save logs to disk from main memory. Defaults to 100.
create_graph (Optional[bool], optional) β whether to create a provenance graph. Defaults to True.
create_svg (Optional[bool], optional) β whether to create an SVG representation of the provenance graph. Defaults to True.
log_freq (Union[int, Literal['epoch', 'batch']], optional) β determines whether the logger should fulfill or ignore calls to the log() method. See
Logger.should_logmethod for more details. Defaults to βepochβ.log_on_workers (Optional[Union[int, List[int]]]) β if -1, log on all workers; if int log on worker with rank equal to log_on_workers; if List[int], log on workers which rank is in the list. Defaults to 0 (the global rank of the main worker).
- supported_kinds: Tuple[str] = ('metric', 'flops_pb', 'flops_pe', 'system', 'carbon', 'execution_time', 'model', 'best_model', 'torch')ο
Supported kinds in the
logmethod
- create_logger_context(rank: int = 0, **kwargs) None[source]ο
Initializes the logger context.
- Parameters:
rank (int) β global rank of current process, used in distributed environments. Defaults to 0.
- save_hyperparameters(params: Dict[str, Any]) None[source]ο
Save hyperparameters.
- Parameters:
params (Dict[str, Any]) β hyperparameters dictionary.
- log(item: Any | List[Any], identifier: str | List[str], kind: str = 'metric', step: int | None = None, batch_idx: int | None = None, context: str | None = 'training', **kwargs) None[source]ο
Logs with Prov4ML.
- Parameters:
item (Union[Any, List[Any]]) β element to be logged (e.g., metric).
identifier (Union[str, List[str]]) β unique identifier for the element to log(e.g., name of a metric).
kind (str, optional) β type of the item to be logged. Must be one among the list of
self.supported_kinds. Defaults to βmetricβ.step (Optional[int], optional) β logging step. Defaults to None.
batch_idx (Optional[int], optional) β DataLoader batch counter (i.e., batch idx), if available. Defaults to None.
kwargs β keyword arguments to pass to the logger.
- class itwinai.loggers.EmptyLogger(savedir: Path | str = 'mllogs', log_freq: int | Literal['epoch'] | Literal['batch'] = 'epoch', log_on_workers: int | List[int] = 0)[source]ο
Bases:
LoggerDummy logger which can be used as a placeholder when a real logger is not available. All methods do nothing.
- create_logger_context(rank: int = 0, **kwargs)[source]ο
Initializes the logger context.
- Parameters:
rank (int) β global rank of current process, used in distributed environments. Defaults to 0.
- save_hyperparameters(params: Dict[str, Any]) None[source]ο
Save hyperparameters.
- Parameters:
params (Dict[str, Any]) β hyperparameters dictionary.
- log(item: Any | List[Any], identifier: str | List[str], kind: str = 'metric', step: int | None = None, batch_idx: int | None = None, **kwargs) None[source]ο
Log
itemwithidentifiername ofkindtype atsteptime step.- Parameters:
item (Union[Any, List[Any]]) β element to be logged (e.g., metric).
identifier (Union[str, List[str]]) β unique identifier for the element to log(e.g., name of a metric).
kind (str, optional) β type of the item to be logged. Must be one among the list of self.supported_kinds. Defaults to βmetricβ.
step (Optional[int], optional) β logging step. Defaults to None.
batch_idx (Optional[int], optional) β DataLoader batch counter (i.e., batch idx), if available. Defaults to None.
- itwinai.loggers.get_mlflow_logger(logger: Logger | None) MLFlowLogger | None[source]ο
Finds and returns the MLFlowLogger if present in the given logger.