ignite icon indicating copy to clipboard operation
ignite copied to clipboard

[Feature] Add reset_on_start to EarlyStopping

Open TahaZahid05 opened this issue 9 months ago • 15 comments

Motivation

Currently, the EarlyStopping handler maintains its internal state (counter and best_score) across multiple calls of engine.run(). While this is ideal for resuming training from checkpoints, it creates a friction point for users in interactive environments (e.g., Jupyter Notebooks or Google Colab).

In these settings, a user might:

  1. Run a training session that triggers early stopping.
  2. Adjust a hyperparameter in the same notebook.
  3. Call trainer.run() again using the same engine/handler instance.

Because the state is preserved, the engine immediately terminates because the counter is already at the limit. The user must manually re-instantiate the handler or manually reset the attributes, which is not intuitive for experiment-heavy workflows.

Proposed Solution

I propose adding an optional boolean parameter reset_on_start (defaulting to False) to the EarlyStopping constructor.

If set to True, the handler will attach a listener to Events.STARTED on the provided trainer. This listener calls a internal reset() method to clear self.counter and self.best_score at the start of every run.

The feature is also backwards compatible as the default is set to False which preserve existing behavior for distributed/long-running jobs where state must persist across crashes/resumes.

Example

# The handler will now automatically "refresh" every time trainer.run() is called.
handler = EarlyStopping(
    patience=10, 
    score_function=score_function, 
    trainer=trainer, 
    reset_on_start=True
)

evaluator.add_event_handler(Events.COMPLETED, handler)

TahaZahid05 avatar Feb 14 '26 05:02 TahaZahid05

Yes, this suggestion makes sense! I remember there was a discussion about that, I do not quite remember what we decided... There are other similar handlers that require a reset between runs from start. Ideally we should update the API the same way for all of them

vfdev-5 avatar Feb 14 '26 08:02 vfdev-5

Standardizing this across similar handlers would definitely improve the functionality for notebook users.

I can start by implementing it for EarlyStopping as a reference for implementation details. Then I can open a follow-up PR to bring the same functionality to other handlers.

Is this fine or would you prefer the bulk way of adding it to different handlers in the same PR?

TahaZahid05 avatar Feb 14 '26 09:02 TahaZahid05

First, we need to decide the API for all stateful handlers before implementing

vfdev-5 avatar Feb 14 '26 09:02 vfdev-5

I went through the handlers subfolder to identify all stateful handlers:

Handlers that need reset() + reset_on_start (no existing reset mechanism)

Handler File State that persists across engine.run()
EarlyStopping early_stopping.py counter, best_score
BaseParamScheduler param_scheduler.py event_index (inherited by all scheduler subclasses)
CyclicalScheduler param_scheduler.py cycle, mutated start_value/end_value/cycle_size/warmup_duration
ConcatScheduler param_scheduler.py _scheduler_index, _current_duration, sub-scheduler states
LRScheduler param_scheduler.py lr_scheduler.last_epoch
PiecewiseLinear param_scheduler.py _index
ParamGroupScheduler param_scheduler.py sub-scheduler states
ReduceLROnPlateauScheduler param_scheduler.py PyTorch scheduler internals (best, num_bad_epochs, etc.)
PiecewiseLinearStateScheduler state_param_scheduler.py _index
TimeLimit time_limit.py start_time (set at construction, not at run start)
EMAHandler ema_handler.py ema_model accumulated weights

Handlers that already have public reset() but require manual attachment

Handler File Notes
Checkpoint checkpoint.py Has reset(), user must manually call engine.add_event_handler(Events.STARTED, checkpointer.reset)

Could gain reset_on_start for consistency with the new API.

Handlers that already self-reset (no action needed)

Timer, EpochOutputStore, BasicTimeProfiler, HandlersTimeProfiler, ProgressBar, FastaiLRFinder, and FBResearchLogger already reset their state automatically via event hooks in attach(). No changes needed.

Proposed unified API

  1. Add a public reset() method to each handler in the first table, clearing internal state back to initial values.
  2. Add reset_on_start: bool = False to __init__. When True, the handler auto-attaches self.reset to Events.STARTED on the associated engine/trainer.
  3. Default False preserves backward compatibility for checkpoint-resume workflows.

For param schedulers, reset() could be added to BaseParamScheduler (resetting event_index = 0) and overridden in subclasses like CyclicalScheduler that mutate additional attributes during execution.

Let me know if this direction looks right.

TahaZahid05 avatar Feb 14 '26 23:02 TahaZahid05

Hi @vfdev-5 , just checking in to see whether the proposed API details looks good to you?

TahaZahid05 avatar Feb 19 '26 15:02 TahaZahid05

Thanks for pinging @TahaZahid05. It looks interesting, however, we should think about how these handlers would be able to get notified about trainer's STARTED event. Can you make an example with a handler that does not have trainer as attribute and also usually attached to an evaluator engine?

vfdev-5 avatar Feb 19 '26 15:02 vfdev-5

Yeah, that's a good point @vfdev-5. We can deal with this by making the reset_on_start parameter accept either a boolean value or a reference Engine (Union[bool, Engine])

This way, the user can explicitly pass the trainer engine to the handler's reset_on_start argument. This allows the handler to subscribe to the passed trainer's STARTED event, even if it is attached to the evaluator.

Example

trainer = Engine(train_step)
evaluator = Engine(validation_step)

# The handler is attached to the evaluator, 
# but listens to the trainer for resets.
handler = EarlyStopping(
    patience=10,
    score_function=score_function,
    trainer=trainer,
    reset_on_start=trainer  # <--- Link to the trainer engine
)

evaluator.add_event_handler(Events.COMPLETED, handler)

Internal Logic

def __init__(self, ..., reset_on_start: Union[bool, Engine] = False):
    self.reset_on_start = reset_on_start
    
    # Case 1: Explicit Engine passed (e.g. trainer)
    if isinstance(self.reset_on_start, Engine):
        self.reset_on_start.add_event_handler(Events.STARTED, self.reset)
        
    # Case 2: Boolean True
    # We can attach to self.trainer (if it exists) or 
    # handle it during the .attach(engine) call for other handlers.
    elif self.reset_on_start is True and hasattr(self, 'trainer'):
        self.trainer.add_event_handler(Events.STARTED, self.reset)

TahaZahid05 avatar Feb 19 '26 15:02 TahaZahid05

Thanks for details and thinking about this feature! I'm not totally sure what would like to do here and would love if we could try different things before implementing the final API and if you could drive this if would be awesome.

IMO, adding reset_on_start argument taking trainer as input does not look very neat, but possible if nothing else is better.

To recap, we should reset stateful handlers if the trainer is started from epoch 0. We have the following situations:

Handler type attached to engine has trainer as arg Notes
stateful trainer no case A1
stateful other engines no case B1
stateful trainer yes case A2
stateful other engines yes case B2
- - - -
stateless trainer no nothing to do
stateless other engines no nothing to do
stateless trainer yes nothing to do
stateless other engines yes nothing to do

I have few other ideas. We can create an interface ResetableHandler (the name can be changed) with reset method and Engine could have the arg "reset_on_event" with the default as None or event Events.STARTED (for BS should have None but to easily make the engine reset on STARTED but also configurable event we may think a bit). We make all built-in stateful handlers inherit from ResetableHandler and when it is attached to the engine it will automatically attach reset method to the reset_on_event. We should carefully make sure that cases B1 and B2 from the table are working properly. What do you think? If you can propose something better, glad to hear.

vfdev-5 avatar Feb 19 '26 17:02 vfdev-5

Thanks @vfdev-5, I liked the idea of creating an interface class. I made a prototype/proof of concept to test it out. Here's the changes I made:

  1. ResetableHandler Interface It is an abstract base class
class ResetableHandler:
    """Interface for handlers with resettable internal state."""
    def reset(self) -> None:
        raise NotImplementedError
  1. Engine.add_event_handler Extension Two new parameters (both defaults would be set to None for BC)
def add_event_handler(
    self, event_name, handler, *args,
    reset_on_event=None,    # Which event triggers reset
    reset_engine=None,      # Which engine to listen on (for cases B1/B2)
    **kwargs,
) -> RemovableEventHandle:

Logic:

  • If handler is ResetableHandler and reset_on_event is set, then auto-attach handler.reset() to that event on reset_engine (or self if not provided). We use target_engine = reset_engine or self. This allows a handler attached to an evaluator to listen to a trainer for resets.
  • TypeError if reset_on_event is used on a non-ResetableHandler
  • ValueError if reset_engine is passed without reset_on_event
  1. Refactoring in EarlyStopping
class EarlyStopping(Serializable, ResetableHandler):
    def reset(self) -> None:
        self.counter = 0
        self.best_score = None
  1. Case Coverage
Case Scenario Usage
A1/A2 Stateful, attached to trainer trainer.add_event_handler(Events.EPOCH_COMPLETED, handler, reset_on_event=Events.STARTED)
B1/B2 Stateful, attached to evaluator, reset from trainer evaluator.add_event_handler(Events.COMPLETED, handler, reset_on_event=Events.STARTED, reset_engine=trainer)

I am also adding an example for Case B incase it helps:

trainer = Engine(train_step)
evaluator = Engine(validation_step)

handler = EarlyStopping(patience=10, score_function=score_fn, trainer=trainer)

# Handler lives on the evaluator, but resets when the TRAINER starts
evaluator.add_event_handler(
    Events.COMPLETED, handler,
    reset_on_event=Events.STARTED,
    reset_engine=trainer,
)

Additionally, I also ran existing tests of EarlyStopping and Engine and it passed all cases.

The prototype mostly followed your comment as they seemed like the clean approach to me as well, I just added the reset_engine parameter to cater to B1/B2 cases. While reset_engine adds a parameter, it makes the relationship between the trainer and evaluator explicit and easy to debug. I personally think this idea is much more cleaner as the handlers are decoupled as they don't need to store a reference to an engine. Additionally, this is much easier to scale as now we can easily make other stateful handlers resettable just by inheriting the ResetableHandler and implementing the reset() method only.

TahaZahid05 avatar Feb 19 '26 20:02 TahaZahid05

Actually, I was thinking about a bit different API, here is a code showing the idea:

# Let's suppose that this code is inside ignite codebase

class ResettableHandler:
    def reset(self):
        pass


# ignite/handlers/somehandler.py
class AStatefulHandler(ResettableHandler):
    def __init__(self):
        self._state = 0

    def reset(self):
        self._state = 0

    def __call__(self, engine):
        self._state += 1


# ignite/engine.py
class Engine(...):
    def __init__(self, ..., reset_handlers_on_event: bool | Any = False):
        if reset_handlers_on_event is True:
            reset_handlers_on_event = Events.STARTED
        elif reset_handlers_on_event is not False:
            self._assert_allowed_event(reset_handlers_on_event)
        sefl.reset_handlers_on_event = reset_handlers_on_event
        ...

    def add_event_handler(self, event_name: Any, handler: Callable, *args: Any, **kwargs: Any) -> RemovableEventHandle:
        ...
        reset_handle = None
        if self.reset_handlers_on_event is not False:
            reset_handle = self._add_event_handler(self.reset_handlers_on_event, handler)
        
        return RemovableEventHandle(event_name, handler, self, reset_handle)

   def  remove_event_handler(...):
       # TODO: make sure to remove the handler from self.reset_handlers_on_event event


# Usage:

handler1 = AStatefulHandler()
handler2 = AStatefulHandler()

trainer = Engine(..., reset_handlers_on_event=True)
trainer.add_event_handler(Events.EPOCH_COMPLETED, handler1)

evaluator = Engine(...)
evaluator.add_event_handler(Events.COMPLETED, handler2)

...

What do you think?

vfdev-5 avatar Feb 19 '26 23:02 vfdev-5

This is definitely more clean @vfdev-5. However, I have two main questions regarding this approach:

  • If an engine has 5 handlers but I only want to reset 4 of them, I lose that control with a global setting. We might want to add an auto_reset=False toggle to add_event_handler to allow specific handlers to opt-out of the engine's global reset policy. This way we give the user a default setting to minimize effort, and only write code when it deviates from the default reset state.
  • For case B1/B2, the user would have to manually connect the handler to the listening engine through trainer.add_event_handler(Events.STARTED, handler.reset). This isn't necessarily a bad thing, but rather just a tradeoff: Whether we want to automate it, or keep it explicit as it is quite logic based. Just pointing it out to get better insights as to what is our preference.

TahaZahid05 avatar Feb 20 '26 01:02 TahaZahid05

Yes, you are right, that API has some missing parts. Ideally, we would like to have a simple API without too much magic (users should understand what happens and should not be surprised) and have the code behind not too complex. If we can bake something from all these ideas, it would be great

vfdev-5 avatar Feb 20 '26 13:02 vfdev-5

That makes sense. I would like to take all these ideas that we discussed, and implement and submit a PR for this. I'll make sure to keep my priorities to be that it remains simple so the end-user can understand accordingly.

TahaZahid05 avatar Feb 20 '26 13:02 TahaZahid05

@vfdev-5 I've pushed the PR (#3564) with the engine-level approach we discussed. Before you review, I'd like to raise another way we could have gone about this.

While implementing PR #3564 , I realized that Metric already solves the exact same problem of resetting state between engine runs but using a different pattern. In Metric.attach(), the handler registers its own self.started (which calls self.reset()) onto the engine's STARTED event. The Engine doesn't need to know anything about "resettable" handlers, each handler manages its own lifecycle.

This made me wonder whether we should follow the same pattern for EarlyStopping and other stateful handlers instead of modifying the Engine. Here's a comparison:


PR #3564

The Engine detects ResettableHandler instances and auto-registers their .reset().

trainer = Engine(update, reset_handlers_on_event=True)
trainer.add_event_handler(Events.EPOCH_COMPLETED, handler)

Pros:

  • One flag resets all handlers, this is ideal for HPO/sweep workflows with many handlers
  • Minimal setup for the user

Cons:

  • Adds reset_handlers_on_event to Engine.__init__ and modifies add_event_handler logic
  • Introduces a second convention alongside the existing Metric pattern

Another possible solution: Handler-level attach() (mirrors Metric)

Each handler gets an attach() method that registers itself and its own reset, just like Metric does.

handler = EarlyStopping(patience=10, score_function=score_fn, trainer=trainer)
handler.attach(evaluator, event=Events.COMPLETED,
               reset_engine=trainer, reset_event=Events.STARTED)

Pros:

  • Zero Engine changes
  • Follows the existing Metric.attach() convention

Cons:

  • Each handler has to be reset individually.
  • More boilerplate when many handlers need resetting

Both approaches solve the core problem. I'm happy to go with either direction. What do you think?

TahaZahid05 avatar Feb 21 '26 18:02 TahaZahid05

@TahaZahid05 I agree with you and I was also thinking that previously discussed approach was not that neat, IMO. Thanks for checking that from your side, I like the idea about mimicking metrics.

vfdev-5 avatar Feb 21 '26 19:02 vfdev-5