_sanitizer.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. # mypy: allow-untyped-defs
  2. r"""
  3. This module introduces CUDA Sanitizer, a tool for detecting synchronization errors between kernels ran on different streams.
  4. It stores information on accesses to tensors to determine if they are synchronized
  5. or not. When enabled in a python program and a possible data race is detected, a
  6. detailed warning will be printed and the program will exit.
  7. It can be enabled either by importing this module and calling
  8. :func:`enable_cuda_sanitizer()` or by exporting the ``TORCH_CUDA_SANITIZER``
  9. environment variable.
  10. """
  11. import enum
  12. import functools
  13. import inspect
  14. import io
  15. import logging
  16. import re
  17. import sys
  18. import textwrap
  19. import traceback
  20. from collections.abc import Iterator
  21. from dataclasses import dataclass, field
  22. from typing import Any, TypeVar
  23. import torch
  24. import torch.cuda._gpu_trace as gpu_trace
  25. from torch.utils import _pytree as pytree
  26. from torch.utils._python_dispatch import TorchDispatchMode
  27. aten = torch.ops.aten
  28. DEFAULT_STREAM_ID = 0
  29. TK = TypeVar("TK")
  30. TVa = TypeVar("TVa")
  31. TVb = TypeVar("TVb")
  32. DataPtr = int
  33. StreamId = int
  34. EventId = int
  35. SeqNum = int
  36. logger = logging.getLogger(__name__)
  37. # Note that this is only factories that take Tensor as input as they are
  38. # the ones we care about.
  39. FACTORY_FUNCTION_REGEX = re.compile("(new_.*|.*_like)")
  40. class AccessType(enum.Enum):
  41. READ = enum.auto()
  42. WRITE = enum.auto()
  43. def __str__(self):
  44. return "reading from" if self is AccessType.READ else "writing to"
  45. @dataclass
  46. class Access:
  47. r"""Stores information about a single access to a tensor by a kernel.
  48. Args:
  49. type: either AccessType.READ or AccessType.Write.
  50. seq_num: the sequential number of the kernel performing the access.
  51. stream: the stream id of the stream executing the kernel.
  52. operator: the schema of the launched kernel, which lists the
  53. arguments and return type.
  54. aliases: the arguments in the schema this access corresponds to.
  55. is_output: Whether the tensor was an output of the kernel.
  56. stack_trace: the stack summary object captured during access.
  57. """
  58. type: AccessType
  59. seq_num: SeqNum
  60. stream: StreamId
  61. operator: str
  62. aliases: list[str]
  63. is_output: bool
  64. stack_trace: traceback.StackSummary
  65. class SynchronizationError(Exception):
  66. """Base class for errors detected by CUDA Sanitizer."""
  67. class UnsynchronizedAccessError(SynchronizationError):
  68. """Stores information about two unsynchronized accesses to one data pointer."""
  69. def __init__(
  70. self,
  71. data_ptr: DataPtr,
  72. allocation_stack_trace: traceback.StackSummary | None,
  73. current_access: Access,
  74. previous_access: Access,
  75. ):
  76. self.data_ptr = data_ptr
  77. self.allocation_stack_trace = allocation_stack_trace
  78. self.current_access = current_access
  79. self.previous_access = previous_access
  80. def __str__(self):
  81. def format_access(access: Access):
  82. message.write(f"{access.operator}\n{access.type}")
  83. if access.aliases:
  84. message.write(" argument(s) " + ", ".join(access.aliases))
  85. if access.is_output:
  86. message.write(", and to")
  87. if access.is_output:
  88. message.write(" the output")
  89. message.write(
  90. f"\nWith stack trace:\n{''.join(access.stack_trace.format())}\n"
  91. )
  92. with io.StringIO() as message:
  93. message.write(
  94. textwrap.dedent(
  95. f"""\
  96. ============================
  97. CSAN detected a possible data race on tensor with data pointer {self.data_ptr}
  98. Access by stream {self.current_access.stream} during kernel:
  99. """
  100. )
  101. )
  102. format_access(self.current_access)
  103. message.write(
  104. f"Previous access by stream {self.previous_access.stream} during kernel:\n"
  105. )
  106. format_access(self.previous_access)
  107. if self.allocation_stack_trace:
  108. message.write(
  109. "Tensor was allocated with stack trace:\n"
  110. f"{''.join(self.allocation_stack_trace.format())}"
  111. )
  112. else:
  113. message.write("Trace for tensor allocation not found.")
  114. return message.getvalue()
  115. class CUDASanitizerErrors(Exception):
  116. """Wrapper class for errors reported by CUDA Sanitizer."""
  117. def __init__(self, errors: list[SynchronizationError]):
  118. self.errors = errors
  119. def __str__(self):
  120. return f"detected {len(self.errors)} errors"
  121. @dataclass
  122. class TensorInfo:
  123. r"""Stores information about a single tensor and recent accesses to it.
  124. Args:
  125. allocation_stack_trace: the stack summary object captured during tensor
  126. allocation. Can be ``None`` if the allocation wasn't caught by CSAN.
  127. reads: list of read accesses to the tensor that were performed since
  128. the last write.
  129. write: the last write access to the tensor.
  130. """
  131. allocation_stack_trace: traceback.StackSummary | None
  132. reads: list[Access] = field(default_factory=list)
  133. write: Access | None = None
  134. class _TensorsAccessed:
  135. def __init__(self) -> None:
  136. self.accesses: dict[DataPtr, TensorInfo] = {}
  137. def ensure_tensor_exists(self, data_ptr: DataPtr) -> None:
  138. if data_ptr not in self.accesses:
  139. logger.info(
  140. "Found tensor with pointer: %s, but no matching tensor "
  141. "allocation in the trace. Backfilling the trace now. "
  142. "Perhaps the sanitizer was enabled after some torch operations?",
  143. data_ptr,
  144. )
  145. self.create_tensor(data_ptr, None)
  146. def ensure_tensor_does_not_exist(self, data_ptr: DataPtr) -> None:
  147. if data_ptr in self.accesses:
  148. logger.info(
  149. "Found duplicate tensor allocation in the trace for tensor with "
  150. "pointer: %s. Assuming the trace for tensor deallocation "
  151. "wasn't caught and backfilling it now. "
  152. "Perhaps the sanitizer was enabled after some torch operations?",
  153. data_ptr,
  154. )
  155. self.delete_tensor(data_ptr)
  156. def create_tensor(
  157. self, data_ptr: DataPtr, stack_trace: traceback.StackSummary | None
  158. ) -> None:
  159. self.accesses[data_ptr] = TensorInfo(stack_trace)
  160. def delete_tensor(self, data_ptr: DataPtr) -> None:
  161. del self.accesses[data_ptr]
  162. def were_there_reads_since_last_write(self, data_ptr: DataPtr) -> bool:
  163. return bool(self.accesses[data_ptr].reads)
  164. def get_allocation_stack_trace(
  165. self, data_ptr: DataPtr
  166. ) -> traceback.StackSummary | None:
  167. return self.accesses[data_ptr].allocation_stack_trace
  168. def get_write(self, data_ptr: DataPtr) -> Access | None:
  169. return self.accesses[data_ptr].write
  170. def get_reads(self, data_ptr: DataPtr) -> list[Access]:
  171. return self.accesses[data_ptr].reads
  172. def add_read(self, data_ptr: DataPtr, access: Access) -> None:
  173. self.accesses[data_ptr].reads.append(access)
  174. def set_write(self, data_ptr: DataPtr, access: Access) -> None:
  175. self.accesses[data_ptr].write = access
  176. self.accesses[data_ptr].reads = []
  177. class StreamSynchronizations:
  178. def __init__(self) -> None:
  179. self.current_sync_states: dict[StreamId, dict[StreamId, SeqNum]] = {}
  180. self.recorded_sync_states: dict[EventId, dict[StreamId, SeqNum]] = {}
  181. self.host_sync_state: dict[StreamId, SeqNum] = {}
  182. self.create_stream(DEFAULT_STREAM_ID)
  183. def _ensure_stream_exists(self, stream: StreamId) -> None:
  184. if stream not in self.current_sync_states:
  185. logger.info(
  186. "Found Stream with id: %s, but no matching stream "
  187. "creation in the trace. Backfilling the trace now. "
  188. "Perhaps the sanitizer was enabled after some torch operations?",
  189. stream,
  190. )
  191. self.create_stream(stream)
  192. def _ensure_event_exists(self, event: EventId) -> None:
  193. if event not in self.recorded_sync_states:
  194. logger.info(
  195. "Found Event with id: %s, but no matching event "
  196. "creation in the trace. Backfilling the trace now. "
  197. "Perhaps the sanitizer was enabled after some torch operations?",
  198. event,
  199. )
  200. self.create_event(event)
  201. def _ensure_event_does_not_exist(self, event: EventId) -> None:
  202. if event in self.recorded_sync_states:
  203. logger.info(
  204. "Found duplicate event creation in the trace for event with "
  205. "id: %s. Assuming the trace for event deletion wasn't caught "
  206. "and backfilling it now. "
  207. "Perhaps the sanitizer was enabled after some torch operations?",
  208. event,
  209. )
  210. self.delete_event(event)
  211. def create_stream(self, stream: StreamId) -> None:
  212. if stream in self.current_sync_states:
  213. logger.info(
  214. "Found duplicate Stream creation in the trace for Stream with "
  215. "id: %s. PyTorch Streams are only created once, so this "
  216. "trace entry is ignored.",
  217. stream,
  218. )
  219. else:
  220. self.host_sync_state[stream] = 0
  221. self.current_sync_states[stream] = self.host_sync_state.copy()
  222. def create_event(self, event: EventId) -> None:
  223. self._ensure_event_does_not_exist(event)
  224. self.recorded_sync_states[event] = {}
  225. def delete_event(self, event: EventId) -> None:
  226. self._ensure_event_exists(event)
  227. del self.recorded_sync_states[event]
  228. def update_seq_num(self, stream: StreamId, seq_num: SeqNum) -> None:
  229. self._ensure_stream_exists(stream)
  230. self.current_sync_states[stream][stream] = seq_num
  231. def record_state(self, event: EventId, stream: StreamId) -> None:
  232. self._ensure_event_exists(event)
  233. self._ensure_stream_exists(stream)
  234. self.recorded_sync_states[event] = self.current_sync_states[stream].copy()
  235. def _state_wait_for_other(
  236. self, state: dict[StreamId, SeqNum], other: dict[StreamId, SeqNum]
  237. ) -> None:
  238. for stream, seq_num in other.items():
  239. state[stream] = max(state.get(stream, -1), seq_num)
  240. def stream_wait_for_event(self, stream: StreamId, event: EventId) -> None:
  241. self._ensure_stream_exists(stream)
  242. self._ensure_event_exists(event)
  243. self._state_wait_for_other(
  244. self.current_sync_states[stream], self.recorded_sync_states[event]
  245. )
  246. def all_streams_wait_for_event(self, event: EventId) -> None:
  247. self._ensure_event_exists(event)
  248. for stream in self.current_sync_states:
  249. self.stream_wait_for_event(stream, event)
  250. self._state_wait_for_other(
  251. self.host_sync_state, self.recorded_sync_states[event]
  252. )
  253. def all_streams_wait_for_stream(self, stream: StreamId) -> None:
  254. self._ensure_stream_exists(stream)
  255. for state in self.current_sync_states.values():
  256. self._state_wait_for_other(state, self.current_sync_states[stream])
  257. self._state_wait_for_other(
  258. self.host_sync_state, self.current_sync_states[stream]
  259. )
  260. def sync_all_streams(self) -> None:
  261. for stream, state in self.current_sync_states.items():
  262. self.host_sync_state[stream] = state[stream]
  263. for state in self.current_sync_states.values():
  264. self._state_wait_for_other(state, self.host_sync_state)
  265. def is_ordered_after(
  266. self, current_stream: StreamId, seq_num: SeqNum, other_stream: StreamId
  267. ) -> bool:
  268. self._ensure_stream_exists(current_stream)
  269. self._ensure_stream_exists(other_stream)
  270. return seq_num <= self.current_sync_states[current_stream].get(other_stream, -1)
  271. class EventHandler:
  272. """Analyzes CSAN trace for synchronization errors.
  273. Stores information on each stream's synchronizations with other streams as well
  274. as tensor accesses to determine whether a given kernel launch might cause a
  275. data race.
  276. """
  277. def __init__(self) -> None:
  278. self.tensors_accessed = _TensorsAccessed()
  279. self.syncs = StreamSynchronizations()
  280. self.seq_num: SeqNum = 0
  281. def _handle_kernel_launch(
  282. self,
  283. stream: StreamId,
  284. read_only: set[DataPtr],
  285. read_write: set[DataPtr],
  286. outputs: set[DataPtr],
  287. operator: str,
  288. tensor_aliases: dict[int, list[str]],
  289. ) -> list[SynchronizationError]:
  290. def check_conflict(
  291. data_ptr: DataPtr, current_access: Access, previous_access: Access | None
  292. ) -> None:
  293. if previous_access is None:
  294. return
  295. if not self.syncs.is_ordered_after(
  296. current_access.stream, previous_access.seq_num, previous_access.stream
  297. ):
  298. error_list.append(
  299. UnsynchronizedAccessError(
  300. data_ptr,
  301. self.tensors_accessed.get_allocation_stack_trace(data_ptr),
  302. current_access,
  303. previous_access,
  304. )
  305. )
  306. error_list: list[SynchronizationError] = []
  307. self.seq_num += 1
  308. self.syncs.update_seq_num(stream, self.seq_num)
  309. stack_trace = traceback.StackSummary.extract(
  310. traceback.walk_stack(inspect.currentframe()), lookup_lines=False
  311. )
  312. # The stack trace generated in this way is in the inverse order, so it must be
  313. # reversed.
  314. stack_trace.reverse()
  315. for data_ptr in read_only:
  316. self.tensors_accessed.ensure_tensor_exists(data_ptr)
  317. current_access = Access(
  318. AccessType.READ,
  319. self.seq_num,
  320. stream,
  321. operator,
  322. tensor_aliases[data_ptr],
  323. data_ptr in outputs,
  324. stack_trace,
  325. )
  326. check_conflict(
  327. data_ptr, current_access, self.tensors_accessed.get_write(data_ptr)
  328. )
  329. self.tensors_accessed.add_read(data_ptr, current_access)
  330. for data_ptr in read_write:
  331. self.tensors_accessed.ensure_tensor_exists(data_ptr)
  332. current_access = Access(
  333. AccessType.WRITE,
  334. self.seq_num,
  335. stream,
  336. operator,
  337. tensor_aliases[data_ptr],
  338. data_ptr in outputs,
  339. stack_trace,
  340. )
  341. if self.tensors_accessed.were_there_reads_since_last_write(data_ptr):
  342. for previous_access in self.tensors_accessed.get_reads(data_ptr):
  343. check_conflict(data_ptr, current_access, previous_access)
  344. else:
  345. check_conflict(
  346. data_ptr, current_access, self.tensors_accessed.get_write(data_ptr)
  347. )
  348. self.tensors_accessed.set_write(data_ptr, current_access)
  349. return error_list
  350. def _handle_event_creation(self, event: EventId) -> None:
  351. self.syncs.create_event(event)
  352. def _handle_event_deletion(self, event: EventId) -> None:
  353. self.syncs.delete_event(event)
  354. def _handle_event_record(self, event: EventId, stream: StreamId) -> None:
  355. self.syncs.record_state(event, stream)
  356. def _handle_event_wait(self, event: EventId, stream: StreamId) -> None:
  357. self.syncs.stream_wait_for_event(stream, event)
  358. def _handle_memory_allocation(self, data_ptr: DataPtr) -> None:
  359. self.tensors_accessed.ensure_tensor_does_not_exist(data_ptr)
  360. stack_trace = traceback.StackSummary.extract(
  361. traceback.walk_stack(inspect.currentframe()), lookup_lines=False
  362. )
  363. # The stack trace generated in this way is in the inverse order, so it must be
  364. # reversed.
  365. stack_trace.reverse()
  366. self.tensors_accessed.create_tensor(
  367. data_ptr,
  368. stack_trace,
  369. )
  370. def _handle_memory_deallocation(self, data_ptr: DataPtr) -> None:
  371. self.tensors_accessed.ensure_tensor_exists(data_ptr)
  372. self.tensors_accessed.delete_tensor(data_ptr)
  373. def _handle_stream_creation(self, stream: StreamId) -> None:
  374. self.syncs.create_stream(stream)
  375. def _handle_device_synchronization(self) -> None:
  376. self.syncs.sync_all_streams()
  377. def _handle_stream_synchronization(self, stream: StreamId) -> None:
  378. self.syncs.all_streams_wait_for_stream(stream)
  379. def _handle_event_synchronization(self, event: EventId) -> None:
  380. self.syncs.all_streams_wait_for_event(event)
  381. def zip_by_key(a: dict[TK, TVa], b: dict[TK, TVb]) -> Iterator[tuple[TK, TVa, TVb]]:
  382. for arg, value in a.items():
  383. if arg in b:
  384. yield arg, value, b[arg]
  385. def zip_arguments(
  386. schema: torch.FunctionSchema, args: tuple[Any, ...], kwargs: dict[str, Any]
  387. ) -> Iterator[tuple[torch.Argument, Any]]:
  388. schema_args = schema.arguments[: len(args)]
  389. schema_kwargs = {arg.name: arg for arg in schema.arguments[len(args) :]}
  390. yield from zip(schema_args, args)
  391. for _, argument, value in zip_by_key(schema_kwargs, kwargs):
  392. yield (argument, value)
  393. class ArgumentHandler:
  394. def __init__(self) -> None:
  395. self.dataptrs_read: set[DataPtr] = set()
  396. self.dataptrs_written: set[DataPtr] = set()
  397. self.tensor_aliases: dict[DataPtr, list[str]] = {}
  398. self.outputs: set[DataPtr] = set()
  399. def _handle_argument(
  400. self,
  401. value: Any,
  402. is_write: bool,
  403. metadata_only: bool,
  404. name: str | None = None,
  405. is_output: bool = False,
  406. ) -> None:
  407. if isinstance(value, torch.Tensor) and value.is_cuda:
  408. # data_ptr() is preferred, but distinguish Tensors with null data_ptr()
  409. # otherwise two empty Tensors could incorrectly match as a conflict
  410. data_ptr = value.data_ptr() if value.data_ptr() else id(value)
  411. if is_write:
  412. self.dataptrs_written.add(data_ptr)
  413. elif not metadata_only:
  414. self.dataptrs_read.add(data_ptr)
  415. self.tensor_aliases.setdefault(data_ptr, [])
  416. if name is not None:
  417. self.tensor_aliases[data_ptr].append(name)
  418. if is_output:
  419. self.outputs.add(data_ptr)
  420. def parse_inputs(
  421. self,
  422. schema: torch.FunctionSchema,
  423. args: tuple[Any, ...],
  424. kwargs: dict[str, Any],
  425. *,
  426. is_factory: bool,
  427. ) -> None:
  428. for argument, value in zip_arguments(schema, args, kwargs):
  429. is_write = argument.alias_info is not None and argument.alias_info.is_write
  430. # A change is metadata only if it is a view or a factory function that
  431. # reads only metadata
  432. metadata_only = is_factory or (
  433. argument.alias_info is not None and not argument.alias_info.is_write
  434. )
  435. pytree.tree_map_(
  436. functools.partial(
  437. self._handle_argument,
  438. is_write=is_write,
  439. name=argument.name,
  440. metadata_only=metadata_only,
  441. ),
  442. value,
  443. )
  444. def parse_outputs(
  445. self, schema: torch.FunctionSchema, outputs: Any, *, is_factory: bool
  446. ) -> None:
  447. for res, value in zip(schema.returns, (outputs,)):
  448. metadata_only = is_factory or (
  449. res.alias_info is not None and not res.alias_info.is_write
  450. )
  451. pytree.tree_map_(
  452. functools.partial(
  453. self._handle_argument,
  454. is_write=not metadata_only,
  455. is_output=True,
  456. metadata_only=metadata_only,
  457. ),
  458. value,
  459. )
  460. class CUDASanitizerDispatchMode(TorchDispatchMode):
  461. def __init__(self) -> None:
  462. self.event_handler = EventHandler()
  463. torch._C._activate_gpu_trace()
  464. gpu_trace.register_callback_for_event_creation(
  465. self.event_handler._handle_event_creation
  466. )
  467. gpu_trace.register_callback_for_event_deletion(
  468. self.event_handler._handle_event_deletion
  469. )
  470. gpu_trace.register_callback_for_event_record(
  471. self.event_handler._handle_event_record
  472. )
  473. gpu_trace.register_callback_for_event_wait(
  474. self.event_handler._handle_event_wait
  475. )
  476. gpu_trace.register_callback_for_memory_allocation(
  477. self.event_handler._handle_memory_allocation
  478. )
  479. gpu_trace.register_callback_for_memory_deallocation(
  480. self.event_handler._handle_memory_deallocation
  481. )
  482. gpu_trace.register_callback_for_stream_creation(
  483. self.event_handler._handle_stream_creation
  484. )
  485. gpu_trace.register_callback_for_device_synchronization(
  486. self.event_handler._handle_device_synchronization
  487. )
  488. gpu_trace.register_callback_for_stream_synchronization(
  489. self.event_handler._handle_stream_synchronization
  490. )
  491. gpu_trace.register_callback_for_event_synchronization(
  492. self.event_handler._handle_event_synchronization
  493. )
  494. def __torch_dispatch__(self, func, types, args=(), kwargs=None):
  495. if kwargs is None:
  496. kwargs = {}
  497. # record_stream is not a kernel dispatch, skip it
  498. if func is aten.record_stream.default:
  499. return func(*args, **kwargs)
  500. is_factory = bool(FACTORY_FUNCTION_REGEX.match(func._schema.name))
  501. argument_handler = ArgumentHandler()
  502. argument_handler.parse_inputs(func._schema, args, kwargs, is_factory=is_factory)
  503. outputs = func(*args, **kwargs)
  504. argument_handler.parse_outputs(func._schema, outputs, is_factory=is_factory)
  505. errors = self.event_handler._handle_kernel_launch(
  506. torch.cuda.current_stream().cuda_stream,
  507. argument_handler.dataptrs_read - argument_handler.dataptrs_written,
  508. argument_handler.dataptrs_written,
  509. argument_handler.outputs,
  510. func._schema,
  511. argument_handler.tensor_aliases,
  512. )
  513. if errors:
  514. for error in errors:
  515. print(error, file=sys.stderr)
  516. raise CUDASanitizerErrors(errors)
  517. return outputs
  518. class CUDASanitizer:
  519. """Manages the lifetime of a CUDASanitizer dispatch mode object.
  520. The CUDASanitizer class wraps the entering/exiting functions of the dispatch mode
  521. context manager in the enable function/destructor, respectively. This is to
  522. explicitly set the lifetime of the dispatch mode object to that of the application.
  523. This approach was deemed more elegant than using the atexit module.
  524. """
  525. def __init__(self) -> None:
  526. self.dispatch = CUDASanitizerDispatchMode()
  527. self.enabled = False
  528. def enable(self):
  529. self.dispatch.__enter__()
  530. self.enabled = True
  531. def disable(self):
  532. self.dispatch.__exit__(None, None, None)
  533. self.enabled = False
  534. def __del__(self):
  535. # Since this object lifetime is linked to the `torch.cuda._sanitizer` python
  536. # module, it often gets deleted as part of the overall `torch` module cleanup
  537. # At that time, depending on CPython version, the torch.* module might be in
  538. # different states of being already cleaned up.
  539. # Similarly other imports might already have been cleaned up so `sys` might
  540. # be already gone as well.
  541. # Skip exiting the mode if it outlived the runtime.
  542. if (sys is not None) and (not sys.is_finalizing()) and self.enabled:
  543. self.disable()
  544. def enable_cuda_sanitizer():
  545. """Enable CUDA Sanitizer.
  546. The sanitizer will begin to analyze low-level CUDA calls invoked by torch functions
  547. for synchronization errors. All data races found will be printed to the standard
  548. error output along with stack traces of suspected causes. For best results, the
  549. sanitizer should be enabled at the very beginning of the program.
  550. """
  551. cuda_sanitizer.enable()
  552. cuda_sanitizer = CUDASanitizer()