nvtx.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. from contextlib import contextmanager
  2. try:
  3. from torch._C import _nvtx
  4. except ImportError:
  5. class _NVTXStub:
  6. @staticmethod
  7. def _fail(*args, **kwargs):
  8. raise RuntimeError("NVTX functions not installed. Are you sure you have a CUDA build?")
  9. rangePushA = _fail
  10. rangePop = _fail
  11. markA = _fail
  12. _nvtx = _NVTXStub() # type: ignore[assignment]
  13. __all__ = ["range_push", "range_pop", "range_start", "range_end", "mark", "range"]
  14. def range_push(msg):
  15. """
  16. Pushes a range onto a stack of nested range span. Returns zero-based
  17. depth of the range that is started.
  18. Args:
  19. msg (str): ASCII message to associate with range
  20. """
  21. return _nvtx.rangePushA(msg)
  22. def range_pop():
  23. """
  24. Pops a range off of a stack of nested range spans. Returns the
  25. zero-based depth of the range that is ended.
  26. """
  27. return _nvtx.rangePop()
  28. def range_start(msg) -> int:
  29. """
  30. Mark the start of a range with string message. It returns an unique handle
  31. for this range to pass to the corresponding call to rangeEnd().
  32. A key difference between this and range_push/range_pop is that the
  33. range_start/range_end version supports range across threads (start on one
  34. thread and end on another thread).
  35. Returns: A range handle (uint64_t) that can be passed to range_end().
  36. Args:
  37. msg (str): ASCII message to associate with the range.
  38. """
  39. return _nvtx.rangeStartA(msg)
  40. def range_end(range_id) -> None:
  41. """
  42. Mark the end of a range for a given range_id.
  43. Args:
  44. range_id (int): an unique handle for the start range.
  45. """
  46. _nvtx.rangeEnd(range_id)
  47. def mark(msg):
  48. """
  49. Describe an instantaneous event that occurred at some point.
  50. Args:
  51. msg (str): ASCII message to associate with the event.
  52. """
  53. return _nvtx.markA(msg)
  54. @contextmanager
  55. def range(msg, *args, **kwargs):
  56. """
  57. Context manager / decorator that pushes an NVTX range at the beginning
  58. of its scope, and pops it at the end. If extra arguments are given,
  59. they are passed as arguments to msg.format().
  60. Args:
  61. msg (str): message to associate with the range
  62. """
  63. range_push(msg.format(*args, **kwargs))
  64. yield
  65. range_pop()