_sanitizer.py 24 KB

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