hipify_python.py 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176
  1. #!/usr/bin/env python3
  2. # mypy: allow-untyped-defs
  3. """ The Python Hipify script.
  4. ##
  5. # Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved.
  6. # 2017-2018 Advanced Micro Devices, Inc. and
  7. # Facebook Inc. All rights reserved.
  8. #
  9. # Permission is hereby granted, free of charge, to any person obtaining a copy
  10. # of this software and associated documentation files (the "Software"), to deal
  11. # in the Software without restriction, including without limitation the rights
  12. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. # copies of the Software, and to permit persons to whom the Software is
  14. # furnished to do so, subject to the following conditions:
  15. #
  16. # The above copyright notice and this permission notice shall be included in
  17. # all copies or substantial portions of the Software.
  18. #
  19. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. # THE SOFTWARE.
  26. """
  27. import argparse
  28. import fnmatch
  29. import re
  30. import shutil
  31. import sys
  32. import os
  33. from . import constants
  34. from .cuda_to_hip_mappings import CUDA_TO_HIP_MAPPINGS
  35. from .cuda_to_hip_mappings import MATH_TRANSPILATIONS
  36. from typing import Optional
  37. from collections.abc import Iterator
  38. from collections.abc import Mapping, Iterable
  39. from enum import Enum
  40. import functools
  41. import hashlib
  42. class CurrentState(Enum):
  43. INITIALIZED = 1
  44. DONE = 2
  45. class HipifyResult:
  46. def __init__(self, current_state, hipified_path):
  47. self.current_state = current_state
  48. self.hipified_path = hipified_path
  49. self.status = ""
  50. def __str__(self):
  51. return (f"HipifyResult:: current_state: {self.current_state}, hipified_path : {self.hipified_path}, status: {self.status}")
  52. HipifyFinalResult = dict[str, HipifyResult]
  53. HIPIFY_C_BREADCRUMB = "// !!! This is a file automatically generated by hipify!!!\n"
  54. HIPIFY_FINAL_RESULT: HipifyFinalResult = {}
  55. # Hardcode the PyTorch template map
  56. """This dictionary provides the mapping from PyTorch kernel template types
  57. to their actual types."""
  58. PYTORCH_TEMPLATE_MAP = {"Dtype": "scalar_t", "T": "scalar_t"}
  59. __all__ = ['InputError', 'openf', 'bcolors', 'GeneratedFileCleaner', 'match_extensions', 'matched_files_iter',
  60. 'preprocess_file_and_save_result', 'compute_stats', 'add_dim3', 'processKernelLaunches', 'find_closure_group',
  61. 'find_bracket_group', 'find_parentheses_group', 'replace_math_functions', 'hip_header_magic', 'replace_extern_shared',
  62. 'get_hip_file_path', 'is_out_of_place', 'is_pytorch_file', 'is_cusparse_file', 'is_special_file', 'is_caffe2_gpu_file',
  63. 'is_caffe2_gpu_file', 'Trie', 'preprocessor', 'file_specific_replacement', 'file_add_header',
  64. 'fix_static_global_kernels', 'extract_arguments', 'str2bool', 'CurrentState', 'HipifyResult', 'hipify']
  65. class InputError(Exception):
  66. # Exception raised for errors in the input.
  67. def __init__(self, message):
  68. super().__init__(message)
  69. self.message = message
  70. def __str__(self):
  71. return f"Input error: {self.message}"
  72. def openf(filename, mode):
  73. return open(filename, mode, errors='ignore')
  74. # Color coding for printing
  75. class bcolors:
  76. HEADER = '\033[95m'
  77. OKBLUE = '\033[94m'
  78. OKGREEN = '\033[92m'
  79. WARNING = '\033[93m'
  80. FAIL = '\033[91m'
  81. ENDC = '\033[0m'
  82. BOLD = '\033[1m'
  83. UNDERLINE = '\033[4m'
  84. # To the programmer, the output of hipify most likely are intermediates.
  85. # This class allows users of hipify to ask for a cleanup by running the
  86. # hipify and compilation in a with instantiating this context manager class
  87. # with keep_intermediates=False.
  88. # The main usecase is the cpp_extensions, specifically the load method.
  89. # It is a good idea to keep intermediates (in case of errors or to
  90. # not recompile unchanged files), but in cases where you don't want to
  91. # keep them (e.g. in the CI), this can be used to remove files.
  92. class GeneratedFileCleaner:
  93. """Context Manager to clean up generated files"""
  94. def __init__(self, keep_intermediates=False):
  95. self.keep_intermediates = keep_intermediates
  96. self.files_to_clean = set()
  97. self.dirs_to_clean = []
  98. def __enter__(self):
  99. return self
  100. def open(self, fn, *args, **kwargs):
  101. if not os.path.exists(fn):
  102. self.files_to_clean.add(os.path.abspath(fn))
  103. return open(fn, *args, **kwargs)
  104. def makedirs(self, dn, exist_ok=False):
  105. parent, n = os.path.split(dn)
  106. if not n:
  107. parent, n = os.path.split(parent)
  108. if parent and n and not os.path.exists(parent):
  109. self.makedirs(parent, exist_ok=True)
  110. if not os.path.isdir(dn) or not exist_ok:
  111. os.mkdir(dn)
  112. self.dirs_to_clean.append(os.path.abspath(dn))
  113. def __exit__(self, type, value, traceback):
  114. if not self.keep_intermediates:
  115. for f in self.files_to_clean:
  116. os.unlink(f)
  117. for d in self.dirs_to_clean[::-1]:
  118. os.rmdir(d)
  119. # Follow UNIX convention for paths to use '/' instead of '\\' on Windows
  120. def _to_unix_path(path: str) -> str:
  121. return path.replace(os.sep, '/')
  122. def match_extensions(filename: str, extensions: Iterable) -> bool:
  123. """Helper method to see if filename ends with certain extension"""
  124. return any(filename.endswith(e) for e in extensions)
  125. def _fnmatch(filepath, patterns):
  126. return any(fnmatch.fnmatch(filepath, pattern) for pattern in patterns)
  127. def matched_files_iter(
  128. root_path: str,
  129. includes: Iterable = (),
  130. ignores: Iterable = (),
  131. extensions: Iterable = (),
  132. out_of_place_only: bool = False,
  133. is_pytorch_extension: bool = False) -> Iterator[str]:
  134. exact_matches = set(includes)
  135. # This is a very rough heuristic; really, we want to avoid scanning
  136. # any file which is not checked into source control, but this script
  137. # needs to work even if you're in a Git or Hg checkout, so easier to
  138. # just block the biggest time sinks that won't matter in the
  139. # end.
  140. for (abs_dirpath, dirs, filenames) in os.walk(root_path, topdown=True):
  141. rel_dirpath = os.path.relpath(abs_dirpath, root_path)
  142. if rel_dirpath == '.':
  143. # Blah blah blah O(n) blah blah
  144. if ".git" in dirs:
  145. dirs.remove(".git")
  146. if "build" in dirs:
  147. dirs.remove("build")
  148. if "third_party" in dirs:
  149. dirs.remove("third_party")
  150. dirs.append("third_party/nvfuser")
  151. for filename in filenames:
  152. filepath = _to_unix_path(os.path.join(abs_dirpath, filename))
  153. rel_filepath = _to_unix_path(os.path.join(rel_dirpath, filename))
  154. # We respect extensions, UNLESS you wrote the entire
  155. # filename verbatim, in which case we always accept it
  156. if (
  157. _fnmatch(filepath, includes)
  158. and (not _fnmatch(filepath, ignores))
  159. and (match_extensions(filepath, extensions) or filepath in exact_matches)
  160. ):
  161. if not is_pytorch_extension: # for pytorch extensions, consider all files
  162. if not is_pytorch_file(rel_filepath) and not is_caffe2_gpu_file(rel_filepath):
  163. continue
  164. if out_of_place_only and not is_out_of_place(rel_filepath):
  165. continue
  166. yield filepath
  167. def preprocess_file_and_save_result(
  168. output_directory: str,
  169. filepath: str,
  170. all_files: Iterable,
  171. header_include_dirs: Iterable,
  172. stats: dict[str, list],
  173. hip_clang_launch: bool,
  174. is_pytorch_extension: bool,
  175. clean_ctx: GeneratedFileCleaner,
  176. show_progress: bool) -> None:
  177. fin_path = os.path.abspath(os.path.join(output_directory, filepath))
  178. hipify_result = HipifyResult(current_state=CurrentState.INITIALIZED, hipified_path=fin_path)
  179. HIPIFY_FINAL_RESULT[fin_path] = hipify_result
  180. result = preprocessor(output_directory, filepath, all_files, header_include_dirs, stats,
  181. hip_clang_launch, is_pytorch_extension, clean_ctx, show_progress)
  182. # Show what happened
  183. if show_progress and "ignored" not in result.status:
  184. print(
  185. fin_path, "->",
  186. result.hipified_path, result.status, flush=True)
  187. HIPIFY_FINAL_RESULT[fin_path] = result
  188. def compute_stats(stats):
  189. unsupported_calls = {cuda_call for (cuda_call, _filepath) in stats["unsupported_calls"]}
  190. # Print the number of unsupported calls
  191. print(f"Total number of unsupported CUDA function calls: {len(unsupported_calls):d}")
  192. # Print the list of unsupported calls
  193. print(", ".join(unsupported_calls))
  194. # Print the number of kernel launches
  195. print(f"\nTotal number of replaced kernel launches: {len(stats['kernel_launches']):d}")
  196. def add_dim3(kernel_string, cuda_kernel):
  197. '''adds dim3() to the second and third arguments in the kernel launch'''
  198. count = 0
  199. closure = 0
  200. kernel_string = kernel_string.replace("<<<", "").replace(">>>", "")
  201. arg_locs: list[dict[str, int]] = [{} for _ in range(2)]
  202. arg_locs[count]['start'] = 0
  203. for ind, c in enumerate(kernel_string):
  204. if count > 1:
  205. break
  206. if c == "(":
  207. closure += 1
  208. elif c == ")":
  209. closure -= 1
  210. if (c == "," or ind == len(kernel_string) - 1) and closure == 0:
  211. arg_locs[count]['end'] = ind + (c != ",")
  212. count += 1
  213. if count < 2:
  214. arg_locs[count]['start'] = ind + 1
  215. first_arg_raw = kernel_string[arg_locs[0]['start']:arg_locs[0]['end'] + 1]
  216. second_arg_raw = kernel_string[arg_locs[1]['start']:arg_locs[1]['end']]
  217. first_arg_clean = kernel_string[arg_locs[0]['start']:arg_locs[0]['end']].replace("\n", "").strip(" ")
  218. second_arg_clean = kernel_string[arg_locs[1]['start']:arg_locs[1]['end']].replace("\n", "").strip(" ")
  219. first_arg_dim3 = f"dim3({first_arg_clean})"
  220. second_arg_dim3 = f"dim3({second_arg_clean})"
  221. first_arg_raw_dim3 = first_arg_raw.replace(first_arg_clean, first_arg_dim3)
  222. second_arg_raw_dim3 = second_arg_raw.replace(second_arg_clean, second_arg_dim3)
  223. cuda_kernel = cuda_kernel.replace(first_arg_raw + second_arg_raw, first_arg_raw_dim3 + second_arg_raw_dim3)
  224. return cuda_kernel
  225. RE_KERNEL_LAUNCH = re.compile(r'([ ]+)(detail?)::[ ]+\\\n[ ]+')
  226. def processKernelLaunches(string, stats):
  227. """ Replace the CUDA style Kernel launches with the HIP style kernel launches."""
  228. # Concat the namespace with the kernel names. (Find cleaner way of doing this later).
  229. string = RE_KERNEL_LAUNCH.sub(lambda inp: f"{inp.group(1)}{inp.group(2)}::", string)
  230. def grab_method_and_template(in_kernel):
  231. # The positions for relevant kernel components.
  232. pos = {
  233. "kernel_launch": {"start": in_kernel["start"], "end": in_kernel["end"]},
  234. "kernel_name": {"start": -1, "end": -1},
  235. "template": {"start": -1, "end": -1}
  236. }
  237. # Count for balancing template
  238. count = {"<>": 0}
  239. # Status for whether we are parsing a certain item.
  240. START = 0
  241. AT_TEMPLATE = 1
  242. AFTER_TEMPLATE = 2
  243. AT_KERNEL_NAME = 3
  244. status = START
  245. # Parse the string character by character
  246. for i in range(pos["kernel_launch"]["start"] - 1, -1, -1):
  247. char = string[i]
  248. # Handle Templating Arguments
  249. if status in (START, AT_TEMPLATE):
  250. if char == ">":
  251. if status == START:
  252. status = AT_TEMPLATE
  253. pos["template"]["end"] = i
  254. count["<>"] += 1
  255. if char == "<":
  256. count["<>"] -= 1
  257. if count["<>"] == 0 and (status == AT_TEMPLATE):
  258. pos["template"]["start"] = i
  259. status = AFTER_TEMPLATE
  260. # Handle Kernel Name
  261. if status != AT_TEMPLATE:
  262. if string[i].isalnum() or string[i] in {'(', ')', '_', ':', '#'}:
  263. if status != AT_KERNEL_NAME:
  264. status = AT_KERNEL_NAME
  265. pos["kernel_name"]["end"] = i
  266. # Case: Kernel name starts the string.
  267. if i == 0:
  268. pos["kernel_name"]["start"] = 0
  269. # Finished
  270. return [(pos["kernel_name"]), (pos["template"]), (pos["kernel_launch"])]
  271. else:
  272. # Potential ending point if we're already traversing a kernel's name.
  273. if status == AT_KERNEL_NAME:
  274. pos["kernel_name"]["start"] = i
  275. # Finished
  276. return [(pos["kernel_name"]), (pos["template"]), (pos["kernel_launch"])]
  277. def find_kernel_bounds(string):
  278. """Finds the starting and ending points for all kernel launches in the string."""
  279. kernel_end = 0
  280. kernel_positions = []
  281. # Continue until we cannot find any more kernels anymore.
  282. while string.find("<<<", kernel_end) != -1:
  283. # Get kernel starting position (starting from the previous ending point)
  284. kernel_start = string.find("<<<", kernel_end)
  285. # Get kernel ending position (adjust end point past the >>>)
  286. kernel_end = string.find(">>>", kernel_start) + 3
  287. if kernel_end <= 0:
  288. raise InputError("no kernel end found")
  289. # Add to list of traversed kernels
  290. kernel_positions.append({"start": kernel_start, "end": kernel_end,
  291. "group": string[kernel_start: kernel_end]})
  292. return kernel_positions
  293. # Replace comments and string literals from the code so that find_kernel_bounds does not
  294. # wrongly capture kernels in comments and string literals.
  295. # This function replaces them with "x" to keep positions.
  296. def mask_comments(string):
  297. in_comment = ''
  298. prev_c = ''
  299. new_string = ''
  300. for c in string:
  301. if in_comment == '':
  302. # Outside comments
  303. if c == '/' and prev_c == '/':
  304. in_comment = '//'
  305. elif c == '*' and prev_c == '/':
  306. in_comment = '/*'
  307. elif c == '"' and prev_c != '\\' and prev_c != "'":
  308. in_comment = '"'
  309. elif in_comment == '//':
  310. # In // xxx
  311. if c == '\r' or c == '\n':
  312. in_comment = ''
  313. elif in_comment == '/*':
  314. # In /* xxx */
  315. if c == '/' and prev_c == '*':
  316. in_comment = ''
  317. elif in_comment == '"':
  318. # In ""
  319. if c == '"' and prev_c != '\\':
  320. in_comment = ''
  321. prev_c = c
  322. if in_comment == '':
  323. new_string += c
  324. else:
  325. new_string += 'x'
  326. return new_string
  327. # Grab positional ranges of all kernel launches
  328. get_kernel_positions = list(find_kernel_bounds(mask_comments(string)))
  329. output_string = string
  330. # Replace each CUDA kernel with a HIP kernel.
  331. for kernel in get_kernel_positions:
  332. # Get kernel components
  333. params = grab_method_and_template(kernel)
  334. # Find parenthesis after kernel launch
  335. parenthesis = string.find("(", kernel["end"])
  336. # Extract cuda kernel
  337. cuda_kernel = string[params[0]["start"]:parenthesis + 1]
  338. kernel_string = string[kernel['start']:kernel['end']]
  339. end_param_index = 0 if params[1]['end'] == -1 else 1
  340. kernel_name_with_template = string[params[0]['start']:params[end_param_index]['end'] + 1]
  341. cuda_kernel_dim3 = add_dim3(kernel_string, cuda_kernel)
  342. # Keep number of kernel launch params consistent (grid dims, group dims, stream, dynamic shared size)
  343. num_klp = len(extract_arguments(0, kernel["group"].replace("<<<", "(").replace(">>>", ")")))
  344. hip_kernel = "hipLaunchKernelGGL(" + cuda_kernel_dim3[0:-1].replace(
  345. ">>>", ", 0" * (4 - num_klp) + ">>>").replace("<<<", ", ").replace(
  346. ">>>", ", ").replace(kernel_name_with_template, "(" + kernel_name_with_template + ")")
  347. # Replace cuda kernel with hip kernel
  348. output_string = output_string.replace(cuda_kernel, hip_kernel)
  349. # Update the statistics
  350. stats["kernel_launches"].append(hip_kernel)
  351. return output_string
  352. def find_closure_group(input_string, start, group):
  353. """Generalization for finding a balancing closure group
  354. if group = ["(", ")"], then finds the first balanced parentheses.
  355. if group = ["{", "}"], then finds the first balanced bracket.
  356. Given an input string, a starting position in the input string, and the group type,
  357. find_closure_group returns the positions of group[0] and group[1] as a tuple.
  358. Example:
  359. >>> find_closure_group("(hi)", 0, ["(", ")"])
  360. (0, 3)
  361. """
  362. inside_parenthesis = False
  363. parens = 0
  364. pos = start
  365. p_start, p_end = -1, -1
  366. while pos < len(input_string):
  367. if input_string[pos] == group[0]:
  368. if inside_parenthesis is False:
  369. inside_parenthesis = True
  370. parens = 1
  371. p_start = pos
  372. else:
  373. parens += 1
  374. elif input_string[pos] == group[1] and inside_parenthesis:
  375. parens -= 1
  376. if parens == 0:
  377. p_end = pos
  378. return p_start, p_end
  379. pos += 1
  380. return None, None
  381. def find_bracket_group(input_string, start):
  382. """Finds the first balanced parentheses."""
  383. return find_closure_group(input_string, start, group=["{", "}"])
  384. def find_parentheses_group(input_string, start):
  385. """Finds the first balanced bracket."""
  386. return find_closure_group(input_string, start, group=["(", ")"])
  387. RE_ASSERT = re.compile(r"\bassert[ ]*\(")
  388. def replace_math_functions(input_string):
  389. """FIXME: Temporarily replace std:: invocations of math functions
  390. with non-std:: versions to prevent linker errors NOTE: This
  391. can lead to correctness issues when running tests, since the
  392. correct version of the math function (exp/expf) might not get
  393. called. Plan is to remove this function once HIP supports
  394. std:: math function calls inside device code
  395. """
  396. output_string = input_string
  397. for func in MATH_TRANSPILATIONS:
  398. output_string = output_string.replace(fr'{func}(', f'{MATH_TRANSPILATIONS[func]}(')
  399. return output_string
  400. RE_SYNCTHREADS = re.compile(r":?:?\b(__syncthreads)\b(\w*\()")
  401. def hip_header_magic(input_string):
  402. """If the file makes kernel builtin calls and does not include the cuda_runtime.h header,
  403. then automatically add an #include to match the "magic" includes provided by NVCC.
  404. TODO:
  405. Update logic to ignore cases where the cuda_runtime.h is included by another file.
  406. """
  407. # Copy the input.
  408. output_string = input_string
  409. # Check if one of the following headers is already included.
  410. headers = ["hip/hip_runtime.h", "hip/hip_runtime_api.h"]
  411. if any(re.search(fr'#include ("{ext}"|<{ext}>)', output_string) for ext in headers):
  412. return output_string
  413. # Rough logic to detect if we're inside device code
  414. hasDeviceLogic: int
  415. hasDeviceLogic = "hipLaunchKernelGGL" in output_string
  416. hasDeviceLogic += "__global__" in output_string
  417. hasDeviceLogic += "__shared__" in output_string
  418. hasDeviceLogic += RE_SYNCTHREADS.search(output_string) is not None
  419. # If device logic found, provide the necessary header.
  420. if hasDeviceLogic:
  421. output_string = '#include "hip/hip_runtime.h"\n' + input_string
  422. return output_string
  423. RE_EXTERN_SHARED = re.compile(r"extern\s+([\w\(\)]+)?\s*__shared__\s+([\w:<>\s]+)\s+(\w+)\s*\[\s*\]\s*;")
  424. def replace_extern_shared(input_string):
  425. """Match extern __shared__ type foo[]; syntax and use HIP_DYNAMIC_SHARED() MACRO instead.
  426. https://github.com/ROCm/hip/blob/master/docs/markdown/hip_kernel_language.md#__shared__
  427. Example:
  428. "extern __shared__ char smemChar[];" => "HIP_DYNAMIC_SHARED( char, smemChar)"
  429. "extern __shared__ unsigned char smem[];" => "HIP_DYNAMIC_SHARED( unsigned char, my_smem)"
  430. """
  431. output_string = input_string
  432. output_string = RE_EXTERN_SHARED.sub(
  433. lambda inp: f"HIP_DYNAMIC_SHARED({inp.group(1) or ''} {inp.group(2)}, {inp.group(3)})", output_string)
  434. return output_string
  435. def get_hip_file_path(rel_filepath, is_pytorch_extension=False):
  436. """
  437. Returns the new name of the hipified file
  438. """
  439. # At the moment, some PyTorch source files are HIPified in place. The predicate
  440. # is_out_of_place tells us if this is the case or not.
  441. assert not os.path.isabs(rel_filepath)
  442. if not is_pytorch_extension and not is_out_of_place(rel_filepath):
  443. return rel_filepath
  444. dirpath, filename = os.path.split(rel_filepath)
  445. root, ext = os.path.splitext(filename)
  446. # Here's the plan:
  447. #
  448. # In general, we need to disambiguate the HIPified filename so that
  449. # it gets a different name from the original filename, so
  450. # that we don't overwrite the original file
  451. #
  452. # There's a lot of different naming conventions across PyTorch
  453. # and Caffe2, but the general recipe is to convert occurrences
  454. # of cuda/gpu to hip, and add hip if there are no occurrences
  455. # of cuda/gpu anywhere.
  456. #
  457. # Concretely, we do the following:
  458. #
  459. # - If there is a directory component named "cuda", replace
  460. # it with "hip", AND
  461. #
  462. # - If the file name contains "CUDA", replace it with "HIP", AND
  463. #
  464. # - ALWAYS replace '.cu' with '.hip', because those files
  465. # contain CUDA kernels that needs to be hipified and processed with
  466. # hip compiler
  467. #
  468. # - If we are not hipifying a PyTorch extension, and the parent
  469. # directory name did not change as a result of the above
  470. # transformations, insert "hip" in the file path
  471. # as the direct parent folder of the file
  472. #
  473. # - If we are hipifying a PyTorch extension, and the parent directory
  474. # name as well as the filename (incl. extension) did not change as
  475. # a result of the above transformations, insert "_hip" in the filename
  476. #
  477. # This isn't set in stone; we might adjust this to support other
  478. # naming conventions.
  479. if ext == '.cu':
  480. ext = '.hip'
  481. orig_filename = filename
  482. orig_dirpath = dirpath
  483. dirpath = dirpath.replace('cuda', 'hip')
  484. dirpath = dirpath.replace('CUDA', 'HIP')
  485. dirpath = dirpath.replace('THC', 'THH')
  486. root = root.replace('cuda', 'hip')
  487. root = root.replace('CUDA', 'HIP')
  488. # Special case to handle caffe2/core/THCCachingAllocator
  489. if dirpath != "caffe2/core":
  490. root = root.replace('THC', 'THH')
  491. if not is_pytorch_extension and dirpath == orig_dirpath:
  492. dirpath = os.path.join(dirpath, 'hip')
  493. if is_pytorch_extension and dirpath == orig_dirpath and (root + ext) == orig_filename:
  494. root = root + "_hip"
  495. return os.path.join(dirpath, root + ext)
  496. def is_out_of_place(rel_filepath):
  497. assert not os.path.isabs(rel_filepath)
  498. if rel_filepath.startswith("torch/"):
  499. return False
  500. if rel_filepath.startswith("third_party/nvfuser/"):
  501. return False
  502. if rel_filepath.startswith("tools/autograd/templates/"):
  503. return False
  504. return True
  505. # Keep this synchronized with includes/ignores in build_amd.py
  506. def is_pytorch_file(rel_filepath):
  507. assert not os.path.isabs(rel_filepath)
  508. if rel_filepath.startswith("aten/"):
  509. if rel_filepath.startswith("aten/src/ATen/core/"):
  510. return False
  511. return True
  512. if rel_filepath.startswith("torch/"):
  513. return True
  514. if rel_filepath.startswith("third_party/nvfuser/"):
  515. return True
  516. if rel_filepath.startswith("tools/autograd/templates/"):
  517. return True
  518. return False
  519. def is_cusparse_file(rel_filepath):
  520. if is_pytorch_file(rel_filepath):
  521. return "sparse" in rel_filepath.lower()
  522. return False
  523. def is_special_file(rel_filepath):
  524. if is_pytorch_file(rel_filepath):
  525. if "sparse" in rel_filepath.lower():
  526. return True
  527. elif "linalg" in rel_filepath.lower():
  528. if "batchlinearalgebralibblas" in rel_filepath.lower():
  529. return False # don't use "special" mappings for this specific linalg cublas file
  530. return True
  531. return False
  532. def is_caffe2_gpu_file(rel_filepath):
  533. assert not os.path.isabs(rel_filepath)
  534. if rel_filepath.startswith("c10/cuda"):
  535. return True
  536. filename = os.path.basename(rel_filepath)
  537. _, ext = os.path.splitext(filename)
  538. return ('gpu' in filename or ext in ['.cu', '.cuh']) and ('cudnn' not in filename)
  539. class TrieNode:
  540. """A Trie node whose children are represented as a directory of char: TrieNode.
  541. A special char '' represents end of word
  542. """
  543. def __init__(self):
  544. self.children = {}
  545. class Trie:
  546. """Creates a Trie out of a list of words. The trie can be exported to a Regex pattern.
  547. The corresponding Regex should match much faster than a simple Regex union."""
  548. def __init__(self):
  549. """Initialize the trie with an empty root node."""
  550. self.root = TrieNode()
  551. self._hash = hashlib.md5(usedforsecurity=False)
  552. self._digest = self._hash.digest()
  553. def add(self, word):
  554. """Add a word to the Trie. """
  555. self._hash.update(word.encode())
  556. self._digest = self._hash.digest()
  557. node = self.root
  558. for char in word:
  559. node.children.setdefault(char, TrieNode())
  560. node = node.children[char]
  561. node.children[''] = True # Mark the end of the word
  562. def dump(self):
  563. """Return the root node of Trie. """
  564. return self.root
  565. def quote(self, char):
  566. """ Escape a char for regex. """
  567. return re.escape(char)
  568. def search(self, word):
  569. """Search whether word is present in the Trie.
  570. Returns True if yes, else return False"""
  571. node = self.root
  572. for char in word:
  573. if char in node.children:
  574. node = node.children[char]
  575. else:
  576. return False
  577. # make sure to check the end-of-word marker present
  578. return '' in node.children
  579. @functools.lru_cache # noqa: B019
  580. def _pattern(self, root, digest):
  581. """Convert a Trie into a regular expression pattern
  582. Memoized on the hash digest of the trie, which is built incrementally
  583. during add().
  584. """
  585. node = root
  586. if "" in node.children and len(node.children.keys()) == 1:
  587. return None
  588. alt = [] # store alternative patterns
  589. cc = [] # store char to char classes
  590. q = 0 # for node representing the end of word
  591. for char in sorted(node.children.keys()):
  592. if isinstance(node.children[char], TrieNode):
  593. try:
  594. recurse = self._pattern(node.children[char], self._digest)
  595. alt.append(self.quote(char) + recurse)
  596. except Exception:
  597. cc.append(self.quote(char))
  598. else:
  599. q = 1
  600. cconly = not len(alt) > 0
  601. if len(cc) > 0:
  602. if len(cc) == 1:
  603. alt.append(cc[0])
  604. else:
  605. alt.append('[' + ''.join(cc) + ']')
  606. if len(alt) == 1:
  607. result = alt[0]
  608. else:
  609. result = "(?:" + "|".join(alt) + ")"
  610. if q:
  611. if cconly:
  612. result += "?"
  613. else:
  614. result = f"(?:{result})?"
  615. return result
  616. def pattern(self):
  617. """Export the Trie to a regex pattern."""
  618. return self._pattern(self.root, self._digest)
  619. def export_to_regex(self):
  620. """Export the Trie to a regex pattern."""
  621. return self._pattern(self.root, self._digest)
  622. CAFFE2_TRIE = Trie()
  623. CAFFE2_MAP = {}
  624. PYTORCH_TRIE = Trie()
  625. PYTORCH_MAP: dict[str, object] = {}
  626. # In PyTorch, we map cuBLAS->rocBLAS and cuSPARSE->hipSPARSE. Note the prefix, roc versus hip.
  627. # The 'hip' APIs offer a more direct CUDA-friendly mapping, but calling rocBLAS directly has better performance.
  628. # Unfortunately, the roc* types and hip* types differ, i.e., rocblas_float_complex versus hipComplex.
  629. # In the case of SPARSE, we must use the hip types for complex instead of the roc types,
  630. # but the pytorch mappings assume roc. Therefore, we create a new SPARSE mapping that has a higher priority.
  631. # Its mappings will trigger first, and only when a miss occurs will the lower-priority pytorch mapping take place.
  632. # When a file contains "sparse" in the filename, a mapping marked with API_SPARSE is preferred over other choices.
  633. # Similarly, "linalg" files require rocBLAS -> hipSOLVER so they also need special handling.
  634. PYTORCH_SPECIAL_MAP = {}
  635. for mapping in CUDA_TO_HIP_MAPPINGS:
  636. assert isinstance(mapping, Mapping)
  637. for src, value in mapping.items():
  638. dst = value[0]
  639. meta_data = value[1:]
  640. if constants.API_CAFFE2 not in meta_data:
  641. PYTORCH_TRIE.add(src)
  642. # if src is already in PYTORCH_MAP and dst belongs to API_SPECIAL
  643. # do not overwrite PYTORCH_MAP, store dst separately
  644. if constants.API_SPECIAL in meta_data and PYTORCH_MAP.get(src, ""):
  645. PYTORCH_SPECIAL_MAP[src] = dst
  646. else:
  647. PYTORCH_MAP[src] = dst
  648. if constants.API_PYTORCH not in meta_data and constants.API_SPECIAL not in meta_data:
  649. CAFFE2_TRIE.add(src)
  650. CAFFE2_MAP[src] = dst
  651. RE_CAFFE2_PREPROCESSOR = re.compile(CAFFE2_TRIE.export_to_regex())
  652. RE_PYTORCH_PREPROCESSOR = re.compile(fr'(?<=\W)({PYTORCH_TRIE.export_to_regex()})(?=\W)')
  653. RE_QUOTE_HEADER = re.compile(r'#include "([^"]+)"')
  654. RE_ANGLE_HEADER = re.compile(r'#include <([^>]+)>')
  655. RE_THC_GENERIC_FILE = re.compile(r'#define THC_GENERIC_FILE "([^"]+)"')
  656. RE_CU_SUFFIX = re.compile(r'\.cu\b') # be careful not to pick up .cuh
  657. """
  658. Returns a HipifyResult object with the following details:
  659. "hipified_path" : absolute path of hipified source file
  660. "status" : "ok" if hipified file was written out
  661. "skipped" if an identical hipified file already existed or hipified file couldn't be written out
  662. "ignored" if the source file was a hipified file itself or not meant to be hipified
  663. "current_state" : CurrentState.INITIALIZED if source file is first ready to be hipified
  664. CurrentState.DONE if source file is done with hipification process
  665. """
  666. def preprocessor(
  667. output_directory: str,
  668. filepath: str,
  669. all_files: Iterable,
  670. header_include_dirs: Iterable,
  671. stats: dict[str, list],
  672. hip_clang_launch: bool,
  673. is_pytorch_extension: bool,
  674. clean_ctx: GeneratedFileCleaner,
  675. show_progress: bool) -> HipifyResult:
  676. """ Executes the CUDA -> HIP conversion on the specified file. """
  677. fin_path = os.path.abspath(os.path.join(output_directory, filepath))
  678. filepath = _to_unix_path(filepath)
  679. hipify_result = HIPIFY_FINAL_RESULT[fin_path]
  680. if filepath not in all_files:
  681. hipify_result.hipified_path = None
  682. hipify_result.status = "[ignored, not to be hipified]"
  683. hipify_result.current_state = CurrentState.DONE
  684. return hipify_result
  685. rel_filepath = _to_unix_path(os.path.relpath(filepath, output_directory))
  686. with open(fin_path, encoding='utf-8') as fin:
  687. if fin.readline() == HIPIFY_C_BREADCRUMB:
  688. hipify_result.hipified_path = None
  689. hipify_result.status = "[ignored, input is hipified output]"
  690. hipify_result.current_state = CurrentState.DONE
  691. return hipify_result
  692. fin.seek(0)
  693. output_source = fin.read()
  694. orig_output_source = output_source
  695. # get_hip_file_path needs a relative path to work correctly
  696. fout_path = os.path.abspath(os.path.join(output_directory, get_hip_file_path(rel_filepath, is_pytorch_extension)))
  697. if not os.path.exists(os.path.dirname(fout_path)):
  698. clean_ctx.makedirs(os.path.dirname(fout_path))
  699. # unsupported_calls statistics reporting is broken atm
  700. def pt_repl(m):
  701. return PYTORCH_MAP[m.group(0)]
  702. def pt_special_repl(m):
  703. # checks SPECIAL map first, and if a miss occurs, falls back to pytorch mappings
  704. return PYTORCH_SPECIAL_MAP.get(m.group(0), pt_repl(m))
  705. if is_pytorch_extension:
  706. output_source = RE_PYTORCH_PREPROCESSOR.sub(pt_repl, output_source)
  707. else:
  708. if is_special_file(rel_filepath):
  709. output_source = RE_PYTORCH_PREPROCESSOR.sub(pt_special_repl, output_source)
  710. elif is_pytorch_file(rel_filepath):
  711. output_source = RE_PYTORCH_PREPROCESSOR.sub(pt_repl, output_source)
  712. else:
  713. def c2_repl(m):
  714. return CAFFE2_MAP[m.group(0)]
  715. output_source = RE_CAFFE2_PREPROCESSOR.sub(c2_repl, output_source)
  716. # Header rewrites
  717. def mk_repl(templ, include_current_dir=True):
  718. def repl(m):
  719. f = m.group(1)
  720. filename = os.path.basename(f)
  721. if (
  722. f.startswith(("ATen/cuda",
  723. "ATen/native/cuda",
  724. "ATen/native/nested/cuda",
  725. "ATen/native/quantized/cuda",
  726. "ATen/native/sparse/cuda",
  727. "ATen/native/transformers/cuda",
  728. "THC/")) or
  729. (f.startswith("THC") and not f.startswith("THCP"))
  730. ):
  731. return templ.format(get_hip_file_path(m.group(1), is_pytorch_extension))
  732. # if filename is one of the files being hipified for this extension
  733. if (is_pytorch_extension and any(s.endswith(filename) for s in all_files)):
  734. header_dir = None
  735. header_filepath = None
  736. # If include_current_dir True, look first in same dir as the including source file
  737. if include_current_dir:
  738. header_dir_to_check = os.path.dirname(fin_path)
  739. header_path_to_check = os.path.abspath(os.path.join(header_dir_to_check, f))
  740. if os.path.exists(header_path_to_check):
  741. header_dir = header_dir_to_check
  742. header_filepath = header_path_to_check
  743. # If not found, look in include dirs one by one and first match wins
  744. if header_filepath is None:
  745. for header_include_dir in header_include_dirs:
  746. header_dir_to_check = os.path.join(output_directory, header_include_dir)
  747. header_path_to_check = os.path.abspath(os.path.join(header_dir_to_check, f))
  748. if os.path.exists(header_path_to_check):
  749. header_dir = header_dir_to_check
  750. header_filepath = header_path_to_check
  751. # If header file not found, keep as is
  752. if header_filepath is None:
  753. return m.group(0)
  754. # Hipify header file first if needed
  755. if header_filepath not in HIPIFY_FINAL_RESULT:
  756. preprocess_file_and_save_result(output_directory,
  757. header_filepath,
  758. all_files, header_include_dirs, stats, hip_clang_launch,
  759. is_pytorch_extension, clean_ctx, show_progress)
  760. elif header_filepath in HIPIFY_FINAL_RESULT:
  761. header_result = HIPIFY_FINAL_RESULT[header_filepath]
  762. if header_result.current_state == CurrentState.INITIALIZED:
  763. # get_hip_file_path needs a relative path to work correctly
  764. header_rel_path = os.path.relpath(header_filepath, output_directory)
  765. header_fout_path = os.path.abspath(os.path.join(output_directory,
  766. get_hip_file_path(header_rel_path, is_pytorch_extension)))
  767. header_result.hipified_path = header_fout_path
  768. HIPIFY_FINAL_RESULT[header_filepath] = header_result
  769. return templ.format(os.path.relpath(header_fout_path if header_fout_path is not None
  770. else header_filepath, header_dir))
  771. hipified_header_filepath = HIPIFY_FINAL_RESULT[header_filepath].hipified_path
  772. return templ.format(_to_unix_path(os.path.relpath(hipified_header_filepath if hipified_header_filepath is not None
  773. else header_filepath, header_dir)))
  774. return m.group(0)
  775. return repl
  776. output_source = RE_QUOTE_HEADER.sub(mk_repl('#include "{0}"', True), output_source)
  777. output_source = RE_ANGLE_HEADER.sub(mk_repl('#include <{0}>', False), output_source)
  778. output_source = RE_THC_GENERIC_FILE.sub(mk_repl('#define THC_GENERIC_FILE "{0}"'), output_source)
  779. # CMakeLists.txt rewrites
  780. if filepath.endswith('CMakeLists.txt'):
  781. output_source = output_source.replace('CUDA', 'HIP')
  782. output_source = output_source.replace('THC', 'THH')
  783. output_source = RE_CU_SUFFIX.sub('.hip', output_source)
  784. # Perform Kernel Launch Replacements
  785. if not hip_clang_launch:
  786. output_source = processKernelLaunches(output_source, stats)
  787. # Replace std:: with non-std:: versions
  788. if (filepath.endswith((".cu", ".cuh"))) and "PowKernel" not in filepath:
  789. output_source = replace_math_functions(output_source)
  790. # Include header if device code is contained.
  791. output_source = hip_header_magic(output_source)
  792. # Replace the extern __shared__
  793. # NOTE: No longer needed after transition from hcc to hipclang.
  794. # output_source = replace_extern_shared(output_source)
  795. # Don't write out identical hipified files for extensions if dirpath has not changed
  796. if (
  797. is_pytorch_extension
  798. and orig_output_source == output_source
  799. and os.path.dirname(fin_path) == os.path.dirname(fout_path)
  800. ):
  801. hipify_result.hipified_path = fin_path
  802. hipify_result.status = "[skipped, no changes]"
  803. hipify_result.current_state = CurrentState.DONE
  804. return hipify_result
  805. # Add hipify breadcrumb for C-style files to avoid re-hipification
  806. if fin_path != fout_path and match_extensions(fin_path, (".cu", ".cuh", ".c", ".cc", ".cpp", ".h", ".hpp")):
  807. output_source = HIPIFY_C_BREADCRUMB + output_source
  808. do_write = True
  809. if os.path.exists(fout_path):
  810. with open(fout_path, encoding='utf-8') as fout_old:
  811. do_write = fout_old.read() != output_source
  812. if do_write:
  813. try:
  814. with clean_ctx.open(fout_path, 'w', encoding='utf-8') as fout:
  815. fout.write(output_source)
  816. hipify_result.hipified_path = fout_path
  817. hipify_result.status = "[ok]"
  818. hipify_result.current_state = CurrentState.DONE
  819. return hipify_result
  820. except OSError as e:
  821. print(f'{bcolors.WARNING}Failed to save {fout_path} with "{e.strerror}", leaving {fin_path} unchanged.{bcolors.ENDC}',
  822. file=sys.stderr)
  823. hipify_result.hipified_path = fin_path
  824. hipify_result.status = "[skipped, no permissions]"
  825. hipify_result.current_state = CurrentState.DONE
  826. return hipify_result
  827. else:
  828. hipify_result.hipified_path = fout_path
  829. hipify_result.status = "[skipped, already hipified]"
  830. hipify_result.current_state = CurrentState.DONE
  831. return hipify_result
  832. def file_specific_replacement(filepath, search_string, replace_string, strict=False):
  833. with openf(filepath, "r+") as f:
  834. contents = f.read()
  835. if strict:
  836. contents = re.sub(fr'\b({re.escape(search_string)})\b', lambda x: replace_string, contents)
  837. else:
  838. contents = contents.replace(search_string, replace_string)
  839. f.seek(0)
  840. f.write(contents)
  841. f.truncate()
  842. def file_add_header(filepath, header):
  843. with openf(filepath, "r+") as f:
  844. contents = f.read()
  845. if header[0] != "<" and header[-1] != ">":
  846. header = f'"{header}"'
  847. contents = (f'#include {header} \n') + contents
  848. f.seek(0)
  849. f.write(contents)
  850. f.truncate()
  851. def fix_static_global_kernels(in_txt):
  852. """Static global kernels in HIP results in a compilation error."""
  853. in_txt = in_txt.replace(" __global__ static", "__global__")
  854. return in_txt
  855. RE_INCLUDE = re.compile(r"#include .*\n")
  856. def extract_arguments(start, string):
  857. """ Return the list of arguments in the upcoming function parameter closure.
  858. Example:
  859. string (input): '(blocks, threads, 0, THCState_getCurrentStream(state))'
  860. arguments (output):
  861. '[{'start': 1, 'end': 7},
  862. {'start': 8, 'end': 16},
  863. {'start': 17, 'end': 19},
  864. {'start': 20, 'end': 53}]'
  865. """
  866. arguments = []
  867. closures = {
  868. "<": 0,
  869. "(": 0
  870. }
  871. current_position = start
  872. argument_start_pos = current_position + 1
  873. # Search for final parenthesis
  874. while current_position < len(string):
  875. if string[current_position] == "(":
  876. closures["("] += 1
  877. elif string[current_position] == ")":
  878. closures["("] -= 1
  879. elif string[current_position] == "<":
  880. closures["<"] += 1
  881. elif string[current_position] == ">" and string[current_position - 1] != "-" and closures["<"] > 0:
  882. closures["<"] -= 1
  883. # Finished all arguments
  884. if closures["("] == 0 and closures["<"] == 0:
  885. # Add final argument
  886. arguments.append({"start": argument_start_pos, "end": current_position})
  887. break
  888. # Finished current argument
  889. if closures["("] == 1 and closures["<"] == 0 and string[current_position] == ",":
  890. arguments.append({"start": argument_start_pos, "end": current_position})
  891. argument_start_pos = current_position + 1
  892. current_position += 1
  893. return arguments
  894. def str2bool(v):
  895. """ArgumentParser doesn't support type=bool. Thus, this helper method will convert
  896. from possible string types to True / False."""
  897. if v.lower() in ('yes', 'true', 't', 'y', '1'):
  898. return True
  899. elif v.lower() in ('no', 'false', 'f', 'n', '0'):
  900. return False
  901. else:
  902. raise argparse.ArgumentTypeError('Boolean value expected.')
  903. def hipify(
  904. project_directory: str,
  905. show_detailed: bool = False,
  906. extensions: Iterable = (".cu", ".cuh", ".c", ".cc", ".cpp", ".h", ".in", ".hpp"),
  907. header_extensions: Iterable = (".cuh", ".h", ".hpp"),
  908. output_directory: str = "",
  909. header_include_dirs: Iterable = (),
  910. includes: Iterable = ('*',),
  911. extra_files: Iterable = (),
  912. out_of_place_only: bool = False,
  913. ignores: Iterable = (),
  914. show_progress: bool = True,
  915. hip_clang_launch: bool = False,
  916. is_pytorch_extension: bool = False,
  917. hipify_extra_files_only: bool = False,
  918. clean_ctx: Optional[GeneratedFileCleaner] = None
  919. ) -> HipifyFinalResult:
  920. if project_directory == "":
  921. project_directory = os.getcwd()
  922. # Verify the project directory exists.
  923. if not os.path.exists(project_directory):
  924. print("The project folder specified does not exist.")
  925. sys.exit(1)
  926. # If no output directory, provide a default one.
  927. if not output_directory:
  928. project_directory.rstrip("/")
  929. output_directory = project_directory + "_amd"
  930. if project_directory != output_directory:
  931. includes = [include.replace(project_directory, output_directory) for include in includes]
  932. ignores = [ignore.replace(project_directory, output_directory) for ignore in ignores]
  933. # Copy from project directory to output directory if not done already.
  934. if not os.path.exists(output_directory):
  935. shutil.copytree(project_directory, output_directory)
  936. includes = list(map(_to_unix_path, includes))
  937. ignores = list(map(_to_unix_path, ignores))
  938. all_files = list(matched_files_iter(output_directory, includes=includes,
  939. ignores=ignores, extensions=extensions,
  940. out_of_place_only=out_of_place_only,
  941. is_pytorch_extension=is_pytorch_extension))
  942. all_files_set = set(all_files)
  943. for f in extra_files:
  944. if not os.path.isabs(f):
  945. f = os.path.join(output_directory, f)
  946. if f not in all_files_set:
  947. all_files.append(f)
  948. # List all files in header_include_paths to ensure they are hipified
  949. from pathlib import Path
  950. for header_include_dir in header_include_dirs:
  951. if os.path.isabs(header_include_dir):
  952. header_include_dir_path = Path(header_include_dir)
  953. else:
  954. header_include_dir_path = Path(os.path.join(output_directory, header_include_dir))
  955. all_files.extend(
  956. str(path) for path in header_include_dir_path.rglob('*') if path.is_file()
  957. and _fnmatch(str(path), includes)
  958. and (not _fnmatch(str(path), ignores))
  959. and match_extensions(path.name, header_extensions)
  960. )
  961. if clean_ctx is None:
  962. clean_ctx = GeneratedFileCleaner(keep_intermediates=True)
  963. # Preprocessing statistics.
  964. stats: dict[str, list] = {"unsupported_calls": [], "kernel_launches": []}
  965. for filepath in (all_files if not hipify_extra_files_only else extra_files):
  966. preprocess_file_and_save_result(output_directory, filepath, all_files, header_include_dirs,
  967. stats, hip_clang_launch, is_pytorch_extension, clean_ctx, show_progress)
  968. print(bcolors.OKGREEN + "Successfully preprocessed all matching files." + bcolors.ENDC, file=sys.stderr)
  969. # Show detailed summary
  970. if show_detailed:
  971. compute_stats(stats)
  972. return HIPIFY_FINAL_RESULT