control.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. """Shared pipeline control helpers: cooperative stop/pause and memory release.
  2. These were previously copy-pasted across the training tasks and training loop.
  3. Centralizing them keeps the stop/pause semantics identical everywhere.
  4. """
  5. import gc
  6. import time
  7. from threading import Event
  8. import torch
  9. def check_control_events(
  10. stop_event: Event | None,
  11. pause_event: Event | None,
  12. ) -> None:
  13. """Cooperatively honor stop/pause events.
  14. Raises:
  15. InterruptedError: if ``stop_event`` is set (including while paused).
  16. """
  17. if stop_event is not None and stop_event.is_set():
  18. raise InterruptedError("Pipeline execution stopped by user.")
  19. while pause_event is not None and pause_event.is_set():
  20. time.sleep(0.5)
  21. if stop_event is not None and stop_event.is_set():
  22. raise InterruptedError("Pipeline execution stopped by user while paused.")
  23. def release_torch_memory(device: str) -> None:
  24. """Free Python and accelerator caches between models to limit VRAM growth."""
  25. gc.collect()
  26. if device.startswith("cuda"):
  27. torch.cuda.empty_cache()
  28. elif device.startswith("mps") and hasattr(torch, "mps"):
  29. torch.mps.empty_cache()