_memory_profiler.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203
  1. # mypy: allow-untyped-defs
  2. import collections
  3. import dataclasses
  4. import enum
  5. import itertools as it
  6. import logging
  7. from typing import (
  8. Any,
  9. cast,
  10. DefaultDict,
  11. Dict,
  12. Iterator,
  13. List,
  14. Optional,
  15. Set,
  16. Tuple,
  17. Union,
  18. )
  19. from typing_extensions import Literal
  20. import torch
  21. from torch._C import FunctionSchema
  22. from torch._C._autograd import _ProfilerResult
  23. from torch._C._profiler import (
  24. _EventType,
  25. _ExtraFields_Allocation,
  26. _ExtraFields_TorchOp,
  27. _ProfilerEvent,
  28. _TensorMetadata,
  29. RecordScope,
  30. )
  31. from torch._utils import _element_size
  32. from torch.profiler import _utils
  33. KeyAndID = Tuple["Key", int]
  34. TensorAndID = Tuple["TensorKey", int]
  35. log = logging.getLogger(__name__)
  36. class Category(enum.Enum):
  37. INPUT = enum.auto()
  38. TEMPORARY = enum.auto()
  39. ACTIVATION = enum.auto()
  40. GRADIENT = enum.auto()
  41. AUTOGRAD_DETAIL = enum.auto()
  42. PARAMETER = enum.auto()
  43. OPTIMIZER_STATE = enum.auto()
  44. _CATEGORY_TO_COLORS = {
  45. Category.PARAMETER: "darkgreen",
  46. Category.OPTIMIZER_STATE: "goldenrod",
  47. Category.INPUT: "black",
  48. Category.TEMPORARY: "mediumpurple",
  49. Category.ACTIVATION: "red",
  50. Category.GRADIENT: "mediumblue",
  51. Category.AUTOGRAD_DETAIL: "royalblue",
  52. None: "grey",
  53. }
  54. _CATEGORY_TO_INDEX = {c: i for i, c in enumerate(_CATEGORY_TO_COLORS)}
  55. class Action(enum.Enum):
  56. PREEXISTING = enum.auto()
  57. CREATE = enum.auto()
  58. INCREMENT_VERSION = enum.auto()
  59. DESTROY = enum.auto()
  60. _ACTION_TO_INDEX = {i: i.value for i in Action}
  61. @dataclasses.dataclass(eq=True, unsafe_hash=False, frozen=True)
  62. class Key:
  63. device: torch.device
  64. @dataclasses.dataclass
  65. class _Storage:
  66. """Bundle storage pointer and id.
  67. All profiling logic should use `allocation_id`, however it is useful to
  68. print storage pointers for debugging and unit tests sometimes look up
  69. values using the storage data pointer of a live Tensor."""
  70. ptr: int
  71. allocation_id: int
  72. def __repr__(self) -> str:
  73. return f"{hex(self.ptr):>18} ({self.allocation_id})"
  74. def __eq__(self, other: object) -> bool:
  75. return isinstance(other, _Storage) and self.allocation_id == other.allocation_id
  76. def __hash__(self) -> int:
  77. return hash(self.allocation_id)
  78. @dataclasses.dataclass(eq=True, unsafe_hash=True, frozen=True)
  79. class TensorKey(Key):
  80. """Hashable identifier for a storage which has been asigned an ID.
  81. A detailed description of Tensor IDs and why they are needed is given in
  82. `torch/csrc/profiler/collection.h` when `TensorID` is declared. To
  83. summarize, multiple Storage buffers can map to the same logical Tensor.
  84. This dataclass is used to refer to a concrete in-memory StorageImpl of
  85. a Tensor.
  86. """
  87. id: int
  88. storage: _Storage
  89. def __repr__(self) -> str:
  90. return f"id={self.id}: {repr(self.storage):<24} ({self.device})"
  91. def __lt__(self, other: "TensorKey") -> bool:
  92. return self._as_sortable < other._as_sortable
  93. @staticmethod
  94. def _make(
  95. tensor_id: Optional[int],
  96. storage_ptr: Optional[int],
  97. allocation_id: Optional[int],
  98. device: torch.device,
  99. ) -> Optional["TensorKey"]:
  100. if (
  101. tensor_id is not None
  102. and storage_ptr is not None
  103. and allocation_id is not None
  104. ):
  105. return TensorKey(device, tensor_id, _Storage(storage_ptr, allocation_id))
  106. return None
  107. @classmethod
  108. def from_allocation(cls, alloc: _ExtraFields_Allocation) -> Optional["TensorKey"]:
  109. return cls._make(alloc.id, alloc.ptr, alloc.allocation_id, alloc.device)
  110. @classmethod
  111. def from_tensor(cls, t: Optional[_TensorMetadata]) -> Optional["TensorKey"]:
  112. if t is not None:
  113. return cls._make(t.id, t.storage_data_ptr, t.allocation_id, t.device)
  114. return None
  115. @property
  116. def _as_sortable(self) -> Tuple[int, int, str, int]:
  117. return self.id, self.storage.allocation_id, self.device.type, self.device.index
  118. def _extract_parameters_and_gradients(
  119. node: _ProfilerEvent,
  120. ) -> Iterator[Tuple[Optional[TensorKey], Optional[TensorKey]]]:
  121. children = node.children
  122. # AccumulateGrad is used in the Autograd engine to handle gradient updates.
  123. # There are two possible cases:
  124. # 1) This is a newly created gradient Tensor. In that case there is nothing
  125. # to accumulate, so autograd simply detaches the Tensor.
  126. #
  127. # 2) There is a preexisting gradient Tensor and we need to add the newly
  128. # computed update. This is done with an in-place add (aten::add_) op.
  129. # (The underscore suffix denotes "in-place".)
  130. if (
  131. node.typed[0] == _EventType.TorchOp
  132. and node.typed[1].scope == RecordScope.BACKWARD_FUNCTION
  133. # TODO(robieta): Move away from load bearing names
  134. and node.name == "torch::autograd::AccumulateGrad"
  135. and children
  136. and children[0].typed[0] == _EventType.TorchOp
  137. and children[0].name in ("aten::detach", "aten::add_")
  138. and children[0].typed[1].inputs
  139. and isinstance(children[0].typed[1].inputs[0], _TensorMetadata)
  140. ):
  141. yield None, TensorKey.from_tensor(children[0].typed[1].inputs[0])
  142. # We directly instrument `torch.nn.Module` and `torch.optim.Optimizer`
  143. # NOTE: The values captured by the python tracer are cached; they can be
  144. # used to build up labels but do not imply that a Tensor was live at
  145. # a particular time.
  146. elif node.typed[0] == _EventType.PyCall:
  147. typed_fields = node.typed[1]
  148. assert typed_fields.module is None or typed_fields.optimizer is None
  149. if typed_fields.module is not None:
  150. for _, p, p_grad in typed_fields.module.parameters:
  151. yield TensorKey.from_tensor(p), TensorKey.from_tensor(p_grad)
  152. if typed_fields.optimizer is not None:
  153. for p, p_grad, _ in typed_fields.optimizer.parameters:
  154. yield TensorKey.from_tensor(p), TensorKey.from_tensor(p_grad)
  155. def extract_parameters(node: _ProfilerEvent) -> Iterator[TensorKey]:
  156. for p, p_grad in _extract_parameters_and_gradients(node):
  157. if p is not None:
  158. yield p
  159. def extract_gradients(
  160. node: _ProfilerEvent,
  161. ) -> Iterator[Tuple[Optional[TensorKey], TensorKey]]:
  162. for p, p_grad in _extract_parameters_and_gradients(node):
  163. if p_grad is not None:
  164. yield p, p_grad
  165. def get_scopes(event: Optional[_ProfilerEvent]) -> Tuple[RecordScope, ...]:
  166. scopes = []
  167. while event:
  168. if event.typed[0] == _EventType.TorchOp:
  169. scopes.append(event.typed[1].scope)
  170. event = event.parent
  171. return tuple(scopes)
  172. class SchemaMatcher:
  173. """Lookup operator schema based on profiled name.
  174. When profiling we record the operator's name but not the schema. However
  175. some analysis requires that information. Fortunately we can look up
  176. registered schema from the recorded name. We do not, however, record the
  177. overload and so we must compare the profiled arguments with all overloads
  178. to determine viable matches.
  179. Note: Once https://github.com/pytorch/pytorch/issues/78871 is completed
  180. this code will be obsolete.
  181. """
  182. @classmethod
  183. def inputs_are_mutable(cls, t: _ExtraFields_TorchOp) -> Tuple[Optional[bool], ...]:
  184. """Determine which inputs may have mutated based on function schema.
  185. Note that we don't need to resolve down to a single schema to perform
  186. this analysis. An input is mutable if it is mutable in any overload. In
  187. practice, however, it is overwhelmingly common to match a single
  188. overload. If we cannot find any valid schema then we must be
  189. conservative and assume all inputs are mutable.
  190. """
  191. mutable: Optional[List[bool]] = None
  192. for schema in cls.match_schemas(t):
  193. mutable = mutable or [False for _ in schema.arguments]
  194. for i, arg in enumerate(schema.arguments):
  195. mutable[i] |= getattr(arg.alias_info, "is_write", False)
  196. return tuple(mutable or (None for _ in t.inputs))
  197. @classmethod
  198. def match_schemas(cls, t: _ExtraFields_TorchOp) -> Tuple[FunctionSchema, ...]:
  199. signature = tuple(
  200. # Tensor
  201. TensorKey.from_tensor(i) if isinstance(i, _TensorMetadata)
  202. #
  203. # TensorList
  204. else [TensorKey.from_tensor(j) for j in i] if isinstance(i, list)
  205. #
  206. # Scalar and uncaptured inputs.
  207. else i
  208. for i in t.inputs
  209. )
  210. def matches(schema) -> bool:
  211. return len(schema.arguments) == len(signature) and all(
  212. cls._types_match(observed, schema_arg.type)
  213. for observed, schema_arg in zip(signature, schema.arguments)
  214. )
  215. return tuple(s for s in cls.lookup_schemas(t.name) or () if matches(s))
  216. @classmethod
  217. def _types_match(cls, observed, schema_type) -> bool:
  218. if isinstance(schema_type, torch._C.OptionalType):
  219. schema_type = schema_type.getElementType()
  220. return observed is None or cls._types_match(observed, schema_type)
  221. if isinstance(schema_type, torch._C.AnyType):
  222. return True
  223. if schema_type.isSubtypeOf(torch._C.ListType.ofTensors()):
  224. return isinstance(observed, list) and all(
  225. isinstance(i, TensorKey) for i in observed
  226. )
  227. type_map: Tuple[Tuple[Any, Union[type, Tuple[type, ...]]], ...] = (
  228. (torch._C.TensorType, TensorKey),
  229. (torch._C.NoneType, type(None)),
  230. (torch._C.BoolType, bool),
  231. (torch._C.IntType, int),
  232. (torch._C.FloatType, float),
  233. (torch._C.ComplexType, complex),
  234. (torch._C.NumberType, (bool, int, float, complex)),
  235. )
  236. for jit_type, py_types in type_map:
  237. if isinstance(schema_type, jit_type):
  238. return isinstance(observed, py_types)
  239. # Profiler only records a subset of possible argument types. If we
  240. # reach this point then the schema must call for a type that profiler
  241. # does not record. Thus, the schema can only be a match if `observed`
  242. # is also None.
  243. return observed is None
  244. @staticmethod
  245. def lookup_schemas(name: str) -> Optional[Tuple[FunctionSchema, ...]]:
  246. # TODO(robieta):
  247. # _jit_get_schemas_for_operator is quite expensive. (~100us / call)
  248. # Consider adding `functools.lru_cache` if that becomes an issue.
  249. try:
  250. # Schema lookup will throw if `name` is malformed. (For example,
  251. # schemas must be namespaced and schema lookup will fail if name
  252. # does not include "::".) We simply catch the exception and return
  253. # `None` to denote that `name` cannot be an operator name.
  254. #
  255. # Note that record_function annotations also go through this path,
  256. # so it is expected that some names will not correspond to PyTorch
  257. # operators.
  258. if "::" not in name:
  259. return None
  260. return tuple(torch._C._jit_get_schemas_for_operator(name))
  261. except RuntimeError:
  262. return None
  263. class OpTree:
  264. def __init__(self, result: _ProfilerResult) -> None:
  265. self._root_nodes = result.experimental_event_tree()
  266. self._sorted_nodes = tuple(sorted(self.dfs(), key=lambda x: x.start_time_ns))
  267. def dfs(self, *args, **kwargs) -> Iterator[_ProfilerEvent]:
  268. yield from _utils.traverse_dfs(self._root_nodes, *args, **kwargs)
  269. @property
  270. def sorted_nodes(self) -> Tuple[_ProfilerEvent, ...]:
  271. return self._sorted_nodes
  272. class SizeMap:
  273. def __init__(self, op_tree: OpTree) -> None:
  274. self._values: Dict[TensorKey, int] = {}
  275. for node in op_tree.sorted_nodes:
  276. if node.typed[0] == _EventType.TorchOp:
  277. for t in self._flat_tensor_inputs(node.typed[1]):
  278. self._update_values(t)
  279. elif node.typed[0] == _EventType.PyCall:
  280. typed_fields = node.typed[1]
  281. assert typed_fields.module is None or typed_fields.optimizer is None
  282. if typed_fields.module is not None:
  283. for _, p, p_grad in typed_fields.module.parameters:
  284. self._update_values(p)
  285. self._update_values(p_grad)
  286. if typed_fields.optimizer is not None:
  287. for p, p_grad, state in typed_fields.optimizer.parameters:
  288. self._update_values(p)
  289. self._update_values(p_grad)
  290. for _, t in state:
  291. self._update_values(t)
  292. allocations: Dict[TensorKey, int] = {}
  293. for node in op_tree.sorted_nodes:
  294. if node.typed[0] == _EventType.Allocation:
  295. alloc_fields = node.typed[1]
  296. key = TensorKey.from_allocation(alloc_fields)
  297. if key:
  298. new_size = abs(alloc_fields.alloc_size)
  299. prior_size = allocations.setdefault(key, new_size)
  300. # It is possible to resize Storage in PyTorch, however we
  301. # key on data pointer so most resizes will be treated as a
  302. # change in storage. The one corner case that cannot be
  303. # handled is `realloc` which successfully resizes the
  304. # storage. At time of writing this is not done anywhere in
  305. # the core PyTorch codebase.
  306. if prior_size != new_size:
  307. delta = f"{prior_size} vs. {new_size}"
  308. log.warning("Mismatch between allocation and free: %s", delta)
  309. self._values.update(allocations)
  310. def _update_values(self, t: Optional[_TensorMetadata]) -> None:
  311. key = TensorKey.from_tensor(t)
  312. if key is not None and t is not None and t.layout == torch.strided:
  313. # Scalars are represented as zero dim Tensors
  314. n = max(i[0] * i[1] for i in zip(t.sizes or [1], t.strides or [1]))
  315. num_bytes = n * _element_size(t.dtype)
  316. assert num_bytes >= 0, f"{num_bytes}"
  317. self._values[key] = max(self._values.get(key, 0), num_bytes)
  318. @staticmethod
  319. def _flat_tensor_inputs(op: _ExtraFields_TorchOp) -> Iterator[_TensorMetadata]:
  320. for i in op.inputs:
  321. if isinstance(i, _TensorMetadata):
  322. yield i
  323. elif isinstance(i, list):
  324. yield from i
  325. def __getitem__(self, key: TensorKey):
  326. return self._values[key]
  327. @dataclasses.dataclass()
  328. class DataFlowEdge:
  329. input_version: Optional[int] = None
  330. mutated: Optional[bool] = False
  331. @property
  332. def is_allocation(self) -> bool:
  333. return self.input_version is None
  334. @property
  335. def is_deletion(self) -> bool:
  336. return self.mutated is None
  337. class DataFlowNode:
  338. def __init__(self, event: _ProfilerEvent, graph: "DataFlowGraph") -> None:
  339. self._event = event
  340. self._graph = graph
  341. self._edges: Dict[TensorKey, DataFlowEdge] = self._determine_edges()
  342. for key, edge in self._edges.items():
  343. if edge.mutated and not edge.is_allocation:
  344. self._graph.bump(key)
  345. # Make sure the version bumping behavior matches what we expect.
  346. versions = {k: (v, self._graph.lookup(k)) for k, v in self.outputs.items()}
  347. assert all(i == j for i, j in versions.values()), f"{versions}, {self._edges}"
  348. def _determine_edges(self) -> Dict[TensorKey, DataFlowEdge]:
  349. subtree = tuple(_utils.traverse_dfs([self._event]))
  350. # Start by populating edges from op inputs and outputs.
  351. mutable_by_key: Dict[Optional[TensorKey], Set[Optional[bool]]] = {}
  352. for op in (i.typed[1] for i in subtree if i.typed[0] == _EventType.TorchOp):
  353. for op_input, mutable in zip(
  354. op.inputs, SchemaMatcher.inputs_are_mutable(op)
  355. ):
  356. # Tensor
  357. if isinstance(op_input, _TensorMetadata):
  358. key = TensorKey.from_tensor(op_input)
  359. mutable_by_key.setdefault(key, set()).add(mutable)
  360. # TensorList
  361. elif isinstance(op_input, list):
  362. for op_input_i in op_input:
  363. key = TensorKey.from_tensor(op_input_i)
  364. mutable_by_key.setdefault(key, set()).add(mutable)
  365. edges: DefaultDict[Optional[TensorKey], DataFlowEdge]
  366. edges = collections.defaultdict(DataFlowEdge)
  367. for key, mutable_set in mutable_by_key.items():
  368. if key is not None:
  369. edges[key].input_version = self._graph.lookup(key) if key else -1
  370. # We consider an op to be mutated if we encounter a schema where it
  371. # is a mutable argument OR if it is ambiguous. (We never explicitly
  372. # see it in any schema.)
  373. mutated = (True in mutable_set) or (tuple(mutable_set) == (None,))
  374. edges[key].mutated = mutated
  375. # Then handle deletions. Note that deleting a Tensor implicitly adds
  376. # it as an input edge.
  377. for i in subtree:
  378. if i.typed[0] == _EventType.Allocation and i.typed[1].alloc_size < 0:
  379. key = TensorKey.from_allocation(i.typed[1])
  380. edge = edges[key]
  381. assert key is None or edge.mutated is not None, f"Double delete: {key}"
  382. edge.mutated = None
  383. edge.input_version = self._graph.lookup(key) if key else -1
  384. # And finally handle allocations. This step must be last, because the
  385. # previous two steps optimistically add input edges.
  386. for i in subtree:
  387. if i.typed[0] == _EventType.Allocation and i.typed[1].alloc_size > 0:
  388. edges[TensorKey.from_allocation(i.typed[1])].input_version = None
  389. # We don't need to sort the inputs, but it makes debugging and unit tests nicer.
  390. return dict(sorted((k, v) for k, v in edges.items() if k is not None))
  391. @property
  392. def inputs(self) -> Dict[TensorKey, Tuple[bool, int]]:
  393. return {
  394. # MyPy can't see through `is_allocation` to know that
  395. # `v.input_version` is not None.
  396. k: (bool(v.mutated), cast(int, v.input_version))
  397. for k, v in self._edges.items()
  398. if not v.is_allocation
  399. }
  400. @property
  401. def outputs(self) -> Dict[TensorKey, int]:
  402. return {
  403. k: 0 if v.input_version is None else v.input_version + 1
  404. for k, v in self._edges.items()
  405. if (v.is_allocation and not v.is_deletion) or v.mutated
  406. }
  407. @property
  408. def intermediates(self) -> Tuple[TensorKey, ...]:
  409. return tuple(
  410. k for k, v in self._edges.items() if v.is_allocation and v.is_deletion
  411. )
  412. @property
  413. def start_time(self) -> int:
  414. return self._event.start_time_ns
  415. class DataFlowGraph:
  416. def __init__(self, op_tree: OpTree) -> None:
  417. self._op_tree = op_tree
  418. self._leaf_events = self._extract_leaf_events(op_tree)
  419. self._active_version: Dict[TensorKey, Optional[int]] = {}
  420. self._flow_nodes = [DataFlowNode(e, self) for e in self.leaf_events]
  421. self._flow_nodes.sort(key=lambda x: x.start_time)
  422. self.validate()
  423. @property
  424. def flow_nodes(self) -> Tuple[DataFlowNode, ...]:
  425. return tuple(self._flow_nodes)
  426. def validate(self):
  427. # Check that each (Tensor, version) pair has a unique creation node
  428. outputs: Set[Tuple[TensorKey, int]] = set()
  429. for node in self.flow_nodes:
  430. node_outputs = set(node.outputs.items())
  431. duplicates = outputs & node_outputs
  432. assert not duplicates, f"{node._event.name} {node._edges} {duplicates}"
  433. outputs |= node_outputs
  434. # And check that `self._nodes` forms a valid topologically sorted DAG.
  435. tensor_versions: Dict[TensorKey, int] = {}
  436. for node in self.flow_nodes:
  437. for key, (_, version) in node.inputs.items():
  438. expected = tensor_versions.get(key, 0)
  439. assert expected == version, (expected, version)
  440. for key, version in node.outputs.items():
  441. prior_version = tensor_versions.get(key, version)
  442. assert version >= prior_version, (version, prior_version)
  443. tensor_versions[key] = version
  444. @property
  445. def leaf_events(self) -> Tuple[_ProfilerEvent, ...]:
  446. return self._leaf_events
  447. @staticmethod
  448. def _extract_leaf_events(op_tree: OpTree) -> Tuple[_ProfilerEvent, ...]:
  449. """Partially traverse the op tree and extract top level ops.
  450. Consider the following code:
  451. ```
  452. with record_function("My annotation"):
  453. x.zero_()
  454. y.zero_()
  455. ```
  456. The op tree (assuming no Autograd) will look like:
  457. <Python context>
  458. TorchOp: "My annotation"
  459. TorchOp: zero_
  460. TorchOp: fill_
  461. TorchOp: zero_
  462. TorchOp: fill_
  463. The recursive structure of operator calls makes data flow unwieldy.
  464. In order to simplify analysis we would like to select the highest level
  465. ops to represent in the graph. In this case those are the `zero_` ops;
  466. the fact that `fill_` is called is an implementation detail. We also
  467. do not want to group everything under "My annotation" as this could
  468. create overly coarse bundles and lose critical semantics.
  469. To address this issue we walk over the graph and select the topmost
  470. torch ops ** which match at least one operator schema **. These form
  471. the leaves of the first pass through the op tree. (As well as any
  472. allocations or frees which do are not part of a kernel.) These events
  473. form the logical nodes in our data flow graph.
  474. """
  475. leaf_events: List[_ProfilerEvent] = []
  476. def leaf_op(e: _ProfilerEvent) -> bool:
  477. return e.typed[0] == _EventType.TorchOp and (
  478. e.typed[1].scope == RecordScope.BACKWARD_FUNCTION
  479. or bool(SchemaMatcher.match_schemas(e.typed[1]))
  480. )
  481. def children_fn(e: _ProfilerEvent):
  482. if leaf_op(e) or e.tag == _EventType.Allocation:
  483. leaf_events.append(e)
  484. return []
  485. return e.children
  486. for _ in op_tree.dfs(children_fn=children_fn):
  487. pass
  488. return tuple(sorted(leaf_events, key=lambda x: x.start_time_ns))
  489. def lookup(self, key: TensorKey) -> int:
  490. version = self._active_version.setdefault(key, 0)
  491. assert version is not None
  492. return version
  493. def bump(self, key: TensorKey) -> None:
  494. prior_version = self._active_version.get(key, None)
  495. assert prior_version is not None
  496. self._active_version[key] = prior_version + 1
  497. def delete(self, key: TensorKey) -> None:
  498. assert self._active_version.setdefault(key, 0) is not None
  499. self._active_version[key] = None
  500. @dataclasses.dataclass
  501. class CategoryElement:
  502. by_id: Optional[Category] = None
  503. by_key: Dict[TensorKey, Category] = dataclasses.field(default_factory=dict)
  504. by_version: Dict[TensorAndID, Category] = dataclasses.field(default_factory=dict)
  505. # Used by unit tests to check internals. (And consequently by
  506. # MemoryProfile.lookup) This should not be used in any other capacity.
  507. _by_id_keyset: Set[TensorKey] = dataclasses.field(default_factory=set)
  508. @dataclasses.dataclass
  509. class CategoryDict:
  510. _values: DefaultDict[int, CategoryElement] = dataclasses.field(
  511. default_factory=lambda: collections.defaultdict(CategoryElement)
  512. )
  513. def set_by_id(self, key: TensorKey, category: Category) -> None:
  514. self._values[key.id].by_id = category
  515. self._values[key.id]._by_id_keyset.add(key)
  516. def set_by_key(self, key: TensorKey, category: Category) -> None:
  517. self._values[key.id].by_key[key] = category
  518. def set_by_version(self, key: TensorKey, version: int, category: Category) -> None:
  519. self._values[key.id].by_version[(key, version)] = category
  520. def setdefault_by_version(
  521. self, key: TensorKey, version: int, category: Category
  522. ) -> None:
  523. self._values[key.id].by_version.setdefault((key, version), category)
  524. def get(self, key: Key, version: int) -> Optional[Category]:
  525. if isinstance(key, Key) and not isinstance(key, TensorKey):
  526. return None
  527. element = self._values[key.id]
  528. return (
  529. element.by_id
  530. or element.by_key.get(key, None)
  531. or element.by_version.get((key, version), None)
  532. )
  533. class MemoryProfile:
  534. def __init__(self, result: _ProfilerResult) -> None:
  535. self._op_tree = OpTree(result)
  536. self._data_flow_graph = DataFlowGraph(self._op_tree)
  537. self._size_map = SizeMap(self._op_tree)
  538. self._categories = CategoryDict()
  539. self._set_gradients_and_temporaries()
  540. self._set_parameters_using_python_tracer()
  541. self._set_inputs()
  542. self._set_parameters_using_data_flow()
  543. self._set_activations()
  544. self._set_optimizer_state()
  545. self._set_autograd_detail()
  546. @property
  547. def timeline(self) -> Tuple[Tuple[int, Action, KeyAndID, int], ...]:
  548. output: List[Tuple[int, Action, KeyAndID, int]] = []
  549. allocation_times: Dict[Tuple[TensorKey, bool], int] = {}
  550. live_unknown: Dict[Tuple[int, torch.device], Literal[True]] = {}
  551. for event in self._op_tree.dfs():
  552. if event.typed[0] == _EventType.Allocation:
  553. alloc_fields = event.typed[1]
  554. alloc_size = alloc_fields.alloc_size
  555. is_allocation = alloc_size > 0
  556. t = event.start_time_ns
  557. tkey = TensorKey.from_allocation(alloc_fields)
  558. if tkey is not None:
  559. allocation_times[(tkey, is_allocation)] = t
  560. else:
  561. key = Key(alloc_fields.device)
  562. ptr_and_device = (alloc_fields.ptr, key.device)
  563. if is_allocation:
  564. if ptr_and_device in live_unknown:
  565. output.append(
  566. (t, Action.INCREMENT_VERSION, (key, 0), alloc_size)
  567. )
  568. else:
  569. live_unknown[ptr_and_device] = True
  570. output.append((t, Action.CREATE, (key, 0), alloc_size))
  571. else:
  572. output.append((t, Action.DESTROY, (key, 0), -alloc_size))
  573. if not live_unknown.pop(ptr_and_device, False):
  574. output.append(
  575. (-1, Action.PREEXISTING, (key, 0), -alloc_size)
  576. )
  577. snapshot = self._category_snapshot()
  578. last_version = dict(sorted(snapshot.keys()))
  579. events: List[Tuple[int, Action, TensorAndID]] = [
  580. (-1, Action.PREEXISTING, (key, version))
  581. for key, version in snapshot.keys()
  582. if (key, True) not in allocation_times and version == 0
  583. ]
  584. for node in self._data_flow_graph.flow_nodes:
  585. for key, edge in node._edges.items():
  586. if edge.is_allocation:
  587. t = allocation_times[(key, True)]
  588. events.append((t, Action.CREATE, (key, 0)))
  589. elif edge.mutated:
  590. t = node._event.start_time_ns
  591. version = edge.input_version
  592. assert version is not None
  593. events.append((t, Action.INCREMENT_VERSION, (key, version)))
  594. if edge.is_deletion:
  595. t = allocation_times[(key, False)]
  596. events.append((t, Action.DESTROY, (key, last_version[key])))
  597. output.extend(
  598. (time, action, (key, version), self._size_map[key])
  599. for time, action, (key, version) in events
  600. )
  601. output.sort(key=lambda x: (x[0], x[1].value))
  602. return tuple(output)
  603. def _is_gradient(self, *args, **kwargs) -> bool:
  604. return self._categories.get(*args, **kwargs) == Category.GRADIENT
  605. def _category_snapshot(self) -> Dict[TensorAndID, Optional[Category]]:
  606. all_tensor_versions: Set[TensorAndID] = set()
  607. for node in self._data_flow_graph.flow_nodes:
  608. all_tensor_versions.update(((k, v) for k, (_, v) in node.inputs.items()))
  609. all_tensor_versions.update((key, 0) for key in node.intermediates)
  610. all_tensor_versions.update(node.outputs.items())
  611. for i in self._categories._values.values():
  612. all_tensor_versions.update((key, 0) for key in i._by_id_keyset)
  613. return {
  614. (key, version): self._categories.get(key, version)
  615. for key, version in sorted(all_tensor_versions)
  616. }
  617. def _any_version_depends_on_gradient(self) -> Set[int]:
  618. """Extract IDs of Tensors which depend or will depend on a gradient.
  619. Note that this weakened definition of "depends" requires us to loop
  620. over the data flow graph multiple times because it allows dependency
  621. information to flow backward through edges and removes the guarantee
  622. that nodes are topologically sorted. (Or indeed, even that a valid
  623. topological order exists.) Put another way, we have converted an
  624. acyclic data flow graph into a cyclic graph and we are attempting to
  625. partition cycles involving a gradient from the rest of the graph.
  626. """
  627. depends_on_gradient: Set[int] = set()
  628. while True:
  629. start_size = len(depends_on_gradient)
  630. for node in self._data_flow_graph.flow_nodes:
  631. ids = tuple(
  632. key.id
  633. for key, (_, version) in node.inputs.items()
  634. if self._categories.get(key, version)
  635. in (Category.GRADIENT, Category.PARAMETER)
  636. or key.id in depends_on_gradient
  637. )
  638. if ids:
  639. depends_on_gradient.update(ids)
  640. depends_on_gradient.update(key.id for key in node.outputs)
  641. # We are guaranteed to exit because there is a finite set of
  642. # TensorAndID pairs. In practice we do not expect to loop more than
  643. # three times: once to identify the core parameter update loop,
  644. # once to fold the first step into that loop, and a third time
  645. # where no new elements are added.
  646. if len(depends_on_gradient) == start_size:
  647. return depends_on_gradient
  648. def _set_gradients_and_temporaries(self) -> None:
  649. """Mark Tensors which are unambiguous and simple to reason about."""
  650. # Gradients are straightforward to detect. We directly check the
  651. # `.grad` property in the Python tracer, and we can detect any new
  652. # gradient Tensors from `AccumulateGrad` ops.
  653. for event in self._op_tree.dfs():
  654. for _, p_grad in extract_gradients(event):
  655. self._categories.set_by_id(p_grad, Category.GRADIENT)
  656. # Similarly, temporary Tensors are easy to identify and are useful to
  657. # flag since they can make memory use "spikier" than one would
  658. # otherwise expect.
  659. for node in self._data_flow_graph.flow_nodes:
  660. for i in node.intermediates:
  661. self._categories.set_by_key(i, Category.TEMPORARY)
  662. def _set_parameters_using_python_tracer(self) -> None:
  663. for event in self._op_tree.dfs():
  664. for p in extract_parameters(event):
  665. if p is not None:
  666. self._categories.set_by_id(p, Category.PARAMETER)
  667. def _set_inputs(self) -> None:
  668. """Mark inputs based on which Tensors are updated using gradients.
  669. The process for differentiating between inputs and activations is more
  670. involved. Most Tensors in a training loop depend on at least one
  671. gradient: parameters depend on them through updates, and activations
  672. and optimizer state depend on them transitively through parameters.
  673. Critically, we do not need to know which Tensors are parameters to
  674. apply this method; we can simply walk the data flow graph to build the
  675. set of all values which depend on a gradient and then obtain the set
  676. of inputs from the conjugate set.
  677. There is, however, one hiccup. The first time we see a parameter is
  678. generally on the forward pass of the first step. We know from
  679. inspection of the data flow graph that v1 of that Tensor depends on
  680. a gradient (provided we profile an optimizer step), but not v0. To
  681. address this problem we weaken the definition of "depends on a
  682. gradient" to "any version of this Tensor depends on a gradient",
  683. which in turn strengthens the criteria for the input set enough to
  684. filter the activations in the forward pass of the first step."""
  685. # All of this analysis is predicated on using at least one training
  686. # step (or parameters from the python tracer) to partition the graph.
  687. # Absent that we cannot determine which Tensors are inputs and which
  688. # ones are part of the model.
  689. depends_on_gradient = self._any_version_depends_on_gradient()
  690. # We only want to annotate Tensors which actually contribute to the
  691. # model calculation.
  692. produces_gradient: Set[TensorAndID] = set()
  693. for node in reversed(self._data_flow_graph.flow_nodes):
  694. tensors = {(key, version) for key, (_, version) in node.inputs.items()}
  695. tensors |= node.outputs.items()
  696. if any(
  697. self._categories.get(*i) in (Category.GRADIENT, Category.PARAMETER)
  698. or i in produces_gradient
  699. for i in tensors
  700. ):
  701. produces_gradient |= tensors
  702. # Don't include Tensors created in the backward pass, as these are
  703. # generally Autograd implementation details rather than proper inputs.
  704. input_candidates = produces_gradient.copy()
  705. for node in self._data_flow_graph.flow_nodes:
  706. if RecordScope.BACKWARD_FUNCTION in get_scopes(node._event):
  707. input_candidates -= set(node.outputs.items())
  708. for key, version in input_candidates:
  709. if key.id not in depends_on_gradient:
  710. self._categories.setdefault_by_version(key, version, Category.INPUT)
  711. def _set_parameters_using_data_flow(self) -> None:
  712. """Deduce which Tensors are parameters.
  713. Consider the following code for the step of SGD with momentum
  714. (nesterov=False), where `d_p` is the gradient of `param` and `buf` is
  715. the momentum buffer.
  716. ```
  717. buf.mul_(momentum).add_(d_p, alpha=1 - dampening)
  718. d_p = buf
  719. param.add_(d_p, alpha=-lr)
  720. ```
  721. Both `param` and `buf` take a gradient and perform an in-place update.
  722. The python tracer will inspect calls to `nn.Module.forward` and
  723. `optim.Optimizer.step` to extract parameter and optimizer state
  724. respectively (including parameters), so this is generally a non-issue.
  725. However as a fallback we can also exploit several properties of
  726. parameters to distinguish them from other model state.
  727. First, they are directly used in the forward pass. (At this point we
  728. haven't established which parts of the graph correspond to the forward
  729. pass but we can deduce enough to suffice.) Some mutable state such as
  730. batch norm moving averages also contribute to the forward pass, but
  731. optimizer state does not.
  732. Second, a parameter is by definition used to compute at least one
  733. gradient and depends on at least one gradient.
  734. """
  735. snapshot = self._category_snapshot()
  736. # Determine which Tensors might be parameters based on forward pass
  737. # data flow. Note this these are only candidates; we filter nodes that
  738. # we know are part of the backward pass but that doesn't guarantee that
  739. # they are part of the forward pass.
  740. candidate_parameters: Set[TensorAndID] = set()
  741. candidate_fwd_tensors: Set[TensorAndID] = {
  742. i for i, category in snapshot.items() if category == Category.INPUT
  743. }
  744. for node in self._data_flow_graph.flow_nodes:
  745. inputs = {(key, value) for key, (_, value) in node.inputs.items()}
  746. if (
  747. # Don't check nodes in the backward pass.
  748. RecordScope.BACKWARD_FUNCTION not in get_scopes(node._event)
  749. and not any(self._is_gradient(*i) for i in inputs)
  750. and not any(self._is_gradient(*i) for i in node.outputs.items())
  751. #
  752. # and only check nodes which depend on an input.
  753. and candidate_fwd_tensors.intersection(inputs)
  754. ):
  755. candidate_fwd_tensors |= node.outputs.items()
  756. candidate_parameters |= inputs.difference(candidate_fwd_tensors)
  757. # Require that each parameter eventually contributes to the value of a gradient
  758. used_for_gradient: Set[TensorAndID] = set()
  759. for node in reversed(self._data_flow_graph.flow_nodes):
  760. if any(
  761. self._is_gradient(*i) or i in used_for_gradient
  762. for i in node.outputs.items()
  763. ):
  764. used_for_gradient.update(
  765. (key, version) for key, (_, version) in node.inputs.items()
  766. )
  767. candidate_parameters.intersection_update(used_for_gradient)
  768. # and depends on a gradient.
  769. parameter_keys = {key.id for key, _ in candidate_parameters}
  770. parameter_keys &= self._any_version_depends_on_gradient()
  771. for key, _ in snapshot.keys():
  772. if key.id in parameter_keys:
  773. self._categories.set_by_id(key, Category.PARAMETER)
  774. def _set_activations(self) -> None:
  775. """Flood the graph to identify activations."""
  776. required = {Category.INPUT, Category.ACTIVATION}
  777. also_allowed = {Category.PARAMETER, Category.TEMPORARY}
  778. for node in self._data_flow_graph.flow_nodes:
  779. inputs = {(key, value) for key, (_, value) in node.inputs.items()}
  780. input_categories = {self._categories.get(*i) for i in inputs}
  781. if (
  782. (input_categories & required)
  783. and not (input_categories - (required | also_allowed))
  784. #
  785. # Stop filling when we reach the backward pass.
  786. and RecordScope.BACKWARD_FUNCTION not in get_scopes(node._event)
  787. ):
  788. for i in node.outputs.items():
  789. self._categories.setdefault_by_version(*i, Category.ACTIVATION)
  790. def _set_optimizer_state(self) -> None:
  791. for event in self._op_tree.dfs():
  792. if event.typed[0] == _EventType.PyCall and event.typed[1].optimizer:
  793. parameters = event.typed[1].optimizer.parameters
  794. for _, t in it.chain(*[state for _, _, state in parameters]):
  795. key = TensorKey.from_tensor(t)
  796. if key is not None:
  797. self._categories.set_by_id(key, Category.OPTIMIZER_STATE)
  798. def _set_autograd_detail(self):
  799. prior = {None, Category.AUTOGRAD_DETAIL}
  800. for node in self._data_flow_graph.flow_nodes:
  801. if RecordScope.BACKWARD_FUNCTION in get_scopes(node._event):
  802. for key, version in node.outputs.items():
  803. if version == 0 or self._categories.get(key, version - 1) in prior:
  804. self._categories.setdefault_by_version(
  805. key, version, Category.AUTOGRAD_DETAIL
  806. )
  807. class MemoryProfileTimeline:
  808. def __init__(self, memory_profile):
  809. """The minimum representation of the memory profile timeline
  810. includes the memory timeline and categories. The timeline
  811. consists of [timestamp, action, (TensorKey, version), numbytes]
  812. elements, to denote any actions (pre-existing, create, destroy,
  813. or increment_version) that occurred to a specific Tensor for a
  814. chunk of memory. The categories help map each (TensorKey,
  815. version) pair into a category."""
  816. self.timeline = memory_profile.timeline
  817. self.categories = memory_profile._categories
  818. def _coalesce_timeline(self, device_str):
  819. """Convert the memory timeline and categories into a memory plot
  820. consisting of timestamps and their respective sizes by category
  821. for a given device.
  822. Input: device
  823. Output: [timestamps, sizes by category]
  824. """
  825. device = torch.device(device_str)
  826. times: List[int] = []
  827. sizes: List[List[int]] = []
  828. def update(key, version, delta):
  829. category = (
  830. self.categories.get(key, version)
  831. if isinstance(key, TensorKey)
  832. else None
  833. )
  834. index = _CATEGORY_TO_INDEX[category] + 1
  835. sizes[-1][index] += int(delta)
  836. t_min = -1
  837. for t, action, (key, version), numbytes in self.timeline:
  838. if key.device != device:
  839. continue
  840. # Convert timestamps from ns to us, to match trace events.
  841. if t != -1:
  842. t = int(t / 1000)
  843. # Save the smallest timestamp to populate pre-existing allocs.
  844. if t_min == -1 or (t < t_min and t > 0):
  845. t_min = t
  846. # Handle timestep
  847. if len(times) == 0:
  848. times.append(t)
  849. sizes.append([0] + [0 for _ in _CATEGORY_TO_INDEX])
  850. elif t != times[-1]:
  851. times.append(t)
  852. sizes.append(sizes[-1].copy())
  853. # Handle memory and categories
  854. if action in (Action.PREEXISTING, Action.CREATE):
  855. update(key, version, numbytes)
  856. elif action == Action.INCREMENT_VERSION:
  857. update(key, version, -numbytes)
  858. update(key, version + 1, numbytes)
  859. elif action == Action.DESTROY:
  860. update(key, version, -numbytes)
  861. else:
  862. raise ValueError(f"Unknown action: {action}")
  863. times = [t_min if t < 0 else t for t in times]
  864. return times, sizes
  865. def export_memory_timeline(self, path, device_str) -> None:
  866. """Saves the memory timeline as [times, sizes by category]
  867. as a JSON formatted file to the given path for the given
  868. device."""
  869. times, sizes = self._coalesce_timeline(device_str)
  870. # TODO: Write a faster serialize (orjson not available in CI)
  871. import json
  872. with open(path, "w") as f:
  873. json.dump([times, sizes], f)
  874. def export_memory_timeline_raw(self, path, device_str) -> None:
  875. """Saves the memory timeline as raw memory event tuples in the
  876. form of (timestamp, action, numbytes, category)
  877. as a JSON formatted file to the given path for the given
  878. device."""
  879. device = torch.device(device_str)
  880. raw_events: List[Tuple[int, int, int, int]] = []
  881. def get_category_index(key, version):
  882. category = (
  883. self.categories.get(key, version)
  884. if isinstance(key, TensorKey)
  885. else None
  886. )
  887. return _CATEGORY_TO_INDEX[category]
  888. for t, action, (key, version), numbytes in self.timeline:
  889. if key.device != device:
  890. continue
  891. if action in (Action.PREEXISTING, Action.CREATE):
  892. raw_events.append(
  893. (
  894. t,
  895. _ACTION_TO_INDEX[action],
  896. numbytes,
  897. get_category_index(key, version),
  898. )
  899. )
  900. elif action == Action.INCREMENT_VERSION:
  901. raw_events.append(
  902. (
  903. t,
  904. _ACTION_TO_INDEX[action],
  905. -numbytes,
  906. get_category_index(key, version),
  907. )
  908. )
  909. raw_events.append(
  910. (
  911. t,
  912. _ACTION_TO_INDEX[action],
  913. numbytes,
  914. get_category_index(key, version + 1),
  915. )
  916. )
  917. elif action == Action.DESTROY:
  918. raw_events.append(
  919. (
  920. t,
  921. _ACTION_TO_INDEX[action],
  922. -numbytes,
  923. get_category_index(key, version),
  924. )
  925. )
  926. else:
  927. raise ValueError(f"Unknown action: {action}")
  928. import json
  929. with open(path, "w") as f:
  930. json.dump(raw_events, f)
  931. def export_memory_timeline_html(
  932. self, path, device_str, figsize=(20, 12), title=None
  933. ) -> None:
  934. """Exports the memory timeline as an HTML file which contains
  935. the memory timeline plot embedded as a PNG file."""
  936. # Check if user has matplotlib installed, return gracefully if not.
  937. import importlib.util
  938. matplotlib_spec = importlib.util.find_spec("matplotlib")
  939. if matplotlib_spec is None:
  940. print(
  941. "export_memory_timeline_html failed because matplotlib was not found."
  942. )
  943. return
  944. from base64 import b64encode
  945. from os import remove
  946. from tempfile import NamedTemporaryFile
  947. import matplotlib.pyplot as plt
  948. import numpy as np
  949. mt = self._coalesce_timeline(device_str)
  950. times, sizes = np.array(mt[0]), np.array(mt[1])
  951. # For this timeline, start at 0 to match Chrome traces.
  952. t_min = min(times)
  953. times -= t_min
  954. stacked = np.cumsum(sizes, axis=1) / 1024**3
  955. device = torch.device(device_str)
  956. max_memory_allocated = torch.cuda.max_memory_allocated(device)
  957. max_memory_reserved = torch.cuda.max_memory_reserved(device)
  958. # Plot memory timeline as stacked data
  959. fig = plt.figure(figsize=figsize, dpi=80)
  960. axes = fig.gca()
  961. for category, color in _CATEGORY_TO_COLORS.items():
  962. i = _CATEGORY_TO_INDEX[category]
  963. axes.fill_between(
  964. times / 1e3, stacked[:, i], stacked[:, i + 1], color=color, alpha=0.7
  965. )
  966. fig.legend(["Unknown" if i is None else i.name for i in _CATEGORY_TO_COLORS])
  967. # Usually training steps are in magnitude of ms.
  968. axes.set_xlabel("Time (ms)")
  969. axes.set_ylabel("Memory (GB)")
  970. title = "\n\n".join(
  971. ([title] if title else [])
  972. + [
  973. f"Max memory allocated: {max_memory_allocated/(1024**3):.2f} GiB \n"
  974. f"Max memory reserved: {max_memory_reserved/(1024**3):.2f} GiB"
  975. ]
  976. )
  977. axes.set_title(title)
  978. # Embed the memory timeline image into the HTML file
  979. tmpfile = NamedTemporaryFile("wb", suffix=".png", delete=False)
  980. tmpfile.close()
  981. fig.savefig(tmpfile.name, format="png")
  982. with open(tmpfile.name, "rb") as tmp:
  983. encoded = b64encode(tmp.read()).decode("utf-8")
  984. html = f"""<html>
  985. <head><meta charset="utf-8" /><title>GPU Memory Timeline HTML</title></head>
  986. <body>
  987. <img src='data:image/png;base64,{encoded}'>
  988. </body>
  989. </html>"""
  990. with open(path, "w") as f:
  991. f.write(html)
  992. remove(tmpfile.name)