_filelock.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. from types import TracebackType
  2. from typing_extensions import Self
  3. from filelock import FileLock as base_FileLock
  4. from torch.monitor import _WaitCounter
  5. class FileLock(base_FileLock):
  6. """
  7. This behaves like a normal file lock.
  8. However, it adds waitcounters for acquiring and releasing the filelock
  9. as well as for the critical region within it.
  10. pytorch.filelock.enter - While we're acquiring the filelock.
  11. pytorch.filelock.region - While we're holding the filelock and doing work.
  12. pytorch.filelock.exit - While we're releasing the filelock.
  13. """
  14. def __enter__(self) -> Self:
  15. self.region_counter = _WaitCounter("pytorch.filelock.region").guard()
  16. with _WaitCounter("pytorch.filelock.enter").guard():
  17. result = super().__enter__()
  18. self.region_counter.__enter__()
  19. return result
  20. def __exit__(
  21. self,
  22. exc_type: type[BaseException] | None,
  23. exc_value: BaseException | None,
  24. traceback: TracebackType | None,
  25. ) -> None:
  26. self.region_counter.__exit__()
  27. with _WaitCounter("pytorch.filelock.exit").guard():
  28. # Returns nothing per
  29. # https://github.com/tox-dev/filelock/blob/57f488ff8fdc2193572efe102408fb63cfefe4e4/src/filelock/_api.py#L379
  30. super().__exit__(exc_type, exc_value, traceback)
  31. # Returns nothing per
  32. # https://github.com/pytorch/pytorch/blob/0f6bfc58a2cfb7a5c052bea618ab62becaf5c912/torch/csrc/monitor/python_init.cpp#L315
  33. return None