GarbageHandler#

class GarbageHandler(interval=150, disable_auto=True, empty_cache=False)[source]#

Bases: HookBase

Control Python garbage collection (and CUDA cache) on a step cadence.

In before_train it optionally disables automatic garbage collection (disable_auto) to avoid unpredictable GC pauses during training. It resets a per-epoch counter in before_epoch and, in after_step, runs gc.collect() every interval steps (also emptying the CUDA cache when empty_cache=True). after_train performs a final collect and CUDA cache empty. Registered as GarbageHandler.

Parameters:
  • interval (int) – Run a manual gc.collect() every this many steps. Defaults to 150.

  • disable_auto (bool) – Disable Python’s automatic GC at train start so collection happens only at the controlled interval. Defaults to True.

  • empty_cache (bool) – Also call torch.cuda.empty_cache() at each interval collect. Defaults to False.

Example

Add to cfg.hooks; it takes over garbage collection so it happens on a fixed cadence rather than unpredictably mid-step:

hooks = [dict(type="GarbageHandler", interval=150)]
# → disables automatic GC in before_train and runs gc.collect() every
#   150 steps (also torch.cuda.empty_cache() when empty_cache=True);
#   final collect + cache empty in after_train
after_step()[source]#
after_train()[source]#
before_epoch()[source]#
before_train()[source]#