Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added state attributes for Neptune logger #2153

Merged
merged 5 commits into from
Aug 11, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions ignite/contrib/handlers/neptune_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,20 @@ def global_step_transform(*args, **kwargs):
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:

.. code-block:: python

npt_logger.attach_output_handler(
trainer,
event_name=Events.ITERATION_COMPLETED,
tag="training",
metrics=["nll", "accuracy"],
state_attributes=["alpha", "beta"],
)


Args:
tag: common title for all produced plots. For example, "training"
metric_names: list of metric names to plot or a string "all" to plot all available
Expand All @@ -301,16 +315,18 @@ def global_step_transform(*args, **kwargs):
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
:meth:`~ignite.contrib.handlers.neptune_logger.global_step_from_engine`.
state_attributes: list of attributes of the ``trainer.state`` to plot.

Note:

Example of `global_step_transform`:

.. code-block:: python

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

.. versionchanged:: 0.5.0
accepts an optional list of `state_attributes`
"""

def __init__(
Expand All @@ -319,8 +335,11 @@ def __init__(
metric_names: Optional[Union[str, List[str]]] = None,
output_transform: Optional[Callable] = None,
global_step_transform: Optional[Callable] = None,
state_attributes: Optional[List[str]] = None,
):
super(OutputHandler, self).__init__(tag, metric_names, output_transform, global_step_transform)
super(OutputHandler, self).__init__(
tag, metric_names, output_transform, global_step_transform, state_attributes
)

def __call__(self, engine: Engine, logger: NeptuneLogger, event_name: Union[str, Events]) -> None:

Expand Down
26 changes: 26 additions & 0 deletions tests/ignite/contrib/handlers/test_neptune_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,32 @@ def global_step_transform(*args, **kwargs):
mock_logger.log_metric.assert_has_calls([call("tag/loss", y=12345, x=10)])


def test_output_handler_state_attrs():
wrapper = OutputHandler("tag", state_attributes=["alpha", "beta", "gamma"])
mock_logger = MagicMock(spec=NeptuneLogger)
mock_logger.log_metric = MagicMock()

mock_engine = MagicMock()
mock_engine.state = State()
mock_engine.state.iteration = 5
mock_engine.state.alpha = 3.899
mock_engine.state.beta = torch.tensor(12.23)
mock_engine.state.gamma = torch.tensor([21.0, 6.0])

wrapper(mock_engine, mock_logger, Events.ITERATION_STARTED)

assert mock_logger.log_metric.call_count == 4
mock_logger.log_metric.assert_has_calls(
[
call("tag/alpha", y=3.899, x=5),
call("tag/beta", y=torch.tensor(12.23).item(), x=5),
call("tag/gamma/0", y=21.0, x=5),
call("tag/gamma/1", y=6.0, x=5),
],
any_order=True,
)


def test_weights_scalar_handler_wrong_setup():
with pytest.raises(TypeError, match="Argument model should be of type torch.nn.Module"):
WeightsScalarHandler(None)
Expand Down