Shortcuts

clearml_logger#

ClearML logger and its helper handlers.

Classes

ClearMLLogger

ClearML handler to log metrics, text, model/optimizer parameters, plots during training and validation.

ClearMLSaver

Handler that saves input checkpoint as ClearML artifacts

GradsHistHandler

Helper handler to log model's gradients as histograms.

GradsScalarHandler

Helper handler to log model's gradients as scalars.

OptimizerParamsHandler

Helper handler to log optimizer parameters

OutputHandler

Helper handler to log engine's output and/or metrics

WeightsHistHandler

Helper handler to log model's weights as histograms.

WeightsScalarHandler

Helper handler to log model's weights as scalars.

class ignite.handlers.clearml_logger.ClearMLLogger(**kwargs)[source]#

ClearML handler to log metrics, text, model/optimizer parameters, plots during training and validation. Also supports model checkpoints logging and upload to the storage solution of your choice (i.e. ClearML File server, S3 bucket etc.)

pip install clearml
clearml-init
Parameters

kwargs (Any) – Keyword arguments accepted from Task.init method. All arguments are optional. If a ClearML Task has already been created, kwargs will be ignored and the current ClearML Task will be used.

Examples

from ignite.handlers.clearml_logger import *

# Create a logger

clearml_logger = ClearMLLogger(
    project_name="pytorch-ignite-integration",
    task_name="cnn-mnist"
)

# Attach the logger to the trainer to log training loss at each iteration
clearml_logger.attach_output_handler(
    trainer,
    event_name=Events.ITERATION_COMPLETED,
    tag="training",
    output_transform=lambda loss: {"loss": loss}
)

# Attach the logger to the evaluator on the training dataset and log NLL, Accuracy metrics after each epoch
# We setup `global_step_transform=global_step_from_engine(trainer)` to take the epoch
# of the `trainer` instead of `train_evaluator`.
clearml_logger.attach_output_handler(
    train_evaluator,
    event_name=Events.EPOCH_COMPLETED,
    tag="training",
    metric_names=["nll", "accuracy"],
    global_step_transform=global_step_from_engine(trainer),
)

# Attach the logger to the evaluator on the validation dataset and log NLL, Accuracy metrics after
# each epoch. We setup `global_step_transform=global_step_from_engine(trainer)` to take the epoch of the
# `trainer` instead of `evaluator`.
clearml_logger.attach_output_handler(
    evaluator,
    event_name=Events.EPOCH_COMPLETED,
    tag="validation",
    metric_names=["nll", "accuracy"],
    global_step_transform=global_step_from_engine(trainer)),
)

# Attach the logger to the trainer to log optimizer's parameters, e.g. learning rate at each iteration
clearml_logger.attach_opt_params_handler(
    trainer,
    event_name=Events.ITERATION_STARTED,
    optimizer=optimizer,
    param_name='lr'  # optional
)

# Attach the logger to the trainer to log model's weights norm after each iteration
clearml_logger.attach(
    trainer,
    event_name=Events.ITERATION_COMPLETED,
    log_handler=WeightsScalarHandler(model)
)
classmethod bypass_mode()[source]#

Returns the bypass mode state.

Note

GITHUB_ACTIONS env will automatically set bypass_mode to True unless overridden specifically with ClearMLLogger.set_bypass_mode(False). For more information, please refer to ClearML docs.

Returns

If True, clearml.Task is on offline mode, and all outside communication is skipped.

Return type

bool

get_task()[source]#

Returns the task context that the logger is reporting.

Returns

Returns the current task, equivalent to clearml.Task.current_task().

Return type

Any

classmethod set_bypass_mode(bypass)[source]#

Set clearml.Task to offline mode. Will bypass all outside communication, and will save all data and logs to a local session folder. Should only be used in “standalone mode”, when there is no access to the clearml-server.

Parameters

bypass (bool) –

If True, all outside communication is skipped. Data and logs will be stored in a local session folder. For more information, please refer to ClearML docs.

Return type

None

class ignite.handlers.clearml_logger.ClearMLSaver(logger=None, output_uri=None, dirname=None, *args, **kwargs)[source]#

Handler that saves input checkpoint as ClearML artifacts

Parameters
  • logger (Optional[ClearMLLogger]) – An instance of ClearMLLogger, ensuring a valid ClearML Task has been initialized. If not provided, and a ClearML Task has not been manually initialized, a runtime error will be raised.

  • output_uri (Optional[str]) – The default location for output models and other artifacts uploaded by ClearML. For more information, see clearml.Task.init.

  • dirname (Optional[str]) – Directory path where the checkpoint will be saved. If not provided, a temporary directory will be created.

  • args (Any) –

  • kwargs (Any) –

Examples

from ignite.handlers.clearml_logger import *
from ignite.handlers import Checkpoint

clearml_logger = ClearMLLogger(
    project_name="pytorch-ignite-integration",
    task_name="cnn-mnist"
)

to_save = {"model": model}

handler = Checkpoint(
    to_save,
    ClearMLSaver(),
    n_saved=1,
    score_function=lambda e: 123,
    score_name="acc",
    filename_prefix="best",
    global_step_transform=global_step_from_engine(trainer)
)

validation_evaluator.add_event_handler(Events.EVENT_COMPLETED, handler)
get_local_copy(filename)[source]#

Get artifact local copy.

Warning

In distributed configuration this method should be called on rank 0 process.

Parameters

filename (str) – artifact name.

Returns

a local path to a downloaded copy of the artifact

Return type

Optional[str]

remove(filename)[source]#

Method to remove saved checkpoint.

Parameters

filename (str) – filename associated with checkpoint.

Return type

None

class ignite.handlers.clearml_logger.GradsHistHandler(model, tag=None, whitelist=None)[source]#

Helper handler to log model’s gradients as histograms.

Parameters
  • model (Module) – model to log weights

  • tag (Optional[str]) – common title for all produced plots. For example, ‘generator’

  • whitelist (Optional[Union[List[str], Callable[[str, Parameter], bool]]]) – specific gradients to log. Should be list of model’s submodules or parameters names, or a callable which gets weight along with its name and determines if its gradient should be logged. Names should be fully-qualified. For more information please refer to PyTorch docs. If not given, all of model’s gradients are logged.

Examples

from ignite.handlers.clearml_logger import *

# Create a logger

clearml_logger = ClearMLLogger(
    project_name="pytorch-ignite-integration",
    task_name="cnn-mnist"
)

# Attach the logger to the trainer to log model's weights norm after each iteration
clearml_logger.attach(
    trainer,
    event_name=Events.ITERATION_COMPLETED,
    log_handler=GradsHistHandler(model)
)
from ignite.handlers.clearml_logger import *

clearml_logger = ClearMLLogger(
    project_name="pytorch-ignite-integration",
    task_name="cnn-mnist"
)

# Log gradient of `fc.bias`
clearml_logger.attach(
    trainer,
    event_name=Events.ITERATION_COMPLETED,
    log_handler=GradsHistHandler(model, whitelist=['fc.bias'])
)
from ignite.handlers.clearml_logger import *

clearml_logger = ClearMLLogger(
    project_name="pytorch-ignite-integration",
    task_name="cnn-mnist"
)

# Log gradient of weights which have shape (2, 1)
def has_shape_2_1(n, p):
    return p.shape == (2,1)

clearml_logger.attach(
    trainer,
    event_name=Events.ITERATION_COMPLETED,
    log_handler=GradsHistHandler(model, whitelist=has_shape_2_1)
)

Changed in version 0.4.9: optional argument whitelist added.

class ignite.handlers.clearml_logger.GradsScalarHandler(model, reduction=<function norm>, tag=None, whitelist=None)[source]#

Helper handler to log model’s gradients as scalars. Handler, upon construction, iterates over named parameters of the model and keep reference to ones permitted by the whitelist. Then at every call, applies reduction function to each parameter’s gradient, produces a scalar and logs it.

Parameters
  • model (Module) – model to log weights

  • reduction (Callable[[Tensor], Union[float, Tensor]]) – function to reduce parameters into scalar

  • tag (Optional[str]) – common title for all produced plots. For example, “generator”

  • whitelist (Optional[Union[List[str], Callable[[str, Parameter], bool]]]) –

    specific gradients to log. Should be list of model’s submodules or parameters names, or a callable which gets weight along with its name and determines if its gradient should be logged. Names should be fully-qualified. For more information please refer to PyTorch docs. If not given, all of model’s gradients are logged.

Examples

from ignite.handlers.clearml_logger import *

# Create a logger

clearml_logger = ClearMLLogger(
    project_name="pytorch-ignite-integration",
    task_name="cnn-mnist"
)

# Attach the logger to the trainer to log model's weights norm after each iteration
clearml_logger.attach(
    trainer,
    event_name=Events.ITERATION_COMPLETED,
    log_handler=GradsScalarHandler(model, reduction=torch.norm)
)
from ignite.handlers.clearml_logger import *

clearml_logger = ClearMLLogger(
    project_name="pytorch-ignite-integration",
    task_name="cnn-mnist"
)

# Log gradient of `base`
clearml_logger.attach(
    trainer,
    event_name=Events.ITERATION_COMPLETED,
    log_handler=GradsScalarHandler(
        model,
        reduction=torch.norm,
        whitelist=['base']
    )
)
from ignite.handlers.clearml_logger import *

clearml_logger = ClearMLLogger(
    project_name="pytorch-ignite-integration",
    task_name="cnn-mnist"
)

# Log gradient of weights which belong to a `fc` layer
def is_in_fc_layer(n, p):
    return 'fc' in n

clearml_logger.attach(
    trainer,
    event_name=Events.ITERATION_COMPLETED,
    log_handler=GradsScalarHandler(model, whitelist=is_in_fc_layer)
)

Changed in version 0.4.9: optional argument whitelist added.

class ignite.handlers.clearml_logger.OptimizerParamsHandler(optimizer, param_name='lr', tag=None)[source]#

Helper handler to log optimizer parameters

Parameters
  • optimizer (Optimizer) – torch optimizer or any object with attribute param_groups as a sequence.

  • param_name (str) – parameter name

  • tag (Optional[str]) – common title for all produced plots. For example, “generator”

Examples

from ignite.handlers.clearml_logger import *

# Create a logger

clearml_logger = ClearMLLogger(
    project_name="pytorch-ignite-integration",
    task_name="cnn-mnist"
)

# Attach the logger to the trainer to log optimizer's parameters, e.g. learning rate at each iteration
clearml_logger.attach(
    trainer,
    log_handler=OptimizerParamsHandler(optimizer),
    event_name=Events.ITERATION_STARTED
)
# or equivalently
clearml_logger.attach_opt_params_handler(
    trainer,
    event_name=Events.ITERATION_STARTED,
    optimizer=optimizer
)
class ignite.handlers.clearml_logger.OutputHandler(tag, metric_names=None, output_transform=None, global_step_transform=None, state_attributes=None)[source]#

Helper handler to log engine’s output and/or metrics

Parameters
  • tag (str) – common title for all produced plots. For example, “training”

  • metric_names (Optional[List[str]]) – list of metric names to plot or a string “all” to plot all available metrics.

  • output_transform (Optional[Callable]) – output transform function to prepare engine.state.output as a number. For example, output_transform = lambda output: output This function can also return a dictionary, e.g {“loss”: loss1, “another_loss”: loss2} to label the plot with corresponding keys.

  • global_step_transform (Optional[Callable[[Engine, Union[str, Events]], int]]) – global step transform function to output a desired global step. Input of the function is (engine, event_name). Output of function should be an integer. Default is None, global_step based on attached engine. If provided, uses function output as global_step. To setup global step from another engine, please use global_step_from_engine().

  • state_attributes (Optional[List[str]]) – list of attributes of the trainer.state to plot.

Examples

from ignite.handlers.clearml_logger import *

# Create a logger

clearml_logger = ClearMLLogger(
    project_name="pytorch-ignite-integration",
    task_name="cnn-mnist"
)

# Attach the logger to the evaluator on the validation dataset and log NLL, Accuracy metrics after
# each epoch. We setup `global_step_transform=global_step_from_engine(trainer)` to take the epoch
# of the `trainer`:
clearml_logger.attach(
    evaluator,
    log_handler=OutputHandler(
        tag="validation",
        metric_names=["nll", "accuracy"],
        global_step_transform=global_step_from_engine(trainer)
    ),
    event_name=Events.EPOCH_COMPLETED
)
# or equivalently
clearml_logger.attach_output_handler(
    evaluator,
    event_name=Events.EPOCH_COMPLETED,
    tag="validation",
    metric_names=["nll", "accuracy"],
    global_step_transform=global_step_from_engine(trainer)
)

Another example, where model is evaluated every 500 iterations:

from ignite.handlers.clearml_logger import *

@trainer.on(Events.ITERATION_COMPLETED(every=500))
def evaluate(engine):
    evaluator.run(validation_set, max_epochs=1)

# Create a logger

clearml_logger = ClearMLLogger(
    project_name="pytorch-ignite-integration",
    task_name="cnn-mnist"
)

def global_step_transform(*args, **kwargs):
    return trainer.state.iteration

# Attach the logger to the evaluator on the validation dataset and log NLL, Accuracy metrics after
# every 500 iterations. Since evaluator engine does not have access to the training iteration, we
# provide a global_step_transform to return the trainer.state.iteration for the global_step, each time
# evaluator metrics are plotted on ClearML.

clearml_logger.attach_output_handler(
    evaluator,
    event_name=Events.EPOCH_COMPLETED,
    tag="validation",
    metrics=["nll", "accuracy"],
    global_step_transform=global_step_transform
)

Another example where the State Attributes trainer.state.alpha and trainer.state.beta are also logged along with the NLL and Accuracy after each iteration:

clearml_logger.attach(
    trainer,
    log_handler=OutputHandler(
        tag="training",
        metric_names=["nll", "accuracy"],
        state_attributes=["alpha", "beta"],
    ),
    event_name=Events.ITERATION_COMPLETED
)

Example of global_step_transform

def global_step_transform(engine, event_name):
    return engine.state.get_event_attrib_value(event_name)

Changed in version 0.4.7: accepts an optional list of state_attributes

class ignite.handlers.clearml_logger.WeightsHistHandler(model, tag=None, whitelist=None)[source]#

Helper handler to log model’s weights as histograms.

Parameters
  • model (Module) – model to log weights

  • tag (Optional[str]) – common title for all produced plots. For example, ‘generator’

  • whitelist (Optional[Union[List[str], Callable[[str, Parameter], bool]]]) –

    specific weights to log. Should be list of model’s submodules or parameters names, or a callable which gets weight along with its name and determines if it should be logged. Names should be fully-qualified. For more information please refer to PyTorch docs. If not given, all of model’s weights are logged.

Examples

from ignite.handlers.clearml_logger import *

# Create a logger

clearml_logger = ClearMLLogger(
    project_name="pytorch-ignite-integration",
    task_name="cnn-mnist"
)

# Attach the logger to the trainer to log model's weights norm after each iteration
clearml_logger.attach(
    trainer,
    event_name=Events.ITERATION_COMPLETED,
    log_handler=WeightsHistHandler(model)
)
from ignite.handlers.clearml_logger import *

clearml_logger = ClearMLLogger(
    project_name="pytorch-ignite-integration",
    task_name="cnn-mnist"
)

# Log weights of `fc` layer
weights = ['fc']

# Attach the logger to the trainer to log weights norm after each iteration
clearml_logger.attach(
    trainer,
    event_name=Events.ITERATION_COMPLETED,
    log_handler=WeightsHistHandler(model, whitelist=weights)
)
from ignite.handlers.clearml_logger import *

clearml_logger = ClearMLLogger(
    project_name="pytorch-ignite-integration",
    task_name="cnn-mnist"
)

# Log weights which name include 'conv'.
weight_selector = lambda name, p: 'conv' in name

# Attach the logger to the trainer to log weights norm after each iteration
clearml_logger.attach(
    trainer,
    event_name=Events.ITERATION_COMPLETED,
    log_handler=WeightsHistHandler(model, whitelist=weight_selector)
)

Changed in version 0.4.9: optional argument whitelist added.

class ignite.handlers.clearml_logger.WeightsScalarHandler(model, reduction=<function norm>, tag=None, whitelist=None)[source]#

Helper handler to log model’s weights as scalars. Handler, upon construction, iterates over named parameters of the model and keep reference to ones permitted by whitelist. Then at every call, applies reduction function to each parameter, produces a scalar and logs it.

Parameters
  • model (Module) – model to log weights

  • reduction (Callable[[Tensor], Union[float, Tensor]]) – function to reduce parameters into scalar

  • tag (Optional[str]) – common title for all produced plots. For example, “generator”

  • whitelist (Optional[Union[List[str], Callable[[str, Parameter], bool]]]) –

    specific weights to log. Should be list of model’s submodules or parameters names, or a callable which gets weight along with its name and determines if it should be logged. Names should be fully-qualified. For more information please refer to PyTorch docs. If not given, all of model’s weights are logged.

Examples

from ignite.handlers.clearml_logger import *

# Create a logger

clearml_logger = ClearMLLogger(
    project_name="pytorch-ignite-integration",
    task_name="cnn-mnist"
)

# Attach the logger to the trainer to log model's weights norm after each iteration
clearml_logger.attach(
    trainer,
    event_name=Events.ITERATION_COMPLETED,
    log_handler=WeightsScalarHandler(model, reduction=torch.norm)
)
from ignite.handlers.clearml_logger import *

clearml_logger = ClearMLLogger(
    project_name="pytorch-ignite-integration",
    task_name="cnn-mnist"
)

# Log only `fc` weights
clearml_logger.attach(
    trainer,
    event_name=Events.ITERATION_COMPLETED,
    log_handler=WeightsScalarHandler(
        model,
        whitelist=['fc']
    )
)
from ignite.handlers.clearml_logger import *

clearml_logger = ClearMLLogger(
    project_name="pytorch-ignite-integration",
    task_name="cnn-mnist"
)

# Log weights which have `bias` in their names
def has_bias_in_name(n, p):
    return 'bias' in n

clearml_logger.attach(
    trainer,
    event_name=Events.ITERATION_COMPLETED,
    log_handler=WeightsScalarHandler(model, whitelist=has_bias_in_name)
)

Changed in version 0.4.9: optional argument whitelist added.

ignite.handlers.clearml_logger.global_step_from_engine(engine, custom_event_name=None)[source]#

Helper method to setup global_step_transform function using another engine. This can be helpful for logging trainer epoch/iteration while output handler is attached to an evaluator.

Parameters
  • engine (Engine) – engine which state is used to provide the global step

  • custom_event_name (Optional[Events]) – registered event name. Optional argument, event name to use.

Returns

global step based on provided engine

Return type

Callable