scheduler.py 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177
  1. import collections
  2. import dataclasses
  3. import functools
  4. import itertools
  5. import logging
  6. import os
  7. import pprint
  8. import textwrap
  9. from typing import Dict, List, Optional, Set
  10. import sympy
  11. import torch
  12. from torch._dynamo.utils import dynamo_timed
  13. from . import config, dependencies, ir, metrics
  14. from .dependencies import StarDep, WeakDep
  15. from .sizevars import SimplifyIndexing
  16. from .utils import cache_on_self, cmp, has_triton
  17. from .virtualized import V
  18. log = logging.getLogger(__name__)
  19. def pformat(obj):
  20. if isinstance(obj, set):
  21. # pformat has trouble with sets of sympy exprs
  22. obj = sorted(obj, key=str)
  23. result = pprint.pformat(obj, indent=4)
  24. if "\n" in result:
  25. return f"\n{textwrap.indent(result, ' '*4)}"
  26. return result
  27. class OutputNode:
  28. def __init__(self, dep):
  29. self.unmet_dependencies = {dep}
  30. self.inverse_users = []
  31. def is_reduction(self):
  32. return False
  33. def get_alias_names(self):
  34. return ()
  35. def get_name(self):
  36. return "OUTPUT"
  37. __repr__ = get_name
  38. class BaseSchedulerNode:
  39. def __init__(self, scheduler: "Scheduler", node: ir.Buffer):
  40. self.scheduler: "Scheduler" = scheduler
  41. self.node: ir.Buffer = node
  42. self.users: Optional[List[NodeUser]] = None
  43. self.inverse_users: List[BaseSchedulerNode] = []
  44. self.set_read_writes(node.get_read_writes())
  45. self.recursive_predecessors: Optional[Set[str]] = None
  46. self.min_order: Optional[int] = None
  47. self.max_order: Optional[int] = None
  48. self.last_usage: Set[str] = None # buffers that won't be used after this kernel
  49. self.written = False
  50. def __repr__(self):
  51. return f"{type(self).__name__}(name={self.get_name()!r})"
  52. def debug_str(self):
  53. """Longer form printout for trace logs"""
  54. name = self.get_name()
  55. lines = [
  56. f"{name}: {type(self).__name__}({type(self.node).__name__})",
  57. f"{name}.writes = {pformat(self.read_writes.writes)}",
  58. f"{name}.unmet_dependencies = {pformat(self.unmet_dependencies)}",
  59. f"{name}.met_dependencies = {pformat(self.read_writes.reads - self.unmet_dependencies)}",
  60. ]
  61. try:
  62. lines += [
  63. self.debug_str_extra(),
  64. ]
  65. except Exception:
  66. log.warning("Ignoring error in debug_str()", exc_info=True)
  67. return "\n".join(lines).rstrip()
  68. def debug_str_extra(self):
  69. return ""
  70. def log_details(self):
  71. log.info(
  72. "%s: unmet_dependencies = %s, writes = %s",
  73. self,
  74. self.unmet_dependencies,
  75. self.read_writes.writes,
  76. )
  77. def update_mutated_names(self, renames: Dict[str, str]):
  78. self.set_read_writes(self.read_writes.rename(renames))
  79. def add_mutation_dep(self, dep):
  80. self.set_read_writes(self.read_writes.with_read(dep))
  81. def set_users(self, users: List["NodeUser"]):
  82. # deduplicate
  83. result: Dict[int, NodeUser] = {}
  84. for use in users:
  85. if id(use.node) in result:
  86. result[id(use.node)] = NodeUser(
  87. use.node, result[id(use.node)].can_inplace and use.can_inplace
  88. )
  89. else:
  90. result[id(use.node)] = use
  91. self.users = list(result.values())
  92. def get_aliases(self):
  93. return self.node.get_alias_names()
  94. def get_mutations(self):
  95. return self.node.get_mutation_names()
  96. def has_aliasing_or_mutation(self):
  97. return bool(self.get_aliases() or self.get_mutations())
  98. def set_read_writes(self, rw: dependencies.ReadWrites):
  99. self.read_writes: dependencies.ReadWrites = rw
  100. self.unmet_dependencies = self.read_writes.reads
  101. self.prune_deps()
  102. def used_buffer_names(self) -> Set[str]:
  103. return {
  104. dep.name
  105. for dep in itertools.chain(self.read_writes.reads, self.read_writes.writes)
  106. }
  107. def prune_deps(self):
  108. self.unmet_dependencies = {
  109. dep
  110. for dep in self.unmet_dependencies
  111. if dep.name not in self.scheduler.available_buffer_names
  112. }
  113. def prune_redundant_deps(self, name_to_fused_node):
  114. """
  115. Prunes stardeps intended for mutation ordering
  116. on an upstream fused node if after fusion there is another dependency
  117. on the fused upstream node, making the stardep redundant
  118. In essence this enforces an ordering on fusions. As fusions occur, prunable stardeps will
  119. be incrementally removed, enabling other fusions, ensuring they are fused in order.
  120. """
  121. name_to_dep_count = collections.Counter()
  122. for dep in self.unmet_dependencies:
  123. if not isinstance(dep, WeakDep):
  124. name_to_dep_count[name_to_fused_node[dep.name].get_name()] += 1
  125. def should_prune(dep):
  126. if isinstance(dep, WeakDep):
  127. is_redundant = (
  128. name_to_dep_count[name_to_fused_node[dep.name].get_name()] > 0
  129. )
  130. # These can occur because fused nodes always gather deps from their snodes
  131. # If B has a weakdep on A
  132. # B gets fused with C, then any time BC is fused, the weakdep will reappear
  133. is_self_dep = name_to_fused_node[dep.name] == self
  134. return is_redundant or is_self_dep
  135. else:
  136. return False
  137. deps_to_prune = {dep for dep in self.unmet_dependencies if should_prune(dep)}
  138. self.unmet_dependencies = self.unmet_dependencies - deps_to_prune
  139. self.set_read_writes(self.read_writes.remove_reads(deps_to_prune))
  140. def get_name(self) -> str:
  141. return self.node.get_name()
  142. def get_first_name(self) -> str:
  143. return self.get_name()
  144. def get_names(self) -> Set[str]:
  145. return {self.get_name()}
  146. def get_nodes(self) -> List["BaseSchedulerNode"]:
  147. return [self]
  148. def get_device(self):
  149. return self.node.get_device()
  150. def is_reduction(self):
  151. return False
  152. def is_template(self):
  153. return False
  154. def is_extern(self):
  155. return False
  156. def can_inplace(self, read_dep: dependencies.MemoryDep):
  157. return False
  158. def allocate(self):
  159. if not self.node.should_allocate():
  160. return
  161. if isinstance(self, (SchedulerNode,)) and (
  162. self.node.get_alias_names() or self.node.get_mutation_names()
  163. ):
  164. V.graph.wrapper_code.codegen_allocation(self.node)
  165. return
  166. if (
  167. isinstance(self, (SchedulerNode,))
  168. and config.inplace_buffers
  169. and (
  170. not isinstance(V.kernel, torch._inductor.codegen.triton.TritonKernel)
  171. or getattr(V.kernel, "mutations", None) is not None
  172. )
  173. ):
  174. from .codegen.wrapper import buffer_reuse_key
  175. ordered_reads = sorted(self.read_writes.reads, key=lambda x: x.name)
  176. for read in ordered_reads:
  177. input_node: BaseSchedulerNode = self.scheduler.name_to_node.get(
  178. read.name
  179. )
  180. if input_node and V.graph.wrapper_code.can_reuse(input_node):
  181. remaining_uses = [
  182. x
  183. for x in input_node.users
  184. if x.node.get_name()
  185. not in self.scheduler.available_buffer_names
  186. ]
  187. if (
  188. len(remaining_uses) == 1
  189. and remaining_uses[0].can_inplace
  190. and remaining_uses[0].node is self
  191. and not isinstance(
  192. input_node.node.get_layout(),
  193. (
  194. ir.MultiOutputLayout,
  195. ir.MutationLayout,
  196. ir.AliasedLayout,
  197. ),
  198. )
  199. and buffer_reuse_key(input_node.node)
  200. == buffer_reuse_key(self.node)
  201. ):
  202. V.graph.wrapper_code.codegen_inplace_reuse(
  203. input_node.node, self.node
  204. )
  205. V.kernel.args.make_inplace(
  206. input_node.get_name(), self.get_name()
  207. )
  208. # mutations not tracked in cpp kernels
  209. if isinstance(
  210. V.kernel, torch._inductor.codegen.triton.TritonKernel
  211. ):
  212. V.kernel.mutations.add(input_node.get_name())
  213. V.kernel.mutations.add(self.get_name())
  214. return
  215. V.graph.wrapper_code.codegen_allocation(self.node)
  216. def can_free(self):
  217. for use in self.users:
  218. if isinstance(use.node, OutputNode):
  219. return False
  220. return True
  221. def codegen_originating_info(self, buffer, only_once=True):
  222. if not config.comment_origin:
  223. return
  224. if only_once and self.written:
  225. return
  226. origins = self.node.origins
  227. out_lines = []
  228. for o in origins:
  229. if o.op == "output":
  230. # These are boring and samey
  231. continue
  232. out_lines.append("")
  233. # TODO(voz): Should the pragma be constant somewhere?
  234. out_lines.append("#pragma CMT ORIGIN:")
  235. out_lines.append(f"#pragma CMT {o.op} {o.target}")
  236. if "stack_trace" in o.meta:
  237. stack_trace = f"{o.meta['stack_trace']}"
  238. stack_trace_last_line = stack_trace.split("|")[-1]
  239. out_lines.append(
  240. "#pragma CMT "
  241. + stack_trace_last_line.replace("{", "{{")
  242. .replace("}", "}}")
  243. .replace("\n", "\\")
  244. )
  245. out_lines.append("#pragma CMT END ORIGIN")
  246. out_lines.append("")
  247. if len(out_lines) == 0:
  248. return
  249. # TODO(voz): Ostensibly, we should not need this. But there are cases where C++ codegen does
  250. # not use BracesBuffer, so we have no good indicator of a C++ buffer atm.
  251. buffer.writelines(out_lines)
  252. self.written = True
  253. class ExternKernelSchedulerNode(BaseSchedulerNode):
  254. def debug_str_extra(self):
  255. return f"{self.get_name()}.node.kernel = {getattr(self.node, 'kernel', None)}"
  256. def is_extern(self):
  257. return True
  258. class NopKernelSchedulerNode(BaseSchedulerNode):
  259. pass
  260. class SchedulerNode(BaseSchedulerNode):
  261. def __init__(self, scheduler: "Scheduler", node: ir.ComputedBuffer, group_fn):
  262. super().__init__(scheduler, node)
  263. (
  264. self._sizes,
  265. self._body,
  266. ) = node.simplify_and_reorder()
  267. self.group = (node.get_device(), group_fn(self._sizes))
  268. if self.is_template():
  269. self.set_read_writes(node.normalized_read_writes())
  270. else:
  271. self.set_read_writes(
  272. dependencies.extract_read_writes(
  273. self._body, *self._sizes, normalize=True
  274. )
  275. )
  276. if self.is_reduction():
  277. # reduction has last (reduced) dim in its sizes, and some
  278. # downstream dependencies get confused by it
  279. self.read_writes.writes = self.read_writes.writes | {
  280. w.strip_last_size() for w in self.read_writes.writes
  281. }
  282. # reduction not on the last dim swaps the sizes, and downstream
  283. # dependencies expect unswapped
  284. # TODO swapping sizes doesn't work, leads to
  285. # File "/scratch/ngimel/work/repos/torchdynamo/torchinductor/sizevars.py", line 130, in guard_equals
  286. # if len(right.free_symbols) < len(left.free_symbols):
  287. # AttributeError: 'int' object has no attribute 'free_symbols'
  288. # even though memory dep looks correct
  289. # self.read_writes.writes = self.read_writes.writes | {
  290. # w.maybe_swap_sizes() for w in self.read_writes.writes
  291. # }
  292. def debug_str_extra(self):
  293. name = self.get_name()
  294. lines = [
  295. f"{name}.group.device = {self.group[0]}",
  296. f"{name}.group.iteration = {self.group[1]}",
  297. f"{name}.sizes = {self._sizes}",
  298. ]
  299. if self.get_aliases():
  300. lines.append(f"{name}.aliases = {pformat(self.get_aliases())}")
  301. if self.get_mutations():
  302. lines.append(f"{name}.mutations = {pformat(self.get_mutations())}")
  303. if isinstance(self._body, ir.LoopBody):
  304. lines.append(f"class {name}_loop_body:")
  305. lines.append(textwrap.indent(self._body.debug_str(), " "))
  306. return "\n".join(lines)
  307. def get_ranges(self):
  308. return self._sizes
  309. def is_reduction(self):
  310. return bool(self.node.get_reduction_type())
  311. def is_template(self):
  312. return isinstance(self.node, ir.TemplateBuffer)
  313. def run(self, *index_vars):
  314. self.mark_run()
  315. self.codegen(index_vars)
  316. def mark_run(self):
  317. self.allocate()
  318. def ranges_from_index_vars(self, index_vars):
  319. sizes = self._sizes
  320. assert sum(map(len, sizes)) == sum(map(len, index_vars))
  321. var_ranges = dict(
  322. zip(
  323. itertools.chain.from_iterable(index_vars),
  324. itertools.chain.from_iterable(sizes),
  325. )
  326. )
  327. return var_ranges
  328. def codegen(self, index_vars):
  329. var_ranges = self.ranges_from_index_vars(index_vars)
  330. try:
  331. with V.set_ops_handler(
  332. SimplifyIndexing(V.get_ops_handler(), var_ranges)
  333. ), V.kernel.set_current_node(self):
  334. self._body(*index_vars)
  335. except Exception:
  336. log.fatal("Error in codegen for %s", self.node)
  337. raise
  338. def pointwise_read_writes(self):
  339. """
  340. Get the memory dependencies in the non-reduction axis.
  341. """
  342. sizes, reduction_sizes = self._sizes
  343. def fn(index):
  344. return self._body(index, [sympy.Integer(0) for _ in reduction_sizes])
  345. return dependencies.extract_read_writes(fn, sizes)
  346. def can_inplace(self, read_dep: dependencies.MemoryDep):
  347. if self.get_aliases() or self.is_template():
  348. return False
  349. if len(self.read_writes.writes) == 1 and hasattr(read_dep, "index"):
  350. write_dep = next(iter(self.read_writes.writes))
  351. return read_dep.index == write_dep.index and read_dep.size == write_dep.size
  352. return False
  353. class FusedSchedulerNode(BaseSchedulerNode):
  354. """
  355. This is a "fake" scheduler node that represents a group of scheduler nodes
  356. that are meant to be fused together. The way it does this is by maintaining
  357. its unmet dependencies as the union of its constituent nodes.
  358. """
  359. @classmethod
  360. def fuse(cls, node1: BaseSchedulerNode, node2: BaseSchedulerNode):
  361. assert node1.scheduler is node2.scheduler
  362. return cls(node1.scheduler, node1.get_nodes() + node2.get_nodes())
  363. def __init__(self, scheduler: "Scheduler", snodes: List[SchedulerNode]):
  364. # NB: No need to call super().__init__() because we don't need to re-use any of its logic.
  365. self.snodes = snodes
  366. self.scheduler = scheduler
  367. self.node = None # type: ignore[assignment]
  368. self.users = None
  369. self.inverse_users = []
  370. self.group = max(snodes, key=lambda x: int(x.is_reduction())).group
  371. self.recursive_predecessors = functools.reduce(
  372. set.union, [x.recursive_predecessors for x in snodes]
  373. )
  374. self.set_read_writes(
  375. functools.reduce(
  376. dependencies.ReadWrites.merge, [x.read_writes for x in snodes]
  377. )
  378. )
  379. names = set(self.get_names())
  380. self.unmet_dependencies = {
  381. dep
  382. for dep in functools.reduce(
  383. set.union, [x.unmet_dependencies for x in snodes]
  384. )
  385. if dep.name not in names
  386. } - self.read_writes.writes
  387. self.min_order = min([x.min_order for x in self.snodes])
  388. self.max_order = max([x.max_order for x in self.snodes])
  389. @cache_on_self
  390. def get_name(self) -> str:
  391. return "_".join([x.get_name() for x in self.snodes])
  392. def get_first_name(self) -> str:
  393. return self.snodes[0].get_name()
  394. @cache_on_self
  395. def get_names(self) -> Set[str]:
  396. return functools.reduce(set.union, [x.get_names() for x in self.snodes])
  397. def debug_str_extra(self):
  398. return (
  399. f"{self.get_name()}.snodes = {pformat([x.get_name() for x in self.snodes])}"
  400. )
  401. @cache_on_self
  402. def used_buffer_names(self) -> Set[str]:
  403. return functools.reduce(set.union, [x.used_buffer_names() for x in self.snodes])
  404. def get_nodes(self) -> List[BaseSchedulerNode]:
  405. return self.snodes
  406. def __repr__(self):
  407. return f"{type(self).__name__}(nodes={self.get_name()})"
  408. @cache_on_self
  409. def is_reduction(self):
  410. return any(x.is_reduction() for x in self.snodes)
  411. @cache_on_self
  412. def is_template(self):
  413. return any(x.is_template() for x in self.snodes)
  414. def get_device(self):
  415. return self.group[0]
  416. @cache_on_self
  417. def has_aliasing_or_mutation(self):
  418. return any(x.has_aliasing_or_mutation() for x in self.snodes)
  419. # None of these need to be implemented, as a FusedSchedulerNode is just an
  420. # abstraction for scheduling purposes
  421. def update_mutated_names(self, renames: Dict[str, str]):
  422. raise NotImplementedError
  423. def add_mutation_dep(self, name):
  424. raise NotImplementedError
  425. def set_users(self, users: List["NodeUser"]):
  426. raise NotImplementedError
  427. def get_aliases(self):
  428. raise NotImplementedError
  429. def get_mutations(self):
  430. raise NotImplementedError
  431. def can_inplace(self, read_dep: dependencies.MemoryDep):
  432. raise NotImplementedError
  433. def allocate(self):
  434. raise NotImplementedError
  435. def can_free(self):
  436. raise NotImplementedError
  437. def pick_loop_order(stride_lengths, sizes, priority_idx=()):
  438. """
  439. A heuristic to decide loop iteration orders. This has not been well
  440. tuned and may be something we should autotune.
  441. """
  442. @functools.cmp_to_key
  443. def index_cmp(a, b):
  444. if sizes[a] == 1 or sizes[b] == 1:
  445. # 1-sizes don't matter, just move them to the end
  446. return cmp(sizes[a] == 1, sizes[b] == 1)
  447. stride_len_a = [sl[a] for sl in stride_lengths]
  448. stride_len_b = [sl[b] for sl in stride_lengths]
  449. # equivalent to
  450. # np.logical_or(stride_lengths[:, b] == 0, stride_lengths[:, a] < stride_lengths[:, b]).all()
  451. a_first = all(
  452. sl_b == 0 or sl_a < sl_b for sl_a, sl_b in zip(stride_len_a, stride_len_b)
  453. )
  454. b_first = all(
  455. sl_a == 0 or sl_b < sl_a for sl_a, sl_b in zip(stride_len_a, stride_len_b)
  456. )
  457. if a_first and not b_first:
  458. return -1
  459. if b_first and not a_first:
  460. return 1
  461. # otherwise contiguous
  462. return cmp(b, a)
  463. order = list(reversed(range(len(stride_lengths[0]))))
  464. if len(priority_idx) > 0:
  465. # if we have priority node, only use that node's order
  466. stride_lengths = [stride_lengths[pi] for pi in priority_idx]
  467. if config.pick_loop_orders:
  468. order.sort(key=index_cmp)
  469. return order
  470. @dataclasses.dataclass
  471. class NodeUser:
  472. node: BaseSchedulerNode
  473. can_inplace: bool = False
  474. def get_name(self):
  475. return self.node.get_name()
  476. class Scheduler:
  477. @dynamo_timed
  478. def __init__(self, nodes):
  479. super().__init__()
  480. self.backends = {}
  481. self.nodes = []
  482. self.available_buffer_names = {
  483. *V.graph.graph_inputs.keys(),
  484. *V.graph.constants.keys(),
  485. }
  486. for node in nodes:
  487. assert (
  488. node.origins is not None
  489. ), "All nodes passed to scheduling must have an origin"
  490. if node.is_no_op():
  491. self.nodes.append(NopKernelSchedulerNode(self, node))
  492. elif isinstance(node, (ir.ComputedBuffer, ir.TemplateBuffer)):
  493. group_fn = self.get_backend(node.get_device()).group_fn
  494. self.nodes.append(SchedulerNode(self, node, group_fn))
  495. elif isinstance(node, ir.ExternKernel):
  496. self.nodes.append(ExternKernelSchedulerNode(self, node))
  497. else:
  498. raise NotImplementedError(node)
  499. # some new constants could have been created above
  500. self.available_buffer_names.update(V.graph.constants.keys())
  501. for node in self.nodes:
  502. node.prune_deps()
  503. self.name_to_node = {node.get_name(): node for node in self.nodes}
  504. self.name_to_fused_node = None # set in fuse_nods()
  505. # we handle mutation by renaming modified versions of the same
  506. # buffer in the dependency graph to prevent cycles.
  507. # mutation_renames: tracks the current name for a given buffer
  508. # (changed once per mutation)
  509. self.mutation_real_name = {}
  510. # mutation_real_name: maps back to the original name for codegen
  511. self.mutation_renames = {}
  512. self.compute_dependencies()
  513. self.topological_sort_schedule()
  514. self.compute_predecessors()
  515. self.dead_node_elimination()
  516. metrics.ir_nodes_pre_fusion += len(self.nodes)
  517. V.debug.ir_pre_fusion(self.nodes)
  518. self.num_orig_nodes = len(self.nodes)
  519. self.name_to_fused_node = {n.get_name(): n for n in self.nodes}
  520. self.fuse_nodes()
  521. self.compute_last_usage()
  522. V.debug.ir_post_fusion(self.nodes)
  523. V.debug.graph_diagram(self.nodes)
  524. self.debug_draw_graph()
  525. # used during codegen:
  526. self.current_device = None
  527. self.buffer_names_to_free = set()
  528. self.buffer_names_no_longer_needed = set()
  529. def debug_draw_graph(self):
  530. """Generate an image of the graph for debugging"""
  531. if os.environ.get("INDUCTOR_WRITE_SCHEDULER_GRAPH", None) == "1":
  532. from .debug import draw_buffers
  533. draw_buffers(self.nodes, print_graph=True)
  534. def debug_print_nodes(self, label):
  535. if log.isEnabledFor(logging.INFO):
  536. log.info("%s:", label)
  537. for node in self.nodes:
  538. node.log_details()
  539. def compute_dependencies(self):
  540. """
  541. Create dependency edges between nodes, handling aliasing and
  542. mutation properly.
  543. """
  544. name_to_users = collections.defaultdict(list)
  545. # handle aliasing by using python aliasing in name_to_users
  546. # if foo aliases bar then we will make name_to_users["foo"] point
  547. # to the same python list as name_to_users["bar"]
  548. for node1 in self.nodes:
  549. node1_name = node1.get_name()
  550. for node2_name in node1.get_aliases():
  551. if node1_name in name_to_users and node2_name in name_to_users:
  552. # merge the two
  553. list1 = name_to_users[node1_name]
  554. list2 = name_to_users[node2_name]
  555. combined = list1 + list2
  556. for key in name_to_users.keys():
  557. if name_to_users[key] is list1 or name_to_users[key] is list2:
  558. name_to_users[key] = combined
  559. elif node1_name in name_to_users:
  560. name_to_users[node2_name] = name_to_users[node1_name]
  561. else:
  562. name_to_users[node1_name] = name_to_users[node2_name]
  563. def rename(n):
  564. if n in self.mutation_renames:
  565. return rename(self.mutation_renames[n])
  566. return n
  567. def dep_closure(node_name):
  568. reachable_names = {node_name}
  569. node = self.name_to_node[node_name]
  570. write_dep = list(node.read_writes.writes)[0]
  571. for read_dep in node.read_writes.reads:
  572. if (
  573. read_dep.name in self.name_to_node
  574. and read_dep.index == write_dep.index
  575. and read_dep.size == write_dep.size
  576. ):
  577. reachable_names.update(dep_closure(read_dep.name))
  578. return reachable_names
  579. def add_user(used_by_name, user_node, can_inplace=False):
  580. name_to_users[rename(used_by_name)].append(NodeUser(user_node, can_inplace))
  581. for node in self.nodes:
  582. # a node will mutate either 0 or 1 buffers
  583. for alt_name in node.get_mutations():
  584. alt_name = rename(alt_name)
  585. # this node must run after the prior writer
  586. add_user(alt_name, node)
  587. node.add_mutation_dep(StarDep(alt_name))
  588. for other_node in name_to_users[alt_name]:
  589. # this node must run after all prior readers
  590. other_name = rename(other_node.get_name())
  591. known_dep_node_names = dep_closure(node.get_name())
  592. if other_name not in known_dep_node_names:
  593. # If this node already directly or indirectly depends on other_node,
  594. # we don't need to insert an extra dep.
  595. node.add_mutation_dep(WeakDep(other_name))
  596. add_user(other_name, node)
  597. # add normal non-mutation dependencies
  598. for read in node.read_writes.reads:
  599. add_user(read.name, node, node.can_inplace(read))
  600. node.update_mutated_names(self.mutation_renames)
  601. # update our renaming scheme for the next iteration
  602. for alt_name in node.get_mutations():
  603. self.mutation_renames[rename(alt_name)] = node.get_name()
  604. self.mutation_renames[alt_name] = node.get_name()
  605. self.mutation_real_name[node.get_name()] = self.mutation_real_name.get(
  606. alt_name, alt_name
  607. )
  608. # make sure outputs aren't dead-code-eliminated
  609. for node_name in V.graph.get_output_names():
  610. add_user(node_name, OutputNode(StarDep(node_name)))
  611. # make sure input mutation isn't dead-code-eliminated
  612. for name in self.mutation_renames:
  613. if name in V.graph.graph_inputs:
  614. add_user(name, OutputNode(StarDep(name)))
  615. V.graph.mutated_inputs.add(name)
  616. # copy users information onto the nodes
  617. for node in self.nodes:
  618. node.set_users(name_to_users[node.get_name()])
  619. # populate inverse_users
  620. for node in self.nodes:
  621. for user in node.users:
  622. user.node.inverse_users.append(node)
  623. def dead_node_elimination(self):
  624. """
  625. Remove any nodes without users
  626. """
  627. updated_nodes = []
  628. for node in self.nodes:
  629. if node.users:
  630. updated_nodes.append(node)
  631. else:
  632. # dead code
  633. log.debug("removed dead node: %s", node.get_name())
  634. V.graph.removed_buffers.add(node.get_name())
  635. self.nodes = updated_nodes
  636. def topological_sort_schedule(self):
  637. """
  638. Ensure self.nodes is in topologically sorted order
  639. """
  640. seen = set()
  641. name_to_node = dict()
  642. result = []
  643. def visit(n):
  644. if n not in seen:
  645. seen.add(n)
  646. for dep in sorted(n.unmet_dependencies, key=lambda d: d.name):
  647. visit(name_to_node[dep.name])
  648. result.append(n)
  649. for node in self.nodes:
  650. for name in node.get_names():
  651. name_to_node[name] = node
  652. for node in self.nodes:
  653. visit(node)
  654. self.nodes = result
  655. def compute_predecessors(self):
  656. """
  657. Populate each node.recursive_predecessors
  658. """
  659. # note self.nodes is topologically sorted
  660. name_to_predecessors = {}
  661. for node in self.nodes:
  662. recursive_predecessors = set()
  663. for dep in node.unmet_dependencies:
  664. recursive_predecessors.add(dep.name)
  665. recursive_predecessors |= name_to_predecessors[dep.name]
  666. name_to_predecessors[node.get_name()] = recursive_predecessors
  667. node.recursive_predecessors = recursive_predecessors
  668. for order, node in enumerate(self.nodes):
  669. node.min_order = order
  670. node.max_order = order
  671. def fuse_nodes(self):
  672. """
  673. Mutates self.nodes to combine nodes into FusedSchedulerNodes.
  674. """
  675. for _ in range(10):
  676. old_len = len(self.nodes)
  677. self.fuse_nodes_once()
  678. if len(self.nodes) == old_len:
  679. break
  680. def fuse_nodes_once(self):
  681. """
  682. Mutates self.nodes to combine nodes into FusedSchedulerNodes.
  683. This relies on two key functions to control the logic:
  684. - self.can_fuses(): checks if a fusion is legal
  685. - self.score_fusion(): assigns priority to a given fusion
  686. """
  687. fused_nodes = set(self.nodes)
  688. for node1, node2 in self.get_possible_fusions():
  689. node1 = self.name_to_fused_node[node1.get_first_name()]
  690. node2 = self.name_to_fused_node[node2.get_first_name()]
  691. if self.can_fuse(node1, node2) and not self.will_fusion_create_cycle(
  692. node1, node2
  693. ):
  694. node3 = FusedSchedulerNode.fuse(node1, node2)
  695. fused_nodes.remove(node1)
  696. fused_nodes.remove(node2)
  697. fused_nodes.add(node3)
  698. self.name_to_fused_node.update(
  699. {n.get_name(): node3 for n in node3.get_nodes()}
  700. )
  701. self.nodes = sorted(fused_nodes, key=lambda x: x.min_order)
  702. self.topological_sort_schedule()
  703. self.prune_redundant_deps()
  704. def prune_redundant_deps(self):
  705. for node in self.nodes:
  706. node.prune_redundant_deps(self.name_to_fused_node)
  707. def get_possible_fusions(self):
  708. """
  709. Helper to find all legal fusion opportunities, sorted by self.score_fusion()
  710. """
  711. possible_fusions = []
  712. seen = set()
  713. def check_all_pairs(nodes):
  714. for node1_index, node1 in enumerate(nodes):
  715. for node2 in nodes[node1_index + 1 :]:
  716. key = (node1, node2)
  717. if key in seen:
  718. continue
  719. seen.add(key)
  720. if self.can_fuse(node1, node2):
  721. possible_fusions.append(key)
  722. elif node2.is_template() and self.can_fuse(node2, node1):
  723. # epilogue fusions are order dependent
  724. possible_fusions.append((node2, node1))
  725. buffer_names_grouping = collections.defaultdict(list)
  726. for node in self.nodes:
  727. for buf in node.used_buffer_names():
  728. buffer_names_grouping[buf].append(node)
  729. for node_grouping in buffer_names_grouping.values():
  730. check_all_pairs(node_grouping)
  731. if config.aggressive_fusion:
  732. group_grouping = collections.defaultdict(list)
  733. for node in self.nodes:
  734. group = getattr(node, "group", None)
  735. if group:
  736. group_grouping[group].append(node)
  737. for node_grouping in group_grouping.values():
  738. check_all_pairs(node_grouping)
  739. return sorted(possible_fusions, key=self.score_fusion_key, reverse=True)
  740. def will_fusion_create_cycle(self, node1, node2):
  741. """Finds whether there's a path from src to dst caused indirectly by fusion"""
  742. def check(node):
  743. if isinstance(node, FusedSchedulerNode) and node not in visited:
  744. visited.add(node)
  745. return bool(combined_names & node.recursive_predecessors) or any(
  746. check(self.name_to_fused_node[n])
  747. for n in node.recursive_predecessors - combined_predecessors
  748. )
  749. return False
  750. visited = set()
  751. combined_names = node1.get_names() | node2.get_names()
  752. combined_predecessors = (
  753. node1.recursive_predecessors | node2.recursive_predecessors
  754. ) - combined_names
  755. return any(check(self.name_to_fused_node[n]) for n in combined_predecessors)
  756. def can_fuse(self, node1: BaseSchedulerNode, node2: BaseSchedulerNode):
  757. """
  758. Determine if it is possible to combine node1 and node2 into a
  759. single fused node.
  760. """
  761. if node1 is node2:
  762. return False
  763. if (
  764. isinstance(node1, (ExternKernelSchedulerNode, NopKernelSchedulerNode))
  765. and not node1.is_template()
  766. ):
  767. return False
  768. if (
  769. isinstance(node2, (ExternKernelSchedulerNode, NopKernelSchedulerNode))
  770. and not node2.is_template()
  771. ):
  772. return False
  773. if node2.get_names() & node1.recursive_predecessors:
  774. return False # node2 must go before node1
  775. if node2.is_template():
  776. return False # only epilogues
  777. if node1.is_template() and (
  778. node2.has_aliasing_or_mutation()
  779. or node2.is_reduction()
  780. or not config.epilogue_fusion
  781. ):
  782. return False
  783. device = node1.get_device()
  784. if device != node2.get_device():
  785. return False # wrong device
  786. no_shared_data = self.score_fusion_memory(node1, node2) == 0
  787. if no_shared_data and (
  788. not config.aggressive_fusion or node1.is_reduction() or node2.is_reduction()
  789. ):
  790. return False # heuristic not needed for correctness
  791. if len(node1.get_nodes()) + len(node2.get_nodes()) > config.max_fusion_size:
  792. return False # heuristic not needed for correctness
  793. if node1.get_names() & node2.recursive_predecessors:
  794. # node2 depends on node1 outputs
  795. if not self.can_fuse_vertical(node1, node2):
  796. return False
  797. return self.get_backend(device).can_fuse_vertical(node1, node2)
  798. else: # nodes don't depend on each other, but may have common reads
  799. return self.get_backend(device).can_fuse_horizontal(node1, node2)
  800. def can_fuse_vertical(self, node1, node2):
  801. """
  802. Check if it is legal to fuse a consumer (node2) into a producer (node1).
  803. We can fuse them if all the reads of node2 either match
  804. corresponding writes in node1, or are written by nodes that can
  805. be scheduled before the fusion of node1 and node2.
  806. """
  807. node1_names = node1.get_names()
  808. computed_deps = set()
  809. for rd in node2.unmet_dependencies:
  810. for cd in node1.read_writes.writes:
  811. # StarDep doesn't match MemoryDep, different indices don't match
  812. # However, broadcasting sometimes strips dimensions, and if that's the case
  813. # we still can match unmet dep
  814. if (
  815. rd.name == cd.name
  816. and type(rd) == type(cd)
  817. and rd.index == cd.index
  818. and len(rd.size) >= len(cd.size)
  819. and rd.size[: len(cd.size)] == cd.size
  820. ):
  821. computed_deps.add(rd)
  822. remaining_deps = {dep.name for dep in node2.unmet_dependencies - computed_deps}
  823. if remaining_deps & node1_names:
  824. # MemoryDeps didn't match and read different locations of the same buffer.
  825. # Examples here include:
  826. # - MemoryDep("foo", x) != MemoryDep("foo", x + 1)
  827. # - MemoryDep("foo", x) != StarDep("foo")
  828. return False
  829. for name in remaining_deps:
  830. if node1_names & self.name_to_fused_node[name].recursive_predecessors:
  831. return False
  832. return True
  833. def score_fusion(self, node1: BaseSchedulerNode, node2: BaseSchedulerNode):
  834. """
  835. Assign a score (higher comes first) to the fusion of node1
  836. and node2. When different fusions conflict with each other,
  837. this is the way we decide what order to run them in.
  838. Our current score is based on:
  839. - Estimate of the saved memory operations
  840. - Fusions closer together in original order
  841. """
  842. memory_score = self.score_fusion_memory(node1, node2)
  843. proximity_score = -max(
  844. abs(node1.min_order - node2.max_order),
  845. abs(node2.min_order - node1.max_order),
  846. )
  847. return (
  848. node1.is_template() == config.epilogue_fusion_first and memory_score > 0,
  849. node1.is_reduction() == node2.is_reduction() and memory_score > 0,
  850. memory_score,
  851. proximity_score,
  852. )
  853. def score_fusion_memory(self, node1, node2):
  854. """
  855. The first term in our fusion score that estimates number of saved memory operations.
  856. """
  857. common_memory_deps = (node1.read_writes.reads | node1.read_writes.writes) & (
  858. node2.read_writes.reads | node2.read_writes.writes
  859. )
  860. return sum(dep.numbytes_hint() for dep in common_memory_deps)
  861. def score_fusion_key(self, nodes):
  862. """
  863. Shim for list.sort(key=...)
  864. """
  865. node1, node2 = nodes
  866. return self.score_fusion(node1, node2)
  867. def compute_last_usage(self):
  868. """
  869. Populate node.last_usage
  870. """
  871. future_used_buffers = set()
  872. for node_name in V.graph.get_output_names():
  873. future_used_buffers.add(node_name)
  874. for node in reversed(self.nodes):
  875. used_buffers = node.used_buffer_names()
  876. used_buffers = {self.mutation_real_name.get(k, k) for k in used_buffers}
  877. node.last_usage = used_buffers - future_used_buffers
  878. future_used_buffers.update(used_buffers)
  879. def free_buffers(self):
  880. """Free any buffers that are no longer needed"""
  881. for name in sorted(self.buffer_names_to_free - V.graph.removed_buffers):
  882. if name in self.name_to_node:
  883. node = self.name_to_node[name]
  884. if node.can_free():
  885. V.graph.wrapper_code.codegen_free(node.node)
  886. elif name in V.graph.graph_inputs:
  887. storage = V.graph.graph_inputs[name].data
  888. assert storage.is_input_buffer()
  889. V.graph.wrapper_code.codegen_free(storage.data)
  890. self.buffer_names_to_free.clear()
  891. def remove_kernel_local_buffers(self):
  892. """
  893. Any buffers that are both created and have a last use in the
  894. same kernel can be removed.
  895. """
  896. for name in V.kernel.store_buffer_names & self.buffer_names_no_longer_needed:
  897. if (
  898. name not in V.kernel.must_keep_buffers
  899. and name not in V.kernel.args.input_buffers
  900. and name not in self.mutation_renames
  901. and name not in self.mutation_real_name
  902. ):
  903. # For inplace buffers subject to remove, we don't actually
  904. # remove them but put them in a dedicated set. This simplifies
  905. # the life cycle management of inplace buffers.
  906. # This set is used to
  907. # 1) avoid unnecessary store in DeferredLine.
  908. # 2) avoid alias var definitions in kernel.
  909. if name in V.kernel.args.inplace_buffers:
  910. V.graph.inplaced_to_remove.add(name)
  911. else:
  912. self.remove_buffer(name)
  913. def remove_buffer(self, name):
  914. # Assign a special value instead of deleting the entry
  915. # because we still rely on output_buffers's length to
  916. # generate unique arg name.
  917. log.debug("remove_buffer(%r)", name)
  918. V.kernel.args.output_buffers[name] = "REMOVED"
  919. V.graph.removed_buffers.add(name)
  920. def flush(self):
  921. for backend in self.backends.values():
  922. backend.flush()
  923. self.free_buffers()
  924. def codegen_extern_call(self, scheduler_node: ExternKernelSchedulerNode):
  925. assert isinstance(scheduler_node, ExternKernelSchedulerNode)
  926. scheduler_node.allocate()
  927. node = scheduler_node.node
  928. node.codegen(V.graph.wrapper_code)
  929. self.free_buffers()
  930. def create_backend(self, device: torch.device):
  931. assert (
  932. device.type != "cuda" or device.index is not None
  933. ), f"{device} should have been normalized in lowering"
  934. V.graph.device_types.add(device.type)
  935. if device.type == "cpu":
  936. from .codegen.cpp import CppScheduling
  937. return CppScheduling(self)
  938. else:
  939. if not has_triton():
  940. device_props = torch.cuda.get_device_properties(device)
  941. if device_props.major < 7:
  942. raise RuntimeError(
  943. f"Found {device_props.name} which is too old to be supported by the triton GPU compiler, which is used as the backend. Triton only supports devices of CUDA Capability >= 7.0, but your device is of CUDA capability {device_props.major}.{device_props.minor}" # noqa: B950
  944. )
  945. else:
  946. raise RuntimeError(
  947. "Cannot find a working triton installation. More information on installing Triton can be found at https://github.com/openai/triton" # noqa: B950
  948. )
  949. from .codegen.triton import TritonScheduling
  950. return TritonScheduling(self)
  951. def get_backend(self, device: torch.device):
  952. if device not in self.backends:
  953. self.backends[device] = self.create_backend(device)
  954. return self.backends[device]
  955. @dynamo_timed
  956. def codegen(self):
  957. for node in self.nodes:
  958. self.buffer_names_no_longer_needed.update(node.last_usage)
  959. if not isinstance(node, NopKernelSchedulerNode):
  960. device = node.get_device()
  961. if (
  962. device != self.current_device
  963. or node.is_extern()
  964. or node.is_template()
  965. ):
  966. self.flush()
  967. if device != self.current_device:
  968. if device.type == "cuda":
  969. if self.current_device and self.current_device.type == "cuda":
  970. V.graph.wrapper_code.codegen_cuda_device_guard_exit()
  971. assert device.index is not None, "device should have an index"
  972. V.graph.wrapper_code.codegen_cuda_device_guard_enter(
  973. device.index
  974. )
  975. elif self.current_device and self.current_device.type == "cuda":
  976. V.graph.wrapper_code.codegen_cuda_device_guard_exit()
  977. self.current_device = device
  978. self.buffer_names_to_free.update(node.last_usage)
  979. if node.is_template():
  980. node, *epilogue = node.get_nodes()
  981. self.get_backend(device).codegen_template(node, epilogue)
  982. elif node.is_extern():
  983. self.codegen_extern_call(node)
  984. elif isinstance(node, (FusedSchedulerNode, SchedulerNode)):
  985. self.get_backend(device).codegen_nodes(node.get_nodes())
  986. else:
  987. assert isinstance(node, NopKernelSchedulerNode)
  988. node.allocate()
  989. if config.triton.debug_sync_kernel:
  990. self.get_backend(device).codegen_sync()
  991. self.available_buffer_names.update(node.get_names())
  992. self.flush()