Skip to content

[Feature Request] "Removable" event handlers. #586

@asford

Description

@asford

I'm happy to open a PR for this immediately if the feature seems useful.

Ignite's event interface provides both add and remove operations however the "remove" operation requires a reference to the original event handler. This makes temporary or one-off event handlers somewhat tricky to implement.

Pytorch's existing hook interface provides a solution to this issue by returning a "RemovableHandle" handle from register_hook, holding a weakref to the target hook to support later removal.

Ignite's add_event_handler should implement a similar interface, returning a "RemovableEventHandle" rather than None. For example, in an attrs-style syntax:

@attr.s(auto_attribs=True)
class RemovableEventHandle:
    """Removable weak reference to an added event handler."""


    event_name: str
    handler: weakref.ref = attr.ib(converter=_as_weakref)
    engine: weakref.ref = attr.ib(converter=_as_weakref)

    def remove(self):
        """Remove handler from engine."""
        handler = self.handler()
        engine: Engine = self.engine()

        if handler and engine and engine.has_event_handler(handler):
            engine.remove_event_handler(handler, self.event_name)

    def __enter__(self):  # noqa: D
        return self

    def __exit__(self, type, value, tb):  # noqa: D
        self.remove()

Would support features like:

engine = Engine(process_function)

def print_epoch(engine):
    print("Epoch: {}".format(engine.state.epoch))

# Train with a temporary event handler.
with engine.add_event_handler(Events.EPOCH_COMPLETED, print_epoch):
    engine.run(dataloader, 10)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions