GarbageHandler#
- class GarbageHandler(interval=150, disable_auto=True, empty_cache=False)[source]#
Bases:
HookBaseControl Python garbage collection (and CUDA cache) on a step cadence.
In
before_trainit optionally disables automatic garbage collection (disable_auto) to avoid unpredictable GC pauses during training. It resets a per-epoch counter inbefore_epochand, inafter_step, runsgc.collect()everyintervalsteps (also emptying the CUDA cache whenempty_cache=True).after_trainperforms a final collect and CUDA cache empty. Registered asGarbageHandler.- Parameters:
interval (int) – Run a manual
gc.collect()every this many steps. Defaults to150.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 toFalse.
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