metrics.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. from __future__ import annotations
  2. import csv
  3. import dataclasses
  4. import inspect
  5. import os
  6. import re
  7. from dataclasses import dataclass
  8. from functools import lru_cache
  9. from typing import Callable, cast, Optional, TYPE_CHECKING, Union
  10. from torch._inductor import config
  11. from torch._inductor.utils import get_benchmark_name
  12. from torch.utils._ordered_set import OrderedSet
  13. # Prevent circular import
  14. if TYPE_CHECKING:
  15. from torch._inductor.scheduler import BaseSchedulerNode
  16. # counter for tracking how many kernels have been generated
  17. generated_kernel_count = 0
  18. generated_cpp_vec_kernel_count = 0
  19. num_bytes_accessed = 0
  20. nodes_num_elem: list[
  21. tuple[
  22. BaseSchedulerNode,
  23. int,
  24. ]
  25. ] = []
  26. node_runtimes: list[tuple[BaseSchedulerNode, float]] = []
  27. # counters for tracking fusions
  28. ir_nodes_pre_fusion = 0
  29. # counters for tracking to_dtype inserted
  30. cpp_to_dtype_count = 0
  31. @dataclasses.dataclass
  32. class CppOuterLoopFusedCount:
  33. inner_kernel_number: int
  34. local_buffer_number: int = 0
  35. # The length counts the number of outer loop fusions.
  36. cpp_outer_loop_fused_inner_counts: list[CppOuterLoopFusedCount] = []
  37. num_comprehensive_padding = 0
  38. num_matches_for_scatter_upon_const_tensor = 0
  39. num_loop_reordering = 0
  40. # counter for parallel reduction.
  41. parallel_reduction_count = 0
  42. # reset all counters
  43. def reset() -> None:
  44. global generated_kernel_count
  45. global generated_cpp_vec_kernel_count
  46. global num_bytes_accessed, nodes_num_elem
  47. global ir_nodes_pre_fusion
  48. global cpp_to_dtype_count
  49. global cpp_outer_loop_fused_inner_counts
  50. global num_comprehensive_padding
  51. global num_matches_for_scatter_upon_const_tensor
  52. global num_loop_reordering
  53. global parallel_reduction_count
  54. generated_kernel_count = 0
  55. generated_cpp_vec_kernel_count = 0
  56. num_bytes_accessed = 0
  57. nodes_num_elem.clear()
  58. node_runtimes.clear()
  59. ir_nodes_pre_fusion = 0
  60. cpp_to_dtype_count = 0
  61. cpp_outer_loop_fused_inner_counts.clear()
  62. num_comprehensive_padding = 0
  63. num_matches_for_scatter_upon_const_tensor = 0
  64. num_loop_reordering = 0
  65. parallel_reduction_count = 0
  66. @dataclass
  67. class CachedMetricsDeltas:
  68. """
  69. The subset of metrics we want update across cache hits, e.g., the
  70. FxGraphCache.
  71. """
  72. generated_kernel_count: int
  73. generated_cpp_vec_kernel_count: int
  74. ir_nodes_pre_fusion: int
  75. cpp_to_dtype_count: int
  76. num_bytes_accessed: int
  77. num_matches_for_scatter_upon_const_tensor: int
  78. def get_metric_fields() -> list[str]:
  79. return [field.name for field in dataclasses.fields(CachedMetricsDeltas)]
  80. class CachedMetricsHelper:
  81. """
  82. A helper class to help calculate and apply counter deltas for those
  83. metrics we want to save with cache entries (e.g., FxGraphCache) and
  84. apply on a cache hit.
  85. """
  86. def __init__(self) -> None:
  87. self.cached_metrics = {}
  88. for metric in get_metric_fields():
  89. self.cached_metrics[metric] = globals()[metric]
  90. def get_deltas(self) -> CachedMetricsDeltas:
  91. delta_metrics = {}
  92. for metric in get_metric_fields():
  93. delta_metrics[metric] = globals()[metric] - self.cached_metrics[metric]
  94. return CachedMetricsDeltas(**delta_metrics)
  95. @staticmethod
  96. def apply_deltas(delta: CachedMetricsDeltas) -> None:
  97. for metric in get_metric_fields():
  98. globals()[metric] += getattr(delta, metric)
  99. REGISTERED_METRIC_TABLES: dict[str, MetricTable] = {}
  100. @dataclass
  101. class MetricTable:
  102. table_name: str
  103. column_names: list[str]
  104. num_rows_added: int = 0
  105. def add_row(
  106. self, row_fn: Callable[[], dict[str, Optional[Union[str, float]]]]
  107. ) -> None:
  108. if self.table_name not in enabled_metric_tables():
  109. return
  110. row_dict = row_fn()
  111. assert len(self.column_names) == len(row_dict), (
  112. f"{len(self.column_names)} v.s. {len(row_dict)}"
  113. )
  114. assert OrderedSet(self.column_names) == OrderedSet(row_dict.keys()), (
  115. f"{OrderedSet(self.column_names)} v.s. {OrderedSet(row_dict.keys())}"
  116. )
  117. bn = get_benchmark_name()
  118. # assert bn is not None
  119. row = [bn] + [row_dict[column_name] for column_name in self.column_names]
  120. assert all(isinstance(i, str) for i in row)
  121. self._write_row(cast(list[str], row))
  122. def output_filename(self) -> str:
  123. return f"metric_table_{self.table_name}.csv"
  124. def write_header(self) -> None:
  125. filename = self.output_filename()
  126. with open(filename, "w") as fd:
  127. writer = csv.writer(fd, lineterminator="\n")
  128. writer.writerow(["model_name"] + self.column_names)
  129. def _write_row(self, row: list[str]) -> None:
  130. filename = self.output_filename()
  131. if self.num_rows_added == 0 and not os.path.exists(filename):
  132. self.write_header()
  133. self.num_rows_added += 1
  134. for idx, orig_val in enumerate(row):
  135. if isinstance(orig_val, float):
  136. new_val = f"{orig_val:.6f}"
  137. elif orig_val is None:
  138. new_val = ""
  139. else:
  140. new_val = orig_val
  141. row[idx] = new_val
  142. with open(filename, "a") as fd:
  143. writer = csv.writer(fd, lineterminator="\n")
  144. writer.writerow(row)
  145. @staticmethod
  146. def register_table(name: str, column_names: list[str]) -> None:
  147. table = MetricTable(name, column_names)
  148. REGISTERED_METRIC_TABLES[name] = table
  149. MetricTable.register_table(
  150. "slow_fusion",
  151. [
  152. "kernel1_path",
  153. "kernel1_latency",
  154. "kernel2_path",
  155. "kernel2_latency",
  156. "fused_kernel_path",
  157. "fused_kernel_latency",
  158. "slow_down_ratio",
  159. ],
  160. )
  161. # track the fusion statistics for each graph
  162. MetricTable.register_table(
  163. "graph_stats",
  164. [
  165. "graph_id",
  166. "num_nodes_before_fusion",
  167. "num_nodes_after_fusion",
  168. ],
  169. )
  170. # track the perf difference between persistent reduction and non-persistent
  171. # reductions
  172. MetricTable.register_table(
  173. "persistent_red_perf",
  174. [
  175. "kernel0_path",
  176. "kernel1_path",
  177. "kernel2_path",
  178. "kernel3_path",
  179. "kernel0_latency",
  180. "kernel1_latency",
  181. "kernel2_latency",
  182. "kernel3_latency",
  183. "size_hints",
  184. "reduction_hint",
  185. ],
  186. )
  187. # Log the fusion failures due to indexing mismatch
  188. MetricTable.register_table(
  189. "fusion_failure_due_to_indexing_mismatch",
  190. [
  191. "pre_grad_graph_id",
  192. "post_grad_graph_id",
  193. "node1_name",
  194. "node2_name",
  195. "node1_debug_str",
  196. "node2_debug_str",
  197. "common_buffer_names",
  198. "failure_reason",
  199. ],
  200. )
  201. # Log metadata for pointwise/reduction kernels. E.g., model name, kernel path, numel, rnumel, reduction hint
  202. MetricTable.register_table(
  203. "kernel_metadata",
  204. [
  205. "kernel_name",
  206. "kernel_path",
  207. "kernel_category", # pointwise/reduction/foreach etc.
  208. "size_hints",
  209. "reduction_hint",
  210. "line_of_code",
  211. "num_load",
  212. "num_store",
  213. "num_for_loop",
  214. "num_atomic_add",
  215. "num_args",
  216. # xyz numel can be different to size_hints since size_hints are rounded
  217. # up to the nearest power of 2.
  218. # Inductor kernel will burn in the xyz numel in kernel code for static
  219. # shape kernels.
  220. # Logging them will be helpful to find unaligned shape for reduction
  221. "xnumel",
  222. "ynumel",
  223. "rnumel",
  224. "kernel_args_num_gb",
  225. ],
  226. )
  227. def _parse_kernel_fn_code(kernel_module_code: str) -> str:
  228. """
  229. The kernel_module_code is the python module that contains kernel function code.
  230. kernel function is the proper triton kernel function annotated with
  231. @triton.jit
  232. """
  233. from .codecache import PyCodeCache
  234. from .wrapper_benchmark import get_triton_kernel
  235. mod = PyCodeCache.load(kernel_module_code)
  236. kernel = get_triton_kernel(mod)
  237. # kernel is a CachingAutotune; kernel.fn is the JITFunction;
  238. # kernel.fn.fn is the function being decorate by triton.jit
  239. return inspect.getsource(kernel.fn.fn)
  240. def _parse_kernel_line_of_code(proper_kernel_fn_code: str) -> int:
  241. """
  242. Return the line of code for the kernel excluding the decorators.
  243. """
  244. return len(proper_kernel_fn_code.splitlines())
  245. def _parse_size_hints(kernel_module_code: str, kernel_category: str) -> Optional[str]:
  246. if kernel_category == "foreach":
  247. # foreach kernel does not have size_hints
  248. return None
  249. m = re.search(r"size_hints=(\[[0-9, ]*\]),", kernel_module_code)
  250. assert m, "size_hints missing!"
  251. return m.group(1)
  252. def _parse_reduction_hint(
  253. kernel_category: str, kernel_module_code: str
  254. ) -> Optional[str]:
  255. if kernel_category not in ("reduction", "persistent_reduction"):
  256. return None
  257. m = re.search(r"reduction_hint=ReductionHint\.(\w*),", kernel_module_code)
  258. assert m, "reduction_hint not found in kernel source code!"
  259. return m.group(1)
  260. def _count_pattern(proper_kernel_fn_code: str, pattern: str) -> int:
  261. return proper_kernel_fn_code.count(pattern)
  262. def _count_args(proper_kernel_fn_code: str) -> int:
  263. def_line = proper_kernel_fn_code.splitlines()[0]
  264. assert def_line.startswith("def ")
  265. start_idx = def_line.index("(")
  266. end_idx = def_line.index("):")
  267. decl_csv = def_line[start_idx + 1 : end_idx]
  268. comps = decl_csv.split(",")
  269. return len(comps)
  270. def _parse_proper_kernel_fn_code(kernel_fn_code: str) -> str:
  271. """
  272. Skip decorators.
  273. """
  274. start_pos = kernel_fn_code.index("def ")
  275. return kernel_fn_code[start_pos:]
  276. def _parse_numel(proper_kernel_fn_code: str, numel_arg_name: str) -> Optional[int]:
  277. m = re.search(f"{numel_arg_name} = ([\\d]+)", proper_kernel_fn_code)
  278. if m:
  279. return int(m.group(1))
  280. else:
  281. return None
  282. def _parse_kernel_args_num_gb(
  283. kernel_fn_code: str, kernel_category: str
  284. ) -> Optional[float]:
  285. """
  286. inductor meta looks like:
  287. inductor_meta={... 'mutated_arg_names': [], 'no_x_dim': False, 'kernel_num_gb': 2.0},
  288. """
  289. m = re.search(r".kernel_num_gb.:\s*([0-9.]+)", kernel_fn_code)
  290. if m:
  291. return float(m.group(1))
  292. else:
  293. """
  294. There are a few cases that kernel_num_gdb field can be missing:
  295. 1. the field will be missing if config.benchmark_kernel and
  296. config.profile_bandwidth are false
  297. 2. even if config.benchmark_kernel or config.profile_bandwidth is true.
  298. foreach kernel does not have kernel_num_gb field in the metadata
  299. """
  300. return None
  301. def log_kernel_metadata(
  302. kernel_name: str, kernel_path: str, kernel_module_code: str
  303. ) -> None:
  304. """
  305. An utility to log kernel metadata. We may parse metadata from kernel source code here.
  306. It's fine to parse the generated kernel code here since the logging is
  307. disabled by default. It would hurt compilation time.
  308. """
  309. from .wrapper_benchmark import get_kernel_category_by_source_code
  310. kernel_category = get_kernel_category_by_source_code(kernel_module_code)
  311. reduction_hint = _parse_reduction_hint(kernel_category, kernel_module_code)
  312. size_hints = _parse_size_hints(kernel_module_code, kernel_category)
  313. kernel_fn_code = _parse_kernel_fn_code(kernel_module_code)
  314. proper_kernel_fn_code = _parse_proper_kernel_fn_code(kernel_fn_code)
  315. # the line of code excluding the decortors
  316. kernel_line_of_code = _parse_kernel_line_of_code(proper_kernel_fn_code)
  317. get_metric_table("kernel_metadata").add_row(
  318. lambda: {
  319. "kernel_name": kernel_name,
  320. "kernel_path": kernel_path,
  321. "kernel_category": kernel_category,
  322. "size_hints": size_hints,
  323. "reduction_hint": reduction_hint,
  324. "line_of_code": kernel_line_of_code,
  325. "num_load": _count_pattern(proper_kernel_fn_code, "tl.load"),
  326. "num_store": _count_pattern(proper_kernel_fn_code, "tl.store"),
  327. "num_for_loop": _count_pattern(proper_kernel_fn_code, "for "),
  328. "num_atomic_add": _count_pattern(proper_kernel_fn_code, "tl.atomic_add"),
  329. "num_args": _count_args(proper_kernel_fn_code),
  330. "xnumel": _parse_numel(proper_kernel_fn_code, "xnumel"),
  331. "ynumel": _parse_numel(proper_kernel_fn_code, "ynumel"),
  332. "rnumel": _parse_numel(proper_kernel_fn_code, "rnumel"),
  333. "kernel_args_num_gb": _parse_kernel_args_num_gb(
  334. kernel_fn_code, kernel_category
  335. ),
  336. }
  337. )
  338. def purge_old_log_files() -> None:
  339. """
  340. Purge the old log file at the beginning when the benchmark script runs.
  341. Should do it in the parent process rather than the child processes running
  342. each individual model.
  343. """
  344. for name, table in REGISTERED_METRIC_TABLES.items():
  345. if name in enabled_metric_tables():
  346. filename = table.output_filename()
  347. if os.path.exists(filename):
  348. os.unlink(filename)
  349. table.write_header()
  350. def enabled_metric_tables() -> OrderedSet[str]:
  351. return enabled_metric_tables_impl(config.enabled_metric_tables)
  352. @lru_cache
  353. def enabled_metric_tables_impl(config_str: str) -> OrderedSet[str]:
  354. enabled: OrderedSet[str] = OrderedSet()
  355. for name in config_str.split(","):
  356. name = name.strip()
  357. if not name:
  358. continue
  359. assert name in REGISTERED_METRIC_TABLES, (
  360. f"Metric table name {name} is not registered"
  361. )
  362. enabled.add(name)
  363. return enabled
  364. def is_metric_table_enabled(name: str) -> bool:
  365. return name in enabled_metric_tables()
  366. def get_metric_table(name: str) -> MetricTable:
  367. assert name in REGISTERED_METRIC_TABLES, f"Metric table {name} is not defined"
  368. return REGISTERED_METRIC_TABLES[name]