itt.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. from contextlib import contextmanager
  2. try:
  3. from torch._C import _itt
  4. except ImportError:
  5. class _ITTStub:
  6. @staticmethod
  7. def _fail(*args, **kwargs):
  8. raise RuntimeError("ITT functions not installed. Are you sure you have a ITT build?")
  9. @staticmethod
  10. def is_available():
  11. return False
  12. rangePush = _fail
  13. rangePop = _fail
  14. mark = _fail
  15. _itt = _ITTStub() # type: ignore[assignment]
  16. __all__ = ['is_available', 'range_push', 'range_pop', 'mark', 'range']
  17. def is_available():
  18. """
  19. Check if ITT feature is available or not
  20. """
  21. return _itt.is_available()
  22. def range_push(msg):
  23. """
  24. Pushes a range onto a stack of nested range span. Returns zero-based
  25. depth of the range that is started.
  26. Arguments:
  27. msg (str): ASCII message to associate with range
  28. """
  29. return _itt.rangePush(msg)
  30. def range_pop():
  31. """
  32. Pops a range off of a stack of nested range spans. Returns the
  33. zero-based depth of the range that is ended.
  34. """
  35. return _itt.rangePop()
  36. def mark(msg):
  37. """
  38. Describe an instantaneous event that occurred at some point.
  39. Arguments:
  40. msg (str): ASCII message to associate with the event.
  41. """
  42. return _itt.mark(msg)
  43. @contextmanager
  44. def range(msg, *args, **kwargs):
  45. """
  46. Context manager / decorator that pushes an ITT range at the beginning
  47. of its scope, and pops it at the end. If extra arguments are given,
  48. they are passed as arguments to msg.format().
  49. Args:
  50. msg (str): message to associate with the range
  51. """
  52. range_push(msg.format(*args, **kwargs))
  53. yield
  54. range_pop()