ZTWHHH commited on
Commit
fa301c8
·
verified ·
1 Parent(s): 48168ab

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. llava_next/lib/python3.10/site-packages/torch/utils/__pycache__/_cuda_trace.cpython-310.pyc +0 -0
  2. llava_next/lib/python3.10/site-packages/torch/utils/__pycache__/_foreach_utils.cpython-310.pyc +0 -0
  3. llava_next/lib/python3.10/site-packages/torch/utils/__pycache__/_mode_utils.cpython-310.pyc +0 -0
  4. llava_next/lib/python3.10/site-packages/torch/utils/__pycache__/_python_dispatch.cpython-310.pyc +0 -0
  5. llava_next/lib/python3.10/site-packages/torch/utils/__pycache__/_pytree.cpython-310.pyc +0 -0
  6. llava_next/lib/python3.10/site-packages/torch/utils/__pycache__/_stats.cpython-310.pyc +0 -0
  7. llava_next/lib/python3.10/site-packages/torch/utils/__pycache__/_traceback.cpython-310.pyc +0 -0
  8. llava_next/lib/python3.10/site-packages/torch/utils/__pycache__/bundled_inputs.cpython-310.pyc +0 -0
  9. llava_next/lib/python3.10/site-packages/torch/utils/__pycache__/checkpoint.cpython-310.pyc +0 -0
  10. llava_next/lib/python3.10/site-packages/torch/utils/__pycache__/collect_env.cpython-310.pyc +0 -0
  11. llava_next/lib/python3.10/site-packages/torch/utils/__pycache__/cpp_backtrace.cpython-310.pyc +0 -0
  12. llava_next/lib/python3.10/site-packages/torch/utils/__pycache__/mkldnn.cpython-310.pyc +0 -0
  13. llava_next/lib/python3.10/site-packages/torch/utils/__pycache__/throughput_benchmark.cpython-310.pyc +0 -0
  14. llava_next/lib/python3.10/site-packages/torch/utils/__pycache__/weak.cpython-310.pyc +0 -0
  15. llava_next/lib/python3.10/site-packages/torch/utils/backcompat/__init__.py +21 -0
  16. llava_next/lib/python3.10/site-packages/torch/utils/backcompat/__pycache__/__init__.cpython-310.pyc +0 -0
  17. llava_next/lib/python3.10/site-packages/torch/utils/bottleneck/__init__.py +0 -0
  18. llava_next/lib/python3.10/site-packages/torch/utils/bottleneck/__main__.py +229 -0
  19. llava_next/lib/python3.10/site-packages/torch/utils/bottleneck/__pycache__/__init__.cpython-310.pyc +0 -0
  20. llava_next/lib/python3.10/site-packages/torch/utils/bottleneck/__pycache__/__main__.cpython-310.pyc +0 -0
  21. llava_next/lib/python3.10/site-packages/torch/utils/hipify/__init__.py +1 -0
  22. llava_next/lib/python3.10/site-packages/torch/utils/hipify/__pycache__/__init__.cpython-310.pyc +0 -0
  23. llava_next/lib/python3.10/site-packages/torch/utils/hipify/__pycache__/constants.cpython-310.pyc +0 -0
  24. llava_next/lib/python3.10/site-packages/torch/utils/hipify/__pycache__/hipify_python.cpython-310.pyc +0 -0
  25. llava_next/lib/python3.10/site-packages/torch/utils/hipify/__pycache__/version.cpython-310.pyc +0 -0
  26. llava_next/lib/python3.10/site-packages/torch/utils/hipify/constants.py +61 -0
  27. llava_next/lib/python3.10/site-packages/torch/utils/hipify/cuda_to_hip_mappings.py +0 -0
  28. llava_next/lib/python3.10/site-packages/torch/utils/hipify/hipify_python.py +1129 -0
  29. llava_next/lib/python3.10/site-packages/torch/utils/hipify/version.py +1 -0
  30. llava_next/lib/python3.10/site-packages/torch/utils/jit/__init__.py +1 -0
  31. llava_next/lib/python3.10/site-packages/torch/utils/jit/__pycache__/__init__.cpython-310.pyc +0 -0
  32. llava_next/lib/python3.10/site-packages/torch/utils/jit/__pycache__/log_extract.cpython-310.pyc +0 -0
  33. llava_next/lib/python3.10/site-packages/torch/utils/jit/log_extract.py +113 -0
  34. llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/__pycache__/__init__.cpython-310.pyc +0 -0
  35. llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/__pycache__/_caffe2_graph.cpython-310.pyc +0 -0
  36. llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/__pycache__/_convert_np.cpython-310.pyc +0 -0
  37. llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/__pycache__/_embedding.cpython-310.pyc +0 -0
  38. llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/__pycache__/_onnx_graph.cpython-310.pyc +0 -0
  39. llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/__pycache__/_pytorch_graph.cpython-310.pyc +0 -0
  40. llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/__pycache__/_utils.cpython-310.pyc +0 -0
  41. llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/__pycache__/summary.cpython-310.pyc +0 -0
  42. llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/__pycache__/writer.cpython-310.pyc +0 -0
  43. llava_next/lib/python3.10/site-packages/torch/utils/viz/__init__.py +0 -0
  44. llava_next/lib/python3.10/site-packages/torch/utils/viz/__pycache__/__init__.cpython-310.pyc +0 -0
  45. llava_next/lib/python3.10/site-packages/torch/utils/viz/__pycache__/_cycles.cpython-310.pyc +0 -0
  46. llava_next/lib/python3.10/site-packages/torch/utils/viz/_cycles.py +446 -0
  47. vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/__init__.pyi +0 -0
  48. vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/storage.pyi +47 -0
  49. vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/uploadhandler.pyi +86 -0
  50. vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/handlers/base.pyi +13 -0
llava_next/lib/python3.10/site-packages/torch/utils/__pycache__/_cuda_trace.cpython-310.pyc ADDED
Binary file (3.87 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/__pycache__/_foreach_utils.cpython-310.pyc ADDED
Binary file (1.98 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/__pycache__/_mode_utils.cpython-310.pyc ADDED
Binary file (592 Bytes). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/__pycache__/_python_dispatch.cpython-310.pyc ADDED
Binary file (5.93 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/__pycache__/_pytree.cpython-310.pyc ADDED
Binary file (16.5 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/__pycache__/_stats.cpython-310.pyc ADDED
Binary file (832 Bytes). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/__pycache__/_traceback.cpython-310.pyc ADDED
Binary file (5.95 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/__pycache__/bundled_inputs.cpython-310.pyc ADDED
Binary file (17.1 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/__pycache__/checkpoint.cpython-310.pyc ADDED
Binary file (35.9 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/__pycache__/collect_env.cpython-310.pyc ADDED
Binary file (15.1 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/__pycache__/cpp_backtrace.cpython-310.pyc ADDED
Binary file (673 Bytes). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/__pycache__/mkldnn.cpython-310.pyc ADDED
Binary file (7 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/__pycache__/throughput_benchmark.cpython-310.pyc ADDED
Binary file (6.83 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/__pycache__/weak.cpython-310.pyc ADDED
Binary file (8.54 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/backcompat/__init__.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch._C import _set_backcompat_broadcast_warn
2
+ from torch._C import _get_backcompat_broadcast_warn
3
+ from torch._C import _set_backcompat_keepdim_warn
4
+ from torch._C import _get_backcompat_keepdim_warn
5
+
6
+
7
+ class Warning:
8
+ def __init__(self, setter, getter):
9
+ self.setter = setter
10
+ self.getter = getter
11
+
12
+ def set_enabled(self, value):
13
+ self.setter(value)
14
+
15
+ def get_enabled(self):
16
+ return self.getter()
17
+
18
+ enabled = property(get_enabled, set_enabled)
19
+
20
+ broadcast_warning = Warning(_set_backcompat_broadcast_warn, _get_backcompat_broadcast_warn)
21
+ keepdim_warning = Warning(_set_backcompat_keepdim_warn, _get_backcompat_keepdim_warn)
llava_next/lib/python3.10/site-packages/torch/utils/backcompat/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.07 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/bottleneck/__init__.py ADDED
File without changes
llava_next/lib/python3.10/site-packages/torch/utils/bottleneck/__main__.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import cProfile
3
+ import pstats
4
+ import sys
5
+ import os
6
+ from typing import Dict
7
+
8
+ import torch
9
+ from torch.autograd import profiler
10
+ from torch.utils.collect_env import get_env_info
11
+
12
+
13
+ def redirect_argv(new_argv):
14
+ sys.argv[:] = new_argv[:]
15
+
16
+
17
+ def compiled_with_cuda(sysinfo):
18
+ if sysinfo.cuda_compiled_version:
19
+ return f'compiled w/ CUDA {sysinfo.cuda_compiled_version}'
20
+ return 'not compiled w/ CUDA'
21
+
22
+
23
+ env_summary = """
24
+ --------------------------------------------------------------------------------
25
+ Environment Summary
26
+ --------------------------------------------------------------------------------
27
+ PyTorch {pytorch_version}{debug_str} {cuda_compiled}
28
+ Running with Python {py_version} and {cuda_runtime}
29
+
30
+ `{pip_version} list` truncated output:
31
+ {pip_list_output}
32
+ """.strip()
33
+
34
+
35
+ def run_env_analysis():
36
+ print('Running environment analysis...')
37
+ info = get_env_info()
38
+
39
+ result: Dict[str, str] = {}
40
+
41
+ debug_str = ''
42
+ if info.is_debug_build:
43
+ debug_str = ' DEBUG'
44
+
45
+ cuda_avail = ''
46
+ if info.is_cuda_available:
47
+ cuda = info.cuda_runtime_version
48
+ if cuda is not None:
49
+ cuda_avail = 'CUDA ' + cuda
50
+ else:
51
+ cuda = 'CUDA unavailable'
52
+
53
+ pip_version = info.pip_version
54
+ pip_list_output = info.pip_packages
55
+ if pip_list_output is None:
56
+ pip_list_output = 'Unable to fetch'
57
+
58
+ result = {
59
+ 'debug_str': debug_str,
60
+ 'pytorch_version': info.torch_version,
61
+ 'cuda_compiled': compiled_with_cuda(info),
62
+ 'py_version': f'{sys.version_info[0]}.{sys.version_info[1]}',
63
+ 'cuda_runtime': cuda_avail,
64
+ 'pip_version': pip_version,
65
+ 'pip_list_output': pip_list_output,
66
+ }
67
+
68
+ return env_summary.format(**result)
69
+
70
+
71
+ def run_cprofile(code, globs, launch_blocking=False):
72
+ print('Running your script with cProfile')
73
+ prof = cProfile.Profile()
74
+ prof.enable()
75
+ exec(code, globs, None)
76
+ prof.disable()
77
+ return prof
78
+
79
+
80
+ cprof_summary = """
81
+ --------------------------------------------------------------------------------
82
+ cProfile output
83
+ --------------------------------------------------------------------------------
84
+ """.strip()
85
+
86
+
87
+ def print_cprofile_summary(prof, sortby='tottime', topk=15):
88
+ print(cprof_summary)
89
+ cprofile_stats = pstats.Stats(prof).sort_stats(sortby)
90
+ cprofile_stats.print_stats(topk)
91
+
92
+
93
+ def run_autograd_prof(code, globs):
94
+ def run_prof(use_cuda=False):
95
+ with profiler.profile(use_cuda=use_cuda) as prof:
96
+ exec(code, globs, None)
97
+ return prof
98
+
99
+ print('Running your script with the autograd profiler...')
100
+ result = [run_prof(use_cuda=False)]
101
+ if torch.cuda.is_available():
102
+ result.append(run_prof(use_cuda=True))
103
+ else:
104
+ result.append(None)
105
+
106
+ return result
107
+
108
+
109
+ autograd_prof_summary = """
110
+ --------------------------------------------------------------------------------
111
+ autograd profiler output ({mode} mode)
112
+ --------------------------------------------------------------------------------
113
+ {description}
114
+ {cuda_warning}
115
+ {output}
116
+ """.strip()
117
+
118
+
119
+ def print_autograd_prof_summary(prof, mode, sortby='cpu_time', topk=15):
120
+ valid_sortby = ['cpu_time', 'cuda_time', 'cpu_time_total', 'cuda_time_total', 'count']
121
+ if sortby not in valid_sortby:
122
+ warn = ('WARNING: invalid sorting option for autograd profiler results: {}\n'
123
+ 'Expected `cpu_time`, `cpu_time_total`, or `count`. '
124
+ 'Defaulting to `cpu_time`.')
125
+ print(warn.format(sortby))
126
+ sortby = 'cpu_time'
127
+
128
+ if mode == 'CUDA':
129
+ cuda_warning = ('\n\tBecause the autograd profiler uses the CUDA event API,\n'
130
+ '\tthe CUDA time column reports approximately max(cuda_time, cpu_time).\n'
131
+ '\tPlease ignore this output if your code does not use CUDA.\n')
132
+ else:
133
+ cuda_warning = ''
134
+
135
+ sorted_events = sorted(prof.function_events,
136
+ key=lambda x: getattr(x, sortby), reverse=True)
137
+ topk_events = sorted_events[:topk]
138
+
139
+ result = {
140
+ 'mode': mode,
141
+ 'description': f'top {topk} events sorted by {sortby}',
142
+ 'output': torch.autograd.profiler_util._build_table(topk_events),
143
+ 'cuda_warning': cuda_warning
144
+ }
145
+
146
+ print(autograd_prof_summary.format(**result))
147
+
148
+
149
+ descript = """
150
+ `bottleneck` is a tool that can be used as an initial step for debugging
151
+ bottlenecks in your program.
152
+
153
+ It summarizes runs of your script with the Python profiler and PyTorch\'s
154
+ autograd profiler. Because your script will be profiled, please ensure that it
155
+ exits in a finite amount of time.
156
+
157
+ For more complicated uses of the profilers, please see
158
+ https://docs.python.org/3/library/profile.html and
159
+ https://pytorch.org/docs/master/autograd.html#profiler for more information.
160
+ """.strip()
161
+
162
+
163
+ def parse_args():
164
+ parser = argparse.ArgumentParser(description=descript)
165
+ parser.add_argument('scriptfile', type=str,
166
+ help='Path to the script to be run. '
167
+ 'Usually run with `python path/to/script`.')
168
+ parser.add_argument('args', type=str, nargs=argparse.REMAINDER,
169
+ help='Command-line arguments to be passed to the script.')
170
+ return parser.parse_args()
171
+
172
+
173
+ def cpu_time_total(autograd_prof):
174
+ return sum([event.cpu_time_total for event in autograd_prof.function_events])
175
+
176
+
177
+ def main():
178
+ args = parse_args()
179
+
180
+ # Customizable constants.
181
+ scriptfile = args.scriptfile
182
+ scriptargs = [] if args.args is None else args.args
183
+ scriptargs.insert(0, scriptfile)
184
+ cprofile_sortby = 'tottime'
185
+ cprofile_topk = 15
186
+ autograd_prof_sortby = 'cpu_time_total'
187
+ autograd_prof_topk = 15
188
+
189
+ redirect_argv(scriptargs)
190
+
191
+ sys.path.insert(0, os.path.dirname(scriptfile))
192
+ with open(scriptfile, 'rb') as stream:
193
+ code = compile(stream.read(), scriptfile, 'exec')
194
+ globs = {
195
+ '__file__': scriptfile,
196
+ '__name__': '__main__',
197
+ '__package__': None,
198
+ '__cached__': None,
199
+ }
200
+
201
+ print(descript)
202
+
203
+ env_summary = run_env_analysis()
204
+
205
+ if torch.cuda.is_available():
206
+ torch.cuda.init()
207
+ cprofile_prof = run_cprofile(code, globs)
208
+ autograd_prof_cpu, autograd_prof_cuda = run_autograd_prof(code, globs)
209
+
210
+ print(env_summary)
211
+ print_cprofile_summary(cprofile_prof, cprofile_sortby, cprofile_topk)
212
+
213
+ if not torch.cuda.is_available():
214
+ print_autograd_prof_summary(autograd_prof_cpu, 'CPU', autograd_prof_sortby, autograd_prof_topk)
215
+ return
216
+
217
+ # Print both the result of the CPU-mode and CUDA-mode autograd profilers
218
+ # if their execution times are very different.
219
+ cuda_prof_exec_time = cpu_time_total(autograd_prof_cuda)
220
+ if len(autograd_prof_cpu.function_events) > 0:
221
+ cpu_prof_exec_time = cpu_time_total(autograd_prof_cpu)
222
+ pct_diff = (cuda_prof_exec_time - cpu_prof_exec_time) / cuda_prof_exec_time
223
+ if abs(pct_diff) > 0.05:
224
+ print_autograd_prof_summary(autograd_prof_cpu, 'CPU', autograd_prof_sortby, autograd_prof_topk)
225
+
226
+ print_autograd_prof_summary(autograd_prof_cuda, 'CUDA', autograd_prof_sortby, autograd_prof_topk)
227
+
228
+ if __name__ == '__main__':
229
+ main()
llava_next/lib/python3.10/site-packages/torch/utils/bottleneck/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (178 Bytes). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/bottleneck/__pycache__/__main__.cpython-310.pyc ADDED
Binary file (6.79 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/hipify/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .version import __version__
llava_next/lib/python3.10/site-packages/torch/utils/hipify/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (217 Bytes). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/hipify/__pycache__/constants.cpython-310.pyc ADDED
Binary file (1.74 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/hipify/__pycache__/hipify_python.cpython-310.pyc ADDED
Binary file (28.4 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/hipify/__pycache__/version.cpython-310.pyc ADDED
Binary file (194 Bytes). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/hipify/constants.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Constants for annotations in the mapping.
2
+ The constants defined here are used to annotate the mapping tuples in cuda_to_hip_mappings.py.
3
+ They are based on
4
+ https://github.com/ROCm-Developer-Tools/HIP/blob/master/hipify-clang/src/Statistics.h
5
+ and fall in three categories: 1) type of mapping, 2) API of mapping, 3) unsupported
6
+ mapping.
7
+ """
8
+
9
+ CONV_VERSION = 0,
10
+ CONV_INIT = 1
11
+ CONV_DEVICE = 2
12
+ CONV_MEM = 3
13
+ CONV_KERN = 4
14
+ CONV_COORD_FUNC = 5
15
+ CONV_MATH_FUNC = 6
16
+ CONV_DEVICE_FUNC = 7
17
+ CONV_SPECIAL_FUNC = 8
18
+ CONV_STREAM = 9
19
+ CONV_EVENT = 10
20
+ CONV_OCCUPANCY = 11
21
+ CONV_CONTEXT = 12
22
+ CONV_PEER = 13
23
+ CONV_MODULE = 14
24
+ CONV_CACHE = 15
25
+ CONV_EXEC = 16
26
+ CONV_ERROR = 17
27
+ CONV_DEF = 18
28
+ CONV_TEX = 19
29
+ CONV_GL = 20
30
+ CONV_GRAPHICS = 21
31
+ CONV_SURFACE = 22
32
+ CONV_JIT = 23
33
+ CONV_D3D9 = 24
34
+ CONV_D3D10 = 25
35
+ CONV_D3D11 = 26
36
+ CONV_VDPAU = 27
37
+ CONV_EGL = 28
38
+ CONV_THREAD = 29
39
+ CONV_OTHER = 30
40
+ CONV_INCLUDE = 31
41
+ CONV_INCLUDE_CUDA_MAIN_H = 32
42
+ CONV_TYPE = 33
43
+ CONV_LITERAL = 34
44
+ CONV_NUMERIC_LITERAL = 35
45
+ CONV_LAST = 36
46
+
47
+ API_DRIVER = 37
48
+ API_RUNTIME = 38
49
+ API_BLAS = 39
50
+ API_SPECIAL = 40
51
+ API_RAND = 41
52
+ API_LAST = 42
53
+ API_FFT = 43
54
+ API_RTC = 44
55
+ API_ROCTX = 45
56
+
57
+ HIP_UNSUPPORTED = 46
58
+ API_PYTORCH = 1337
59
+ API_CAFFE2 = 1338
60
+ API_C10 = 1339
61
+ API_ROCMSMI = 1340
llava_next/lib/python3.10/site-packages/torch/utils/hipify/cuda_to_hip_mappings.py ADDED
The diff for this file is too large to render. See raw diff
 
llava_next/lib/python3.10/site-packages/torch/utils/hipify/hipify_python.py ADDED
@@ -0,0 +1,1129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ The Python Hipify script.
3
+ ##
4
+ # Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved.
5
+ # 2017-2018 Advanced Micro Devices, Inc. and
6
+ # Facebook Inc. All rights reserved.
7
+ #
8
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ # of this software and associated documentation files (the "Software"), to deal
10
+ # in the Software without restriction, including without limitation the rights
11
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ # copies of the Software, and to permit persons to whom the Software is
13
+ # furnished to do so, subject to the following conditions:
14
+ #
15
+ # The above copyright notice and this permission notice shall be included in
16
+ # all copies or substantial portions of the Software.
17
+ #
18
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24
+ # THE SOFTWARE.
25
+ """
26
+ import argparse
27
+ import fnmatch
28
+ import re
29
+ import shutil
30
+ import sys
31
+ import os
32
+
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
+
37
+ from typing import Dict, List, Iterator, Optional
38
+ from collections.abc import Mapping, Iterable
39
+ from enum import Enum
40
+
41
+ class CurrentState(Enum):
42
+ INITIALIZED = 1
43
+ DONE = 2
44
+
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
+
51
+ def __str__(self):
52
+ return ("HipifyResult:: current_state: {}, hipified_path : {}, status: {}".format(self.current_state,
53
+ self.hipified_path, self.status))
54
+
55
+ HipifyFinalResult = Dict[str, HipifyResult]
56
+ HIPIFY_C_BREADCRUMB = "// !!! This is a file automatically generated by hipify!!!\n"
57
+ HIPIFY_FINAL_RESULT: HipifyFinalResult = {}
58
+
59
+ # Hardcode the PyTorch template map
60
+ """This dictionary provides the mapping from PyTorch kernel template types
61
+ to their actual types."""
62
+ PYTORCH_TEMPLATE_MAP = {"Dtype": "scalar_t", "T": "scalar_t"}
63
+
64
+ __all__ = ['InputError', 'openf', 'bcolors', 'GeneratedFileCleaner', 'match_extensions', 'matched_files_iter',
65
+ 'preprocess_file_and_save_result', 'compute_stats', 'add_dim3', 'processKernelLaunches', 'find_closure_group',
66
+ 'find_bracket_group', 'find_parentheses_group', 'replace_math_functions', 'hip_header_magic', 'replace_extern_shared',
67
+ 'get_hip_file_path', 'is_out_of_place', 'is_pytorch_file', 'is_cusparse_file', 'is_special_file', 'is_caffe2_gpu_file',
68
+ 'is_caffe2_gpu_file', 'Trie', 'preprocessor', 'file_specific_replacement', 'file_add_header',
69
+ 'fix_static_global_kernels', 'extract_arguments', 'str2bool', 'CurrentState', 'HipifyResult', 'hipify']
70
+
71
+
72
+ class InputError(Exception):
73
+ # Exception raised for errors in the input.
74
+
75
+ def __init__(self, message):
76
+ super().__init__(message)
77
+ self.message = message
78
+
79
+ def __str__(self):
80
+ return f"Input error: {self.message}"
81
+
82
+
83
+ def openf(filename, mode):
84
+ return open(filename, mode, errors='ignore')
85
+
86
+
87
+ # Color coding for printing
88
+ class bcolors:
89
+ HEADER = '\033[95m'
90
+ OKBLUE = '\033[94m'
91
+ OKGREEN = '\033[92m'
92
+ WARNING = '\033[93m'
93
+ FAIL = '\033[91m'
94
+ ENDC = '\033[0m'
95
+ BOLD = '\033[1m'
96
+ UNDERLINE = '\033[4m'
97
+
98
+
99
+ # To the programmer, the output of hipify most likely are intermediates.
100
+ # This class allows users of hipify to ask for a cleanup by running the
101
+ # hipify and compilation in a with instantiating this context manager class
102
+ # with keep_intermediates=False.
103
+ # The main usecase is the cpp_extensions, specifically the load method.
104
+ # It is a good idea to keep intermediates (in case of errors or to
105
+ # not recompile unchanged files), but in cases where you don't want to
106
+ # keep them (e.g. in the CI), this can be used to remove files.
107
+ class GeneratedFileCleaner:
108
+ """Context Manager to clean up generated files"""
109
+ def __init__(self, keep_intermediates=False):
110
+ self.keep_intermediates = keep_intermediates
111
+ self.files_to_clean = set()
112
+ self.dirs_to_clean = []
113
+
114
+ def __enter__(self):
115
+ return self
116
+
117
+ def open(self, fn, *args, **kwargs):
118
+ if not os.path.exists(fn):
119
+ self.files_to_clean.add(os.path.abspath(fn))
120
+ return open(fn, *args, **kwargs)
121
+
122
+ def makedirs(self, dn, exist_ok=False):
123
+ parent, n = os.path.split(dn)
124
+ if not n:
125
+ parent, n = os.path.split(parent)
126
+ if parent and n and not os.path.exists(parent):
127
+ self.makedirs(parent, exist_ok=True)
128
+ if not os.path.isdir(dn) or not exist_ok:
129
+ os.mkdir(dn)
130
+ self.dirs_to_clean.append(os.path.abspath(dn))
131
+
132
+ def __exit__(self, type, value, traceback):
133
+ if not self.keep_intermediates:
134
+ for f in self.files_to_clean:
135
+ os.unlink(f)
136
+ for d in self.dirs_to_clean[::-1]:
137
+ os.rmdir(d)
138
+
139
+
140
+ def match_extensions(filename: str, extensions: Iterable) -> bool:
141
+ """Helper method to see if filename ends with certain extension"""
142
+ return any(filename.endswith(e) for e in extensions)
143
+
144
+
145
+ def _fnmatch(filepath, patterns):
146
+ return any(fnmatch.fnmatch(filepath, pattern) for pattern in patterns)
147
+
148
+
149
+ def matched_files_iter(
150
+ root_path: str,
151
+ includes: Iterable = (),
152
+ ignores: Iterable = (),
153
+ extensions: Iterable = (),
154
+ out_of_place_only: bool = False,
155
+ is_pytorch_extension: bool = False) -> Iterator[str]:
156
+
157
+ exact_matches = set(includes)
158
+
159
+ # This is a very rough heuristic; really, we want to avoid scanning
160
+ # any file which is not checked into source control, but this script
161
+ # needs to work even if you're in a Git or Hg checkout, so easier to
162
+ # just block the biggest time sinks that won't matter in the
163
+ # end.
164
+ for (abs_dirpath, dirs, filenames) in os.walk(root_path, topdown=True):
165
+ rel_dirpath = os.path.relpath(abs_dirpath, root_path)
166
+ if rel_dirpath == '.':
167
+ # Blah blah blah O(n) blah blah
168
+ if ".git" in dirs:
169
+ dirs.remove(".git")
170
+ if "build" in dirs:
171
+ dirs.remove("build")
172
+ if "third_party" in dirs:
173
+ dirs.remove("third_party")
174
+ dirs.append("third_party/nvfuser")
175
+ for filename in filenames:
176
+ filepath = os.path.join(abs_dirpath, filename)
177
+ rel_filepath = os.path.join(rel_dirpath, filename)
178
+ # We respect extensions, UNLESS you wrote the entire
179
+ # filename verbatim, in which case we always accept it
180
+ if (
181
+ _fnmatch(filepath, includes)
182
+ and (not _fnmatch(filepath, ignores))
183
+ and (match_extensions(filepath, extensions) or filepath in exact_matches)
184
+ ):
185
+ if not is_pytorch_extension: # for pytorch extensions, consider all files
186
+ if not is_pytorch_file(rel_filepath) and not is_caffe2_gpu_file(rel_filepath):
187
+ continue
188
+ if out_of_place_only and not is_out_of_place(rel_filepath):
189
+ continue
190
+ yield filepath
191
+
192
+
193
+ def preprocess_file_and_save_result(
194
+ output_directory: str,
195
+ filepath: str,
196
+ all_files: Iterable,
197
+ header_include_dirs: Iterable,
198
+ stats: Dict[str, List],
199
+ hip_clang_launch: bool,
200
+ is_pytorch_extension: bool,
201
+ clean_ctx: GeneratedFileCleaner,
202
+ show_progress: bool) -> None:
203
+ fin_path = os.path.abspath(os.path.join(output_directory, filepath))
204
+ hipify_result = HipifyResult(current_state=CurrentState.INITIALIZED, hipified_path=fin_path)
205
+ HIPIFY_FINAL_RESULT[fin_path] = hipify_result
206
+ result = preprocessor(output_directory, filepath, all_files, header_include_dirs, stats,
207
+ hip_clang_launch, is_pytorch_extension, clean_ctx, show_progress)
208
+
209
+ # Show what happened
210
+ if show_progress and "ignored" not in result.status:
211
+ print(
212
+ fin_path, "->",
213
+ result.hipified_path, result.status, flush=True)
214
+
215
+ HIPIFY_FINAL_RESULT[fin_path] = result
216
+
217
+
218
+ def compute_stats(stats):
219
+ unsupported_calls = {cuda_call for (cuda_call, _filepath) in stats["unsupported_calls"]}
220
+
221
+ # Print the number of unsupported calls
222
+ print(f"Total number of unsupported CUDA function calls: {len(unsupported_calls):d}")
223
+
224
+ # Print the list of unsupported calls
225
+ print(", ".join(unsupported_calls))
226
+
227
+ # Print the number of kernel launches
228
+ print(f"\nTotal number of replaced kernel launches: {len(stats['kernel_launches']):d}")
229
+
230
+
231
+ def add_dim3(kernel_string, cuda_kernel):
232
+ '''adds dim3() to the second and third arguments in the kernel launch'''
233
+ count = 0
234
+ closure = 0
235
+ kernel_string = kernel_string.replace("<<<", "").replace(">>>", "")
236
+ arg_locs: List[Dict[str, int]] = [{} for _ in range(2)]
237
+ arg_locs[count]['start'] = 0
238
+ for ind, c in enumerate(kernel_string):
239
+ if count > 1:
240
+ break
241
+ if c == "(":
242
+ closure += 1
243
+ elif c == ")":
244
+ closure -= 1
245
+ if (c == "," or ind == len(kernel_string) - 1) and closure == 0:
246
+ arg_locs[count]['end'] = ind + (c != ",")
247
+ count += 1
248
+ if count < 2:
249
+ arg_locs[count]['start'] = ind + 1
250
+
251
+ first_arg_raw = kernel_string[arg_locs[0]['start']:arg_locs[0]['end'] + 1]
252
+ second_arg_raw = kernel_string[arg_locs[1]['start']:arg_locs[1]['end']]
253
+
254
+ first_arg_clean = kernel_string[arg_locs[0]['start']:arg_locs[0]['end']].replace("\n", "").strip(" ")
255
+ second_arg_clean = kernel_string[arg_locs[1]['start']:arg_locs[1]['end']].replace("\n", "").strip(" ")
256
+
257
+ first_arg_dim3 = f"dim3({first_arg_clean})"
258
+ second_arg_dim3 = f"dim3({second_arg_clean})"
259
+
260
+ first_arg_raw_dim3 = first_arg_raw.replace(first_arg_clean, first_arg_dim3)
261
+ second_arg_raw_dim3 = second_arg_raw.replace(second_arg_clean, second_arg_dim3)
262
+ cuda_kernel = cuda_kernel.replace(first_arg_raw + second_arg_raw, first_arg_raw_dim3 + second_arg_raw_dim3)
263
+ return cuda_kernel
264
+
265
+
266
+ RE_KERNEL_LAUNCH = re.compile(r'([ ]+)(detail?)::[ ]+\\\n[ ]+')
267
+
268
+
269
+ def processKernelLaunches(string, stats):
270
+ """ Replace the CUDA style Kernel launches with the HIP style kernel launches."""
271
+ # Concat the namespace with the kernel names. (Find cleaner way of doing this later).
272
+ string = RE_KERNEL_LAUNCH.sub(lambda inp: f"{inp.group(1)}{inp.group(2)}::", string)
273
+
274
+ def grab_method_and_template(in_kernel):
275
+ # The positions for relevant kernel components.
276
+ pos = {
277
+ "kernel_launch": {"start": in_kernel["start"], "end": in_kernel["end"]},
278
+ "kernel_name": {"start": -1, "end": -1},
279
+ "template": {"start": -1, "end": -1}
280
+ }
281
+
282
+ # Count for balancing template
283
+ count = {"<>": 0}
284
+
285
+ # Status for whether we are parsing a certain item.
286
+ START = 0
287
+ AT_TEMPLATE = 1
288
+ AFTER_TEMPLATE = 2
289
+ AT_KERNEL_NAME = 3
290
+
291
+ status = START
292
+
293
+ # Parse the string character by character
294
+ for i in range(pos["kernel_launch"]["start"] - 1, -1, -1):
295
+ char = string[i]
296
+
297
+ # Handle Templating Arguments
298
+ if status in (START, AT_TEMPLATE):
299
+ if char == ">":
300
+ if status == START:
301
+ status = AT_TEMPLATE
302
+ pos["template"]["end"] = i
303
+ count["<>"] += 1
304
+
305
+ if char == "<":
306
+ count["<>"] -= 1
307
+ if count["<>"] == 0 and (status == AT_TEMPLATE):
308
+ pos["template"]["start"] = i
309
+ status = AFTER_TEMPLATE
310
+
311
+ # Handle Kernel Name
312
+ if status != AT_TEMPLATE:
313
+ if string[i].isalnum() or string[i] in {'(', ')', '_', ':', '#'}:
314
+ if status != AT_KERNEL_NAME:
315
+ status = AT_KERNEL_NAME
316
+ pos["kernel_name"]["end"] = i
317
+
318
+ # Case: Kernel name starts the string.
319
+ if i == 0:
320
+ pos["kernel_name"]["start"] = 0
321
+
322
+ # Finished
323
+ return [(pos["kernel_name"]), (pos["template"]), (pos["kernel_launch"])]
324
+
325
+ else:
326
+ # Potential ending point if we're already traversing a kernel's name.
327
+ if status == AT_KERNEL_NAME:
328
+ pos["kernel_name"]["start"] = i
329
+
330
+ # Finished
331
+ return [(pos["kernel_name"]), (pos["template"]), (pos["kernel_launch"])]
332
+
333
+ def find_kernel_bounds(string):
334
+ """Finds the starting and ending points for all kernel launches in the string."""
335
+ kernel_end = 0
336
+ kernel_positions = []
337
+
338
+ # Continue until we cannot find any more kernels anymore.
339
+ while string.find("<<<", kernel_end) != -1:
340
+ # Get kernel starting position (starting from the previous ending point)
341
+ kernel_start = string.find("<<<", kernel_end)
342
+
343
+ # Get kernel ending position (adjust end point past the >>>)
344
+ kernel_end = string.find(">>>", kernel_start) + 3
345
+ if kernel_end <= 0:
346
+ raise InputError("no kernel end found")
347
+
348
+ # Add to list of traversed kernels
349
+ kernel_positions.append({"start": kernel_start, "end": kernel_end,
350
+ "group": string[kernel_start: kernel_end]})
351
+
352
+ return kernel_positions
353
+
354
+ # Replace comments and string literals from the code so that find_kernel_bounds does not
355
+ # wrongly capture kernels in comments and string literals.
356
+ # This function replaces them with "x" to keep positions.
357
+ def mask_comments(string):
358
+ in_comment = ''
359
+ prev_c = ''
360
+ new_string = ''
361
+ for c in string:
362
+ if in_comment == '':
363
+ # Outside comments
364
+ if c == '/' and prev_c == '/':
365
+ in_comment = '//'
366
+ elif c == '*' and prev_c == '/':
367
+ in_comment = '/*'
368
+ elif c == '"' and prev_c != '\\' and prev_c != "'":
369
+ in_comment = '"'
370
+ elif in_comment == '//':
371
+ # In // xxx
372
+ if c == '\r' or c == '\n':
373
+ in_comment = ''
374
+ elif in_comment == '/*':
375
+ # In /* xxx */
376
+ if c == '/' and prev_c == '*':
377
+ in_comment = ''
378
+ elif in_comment == '"':
379
+ # In ""
380
+ if c == '"' and prev_c != '\\':
381
+ in_comment = ''
382
+ prev_c = c
383
+ if in_comment == '':
384
+ new_string += c
385
+ else:
386
+ new_string += 'x'
387
+ return new_string
388
+
389
+ # Grab positional ranges of all kernel launches
390
+ get_kernel_positions = list(find_kernel_bounds(mask_comments(string)))
391
+ output_string = string
392
+
393
+ # Replace each CUDA kernel with a HIP kernel.
394
+ for kernel in get_kernel_positions:
395
+ # Get kernel components
396
+ params = grab_method_and_template(kernel)
397
+
398
+ # Find parenthesis after kernel launch
399
+ parenthesis = string.find("(", kernel["end"])
400
+
401
+ # Extract cuda kernel
402
+ cuda_kernel = string[params[0]["start"]:parenthesis + 1]
403
+ kernel_string = string[kernel['start']:kernel['end']]
404
+ end_param_index = 0 if params[1]['end'] == -1 else 1
405
+ kernel_name_with_template = string[params[0]['start']:params[end_param_index]['end'] + 1]
406
+ cuda_kernel_dim3 = add_dim3(kernel_string, cuda_kernel)
407
+ # Keep number of kernel launch params consistent (grid dims, group dims, stream, dynamic shared size)
408
+ num_klp = len(extract_arguments(0, kernel["group"].replace("<<<", "(").replace(">>>", ")")))
409
+
410
+ hip_kernel = "hipLaunchKernelGGL(" + cuda_kernel_dim3[0:-1].replace(
411
+ ">>>", ", 0" * (4 - num_klp) + ">>>").replace("<<<", ", ").replace(
412
+ ">>>", ", ").replace(kernel_name_with_template, "(" + kernel_name_with_template + ")")
413
+
414
+ # Replace cuda kernel with hip kernel
415
+ output_string = output_string.replace(cuda_kernel, hip_kernel)
416
+
417
+ # Update the statistics
418
+ stats["kernel_launches"].append(hip_kernel)
419
+
420
+ return output_string
421
+
422
+
423
+ def find_closure_group(input_string, start, group):
424
+ """Generalization for finding a balancing closure group
425
+
426
+ if group = ["(", ")"], then finds the first balanced parentheses.
427
+ if group = ["{", "}"], then finds the first balanced bracket.
428
+
429
+ Given an input string, a starting position in the input string, and the group type,
430
+ find_closure_group returns the positions of group[0] and group[1] as a tuple.
431
+
432
+ Example:
433
+ >>> find_closure_group("(hi)", 0, ["(", ")"])
434
+ (0, 3)
435
+ """
436
+
437
+ inside_parenthesis = False
438
+ parens = 0
439
+ pos = start
440
+ p_start, p_end = -1, -1
441
+
442
+ while pos < len(input_string):
443
+ if input_string[pos] == group[0]:
444
+ if inside_parenthesis is False:
445
+ inside_parenthesis = True
446
+ parens = 1
447
+ p_start = pos
448
+ else:
449
+ parens += 1
450
+ elif input_string[pos] == group[1] and inside_parenthesis:
451
+ parens -= 1
452
+
453
+ if parens == 0:
454
+ p_end = pos
455
+ return p_start, p_end
456
+
457
+ pos += 1
458
+ return None, None
459
+
460
+
461
+ def find_bracket_group(input_string, start):
462
+ """Finds the first balanced parantheses."""
463
+ return find_closure_group(input_string, start, group=["{", "}"])
464
+
465
+
466
+ def find_parentheses_group(input_string, start):
467
+ """Finds the first balanced bracket."""
468
+ return find_closure_group(input_string, start, group=["(", ")"])
469
+
470
+
471
+ RE_ASSERT = re.compile(r"\bassert[ ]*\(")
472
+
473
+
474
+ def replace_math_functions(input_string):
475
+ """FIXME: Temporarily replace std:: invocations of math functions
476
+ with non-std:: versions to prevent linker errors NOTE: This
477
+ can lead to correctness issues when running tests, since the
478
+ correct version of the math function (exp/expf) might not get
479
+ called. Plan is to remove this function once HIP supports
480
+ std:: math function calls inside device code
481
+
482
+ """
483
+ output_string = input_string
484
+ for func in MATH_TRANSPILATIONS:
485
+ output_string = output_string.replace(fr'{func}(', f'{MATH_TRANSPILATIONS[func]}(')
486
+
487
+ return output_string
488
+
489
+
490
+ RE_SYNCTHREADS = re.compile(r":?:?\b(__syncthreads)\b(\w*\()")
491
+
492
+
493
+ def hip_header_magic(input_string):
494
+ """If the file makes kernel builtin calls and does not include the cuda_runtime.h header,
495
+ then automatically add an #include to match the "magic" includes provided by NVCC.
496
+ TODO:
497
+ Update logic to ignore cases where the cuda_runtime.h is included by another file.
498
+ """
499
+
500
+ # Copy the input.
501
+ output_string = input_string
502
+
503
+ # Check if one of the following headers is already included.
504
+ headers = ["hip/hip_runtime.h", "hip/hip_runtime_api.h"]
505
+ if any(re.search(fr'#include ("{ext}"|<{ext}>)', output_string) for ext in headers):
506
+ return output_string
507
+
508
+ # Rough logic to detect if we're inside device code
509
+ hasDeviceLogic: int
510
+ hasDeviceLogic = "hipLaunchKernelGGL" in output_string
511
+ hasDeviceLogic += "__global__" in output_string
512
+ hasDeviceLogic += "__shared__" in output_string
513
+ hasDeviceLogic += RE_SYNCTHREADS.search(output_string) is not None
514
+
515
+ # If device logic found, provide the necessary header.
516
+ if hasDeviceLogic:
517
+ output_string = '#include "hip/hip_runtime.h"\n' + input_string
518
+
519
+ return output_string
520
+
521
+
522
+ RE_EXTERN_SHARED = re.compile(r"extern\s+([\w\(\)]+)?\s*__shared__\s+([\w:<>\s]+)\s+(\w+)\s*\[\s*\]\s*;")
523
+
524
+
525
+ def replace_extern_shared(input_string):
526
+ """Match extern __shared__ type foo[]; syntax and use HIP_DYNAMIC_SHARED() MACRO instead.
527
+ https://github.com/ROCm-Developer-Tools/HIP/blob/master/docs/markdown/hip_kernel_language.md#__shared__
528
+ Example:
529
+ "extern __shared__ char smemChar[];" => "HIP_DYNAMIC_SHARED( char, smemChar)"
530
+ "extern __shared__ unsigned char smem[];" => "HIP_DYNAMIC_SHARED( unsigned char, my_smem)"
531
+ """
532
+ output_string = input_string
533
+ output_string = RE_EXTERN_SHARED.sub(
534
+ lambda inp: f"HIP_DYNAMIC_SHARED({inp.group(1) or ''} {inp.group(2)}, {inp.group(3)})", output_string)
535
+
536
+ return output_string
537
+
538
+
539
+ def get_hip_file_path(rel_filepath, is_pytorch_extension=False):
540
+ """
541
+ Returns the new name of the hipified file
542
+ """
543
+ # At the moment, some PyTorch source files are HIPified in place. The predicate
544
+ # is_out_of_place tells us if this is the case or not.
545
+ assert not os.path.isabs(rel_filepath)
546
+ if not is_pytorch_extension and not is_out_of_place(rel_filepath):
547
+ return rel_filepath
548
+
549
+ dirpath, filename = os.path.split(rel_filepath)
550
+ root, ext = os.path.splitext(filename)
551
+
552
+ # Here's the plan:
553
+ #
554
+ # In general, we need to disambiguate the HIPified filename so that
555
+ # it gets a different name from the original filename, so
556
+ # that we don't overwrite the original file
557
+ #
558
+ # There's a lot of different naming conventions across PyTorch
559
+ # and Caffe2, but the general recipe is to convert occurrences
560
+ # of cuda/gpu to hip, and add hip if there are no occurrences
561
+ # of cuda/gpu anywhere.
562
+ #
563
+ # Concretely, we do the following:
564
+ #
565
+ # - If there is a directory component named "cuda", replace
566
+ # it with "hip", AND
567
+ #
568
+ # - If the file name contains "CUDA", replace it with "HIP", AND
569
+ #
570
+ # - ALWAYS replace '.cu' with '.hip', because those files
571
+ # contain CUDA kernels that needs to be hipified and processed with
572
+ # hip compiler
573
+ #
574
+ # - If we are not hipifying a PyTorch extension, and the parent
575
+ # directory name did not change as a result of the above
576
+ # transformations, insert "hip" in the file path
577
+ # as the direct parent folder of the file
578
+ #
579
+ # - If we are hipifying a PyTorch extension, and the parent directory
580
+ # name as well as the filename (incl. extension) did not change as
581
+ # a result of the above transformations, insert "_hip" in the filename
582
+ #
583
+ # This isn't set in stone; we might adjust this to support other
584
+ # naming conventions.
585
+
586
+ if ext == '.cu':
587
+ ext = '.hip'
588
+
589
+ orig_filename = filename
590
+ orig_dirpath = dirpath
591
+
592
+ dirpath = dirpath.replace('cuda', 'hip')
593
+ dirpath = dirpath.replace('CUDA', 'HIP')
594
+ dirpath = dirpath.replace('THC', 'THH')
595
+
596
+ root = root.replace('cuda', 'hip')
597
+ root = root.replace('CUDA', 'HIP')
598
+ # Special case to handle caffe2/core/THCCachingAllocator
599
+ if dirpath != "caffe2/core":
600
+ root = root.replace('THC', 'THH')
601
+
602
+ if not is_pytorch_extension and dirpath == orig_dirpath:
603
+ dirpath = os.path.join(dirpath, 'hip')
604
+
605
+ if is_pytorch_extension and dirpath == orig_dirpath and (root + ext) == orig_filename:
606
+ root = root + "_hip"
607
+
608
+ return os.path.join(dirpath, root + ext)
609
+
610
+
611
+ def is_out_of_place(rel_filepath):
612
+ assert not os.path.isabs(rel_filepath)
613
+ if rel_filepath.startswith("torch/"):
614
+ return False
615
+ if rel_filepath.startswith("third_party/nvfuser/"):
616
+ return False
617
+ if rel_filepath.startswith("tools/autograd/templates/"):
618
+ return False
619
+ return True
620
+
621
+
622
+ # Keep this synchronized with includes/ignores in build_amd.py
623
+ def is_pytorch_file(rel_filepath):
624
+ assert not os.path.isabs(rel_filepath)
625
+ if rel_filepath.startswith("aten/"):
626
+ if rel_filepath.startswith("aten/src/ATen/core/"):
627
+ return False
628
+ return True
629
+ if rel_filepath.startswith("torch/"):
630
+ return True
631
+ if rel_filepath.startswith("third_party/nvfuser/"):
632
+ return True
633
+ if rel_filepath.startswith("tools/autograd/templates/"):
634
+ return True
635
+ return False
636
+
637
+
638
+ def is_cusparse_file(rel_filepath):
639
+ if is_pytorch_file(rel_filepath):
640
+ return "sparse" in rel_filepath.lower()
641
+ return False
642
+
643
+
644
+ def is_special_file(rel_filepath):
645
+ if is_pytorch_file(rel_filepath):
646
+ if "sparse" in rel_filepath.lower():
647
+ return True
648
+ elif "linalg" in rel_filepath.lower():
649
+ if "batchlinearalgebralibblas" in rel_filepath.lower():
650
+ return False # don't use "special" mappings for this specific linalg cublas file
651
+ return True
652
+ return False
653
+
654
+ def is_caffe2_gpu_file(rel_filepath):
655
+ assert not os.path.isabs(rel_filepath)
656
+ if rel_filepath.startswith("c10/cuda"):
657
+ return True
658
+ filename = os.path.basename(rel_filepath)
659
+ _, ext = os.path.splitext(filename)
660
+ return ('gpu' in filename or ext in ['.cu', '.cuh']) and ('cudnn' not in filename)
661
+
662
+
663
+ # Cribbed from https://stackoverflow.com/questions/42742810/speed-up-millions-of-regex-replacements-in-python-3/42789508#42789508
664
+ class Trie:
665
+ """Regex::Trie in Python. Creates a Trie out of a list of words. The trie can be exported to a Regex pattern.
666
+ The corresponding Regex should match much faster than a simple Regex union."""
667
+
668
+ def __init__(self):
669
+ self.data = {}
670
+
671
+ def add(self, word):
672
+ ref = self.data
673
+ for char in word:
674
+ ref[char] = char in ref and ref[char] or {}
675
+ ref = ref[char]
676
+ ref[''] = 1
677
+
678
+ def dump(self):
679
+ return self.data
680
+
681
+ def quote(self, char):
682
+ return re.escape(char)
683
+
684
+ def _pattern(self, pData):
685
+ data = pData
686
+ if "" in data and len(data.keys()) == 1:
687
+ return None
688
+
689
+ alt = []
690
+ cc = []
691
+ q = 0
692
+ for char in sorted(data.keys()):
693
+ if isinstance(data[char], dict):
694
+ try:
695
+ recurse = self._pattern(data[char])
696
+ alt.append(self.quote(char) + recurse)
697
+ except Exception:
698
+ cc.append(self.quote(char))
699
+ else:
700
+ q = 1
701
+ cconly = not len(alt) > 0
702
+
703
+ if len(cc) > 0:
704
+ if len(cc) == 1:
705
+ alt.append(cc[0])
706
+ else:
707
+ alt.append('[' + ''.join(cc) + ']')
708
+
709
+ if len(alt) == 1:
710
+ result = alt[0]
711
+ else:
712
+ result = "(?:" + "|".join(alt) + ")"
713
+
714
+ if q:
715
+ if cconly:
716
+ result += "?"
717
+ else:
718
+ result = f"(?:{result})?"
719
+ return result
720
+
721
+ def pattern(self):
722
+ return self._pattern(self.dump())
723
+
724
+
725
+ CAFFE2_TRIE = Trie()
726
+ CAFFE2_MAP = {}
727
+ PYTORCH_TRIE = Trie()
728
+ PYTORCH_MAP: Dict[str, object] = {}
729
+
730
+ # In PyTorch, we map cuBLAS->rocBLAS and cuSPARSE->hipSPARSE. Note the prefix, roc versus hip.
731
+ # The 'hip' APIs offer a more direct CUDA-friendly mapping, but calling rocBLAS directly has better performance.
732
+ # Unfortunately, the roc* types and hip* types differ, i.e., rocblas_float_complex versus hipComplex.
733
+ # In the case of SPARSE, we must use the hip types for complex instead of the roc types,
734
+ # but the pytorch mappings assume roc. Therefore, we create a new SPARSE mapping that has a higher priority.
735
+ # Its mappings will trigger first, and only when a miss occurs will the lower-priority pytorch mapping take place.
736
+ # When a file contains "sparse" in the filename, a mapping marked with API_SPARSE is preferred over other choices.
737
+ # Similarly, "linalg" files require rocBLAS -> hipSOLVER so they also need special handling.
738
+ PYTORCH_SPECIAL_MAP = {}
739
+
740
+ for mapping in CUDA_TO_HIP_MAPPINGS:
741
+ assert isinstance(mapping, Mapping)
742
+ for src, value in mapping.items():
743
+ dst = value[0]
744
+ meta_data = value[1:]
745
+ if constants.API_CAFFE2 not in meta_data:
746
+ PYTORCH_TRIE.add(src)
747
+ # if src is already in PYTORCH_MAP and dst belongs to API_SPECIAL
748
+ # do not overwrite PYTORCH_MAP, store dst separately
749
+ if constants.API_SPECIAL in meta_data and PYTORCH_MAP.get(src, ""):
750
+ PYTORCH_SPECIAL_MAP[src] = dst
751
+ else:
752
+ PYTORCH_MAP[src] = dst
753
+ if constants.API_PYTORCH not in meta_data and constants.API_SPECIAL not in meta_data:
754
+ CAFFE2_TRIE.add(src)
755
+ CAFFE2_MAP[src] = dst
756
+ RE_CAFFE2_PREPROCESSOR = re.compile(CAFFE2_TRIE.pattern())
757
+ RE_PYTORCH_PREPROCESSOR = re.compile(fr'(?<=\W)({PYTORCH_TRIE.pattern()})(?=\W)')
758
+
759
+ RE_QUOTE_HEADER = re.compile(r'#include "([^"]+)"')
760
+ RE_ANGLE_HEADER = re.compile(r'#include <([^>]+)>')
761
+ RE_THC_GENERIC_FILE = re.compile(r'#define THC_GENERIC_FILE "([^"]+)"')
762
+ RE_CU_SUFFIX = re.compile(r'\.cu\b') # be careful not to pick up .cuh
763
+
764
+ """
765
+ Returns a HipifyResult object with the following details:
766
+ "hipified_path" : absolute path of hipified source file
767
+ "status" : "ok" if hipified file was written out
768
+ "skipped" if an identical hipified file already existed or hipified file couldn't be written out
769
+ "ignored" if the source file was a hipified file itself or not meant to be hipified
770
+ "current_state" : CurrentState.INITIALIZED if source file is first ready to be hipified
771
+ CurrentState.DONE if source file is done with hipification process
772
+ """
773
+
774
+
775
+ def preprocessor(
776
+ output_directory: str,
777
+ filepath: str,
778
+ all_files: Iterable,
779
+ header_include_dirs: Iterable,
780
+ stats: Dict[str, List],
781
+ hip_clang_launch: bool,
782
+ is_pytorch_extension: bool,
783
+ clean_ctx: GeneratedFileCleaner,
784
+ show_progress: bool) -> HipifyResult:
785
+ """ Executes the CUDA -> HIP conversion on the specified file. """
786
+ fin_path = os.path.abspath(os.path.join(output_directory, filepath))
787
+ hipify_result = HIPIFY_FINAL_RESULT[fin_path]
788
+ if filepath not in all_files:
789
+ hipify_result.hipified_path = None
790
+ hipify_result.status = "[ignored, not to be hipified]"
791
+ hipify_result.current_state = CurrentState.DONE
792
+ return hipify_result
793
+
794
+ rel_filepath = os.path.relpath(filepath, output_directory)
795
+
796
+ with open(fin_path, encoding='utf-8') as fin:
797
+ if fin.readline() == HIPIFY_C_BREADCRUMB:
798
+ hipify_result.hipified_path = None
799
+ hipify_result.status = "[ignored, input is hipified output]"
800
+ hipify_result.current_state = CurrentState.DONE
801
+ return hipify_result
802
+ fin.seek(0)
803
+ output_source = fin.read()
804
+
805
+ orig_output_source = output_source
806
+
807
+ # get_hip_file_path needs a relative path to work correctly
808
+ fout_path = os.path.abspath(os.path.join(output_directory, get_hip_file_path(rel_filepath, is_pytorch_extension)))
809
+ if not os.path.exists(os.path.dirname(fout_path)):
810
+ clean_ctx.makedirs(os.path.dirname(fout_path))
811
+
812
+ # unsupported_calls statistics reporting is broken atm
813
+ def pt_repl(m):
814
+ return PYTORCH_MAP[m.group(0)]
815
+
816
+ def pt_special_repl(m):
817
+ # checks SPECIAL map first, and if a miss occurs, falls back to pytorch mappings
818
+ return PYTORCH_SPECIAL_MAP.get(m.group(0), pt_repl(m))
819
+
820
+
821
+ if is_pytorch_extension:
822
+ output_source = RE_PYTORCH_PREPROCESSOR.sub(pt_repl, output_source)
823
+ else:
824
+ if is_special_file(rel_filepath):
825
+ output_source = RE_PYTORCH_PREPROCESSOR.sub(pt_special_repl, output_source)
826
+ elif is_pytorch_file(rel_filepath):
827
+ output_source = RE_PYTORCH_PREPROCESSOR.sub(pt_repl, output_source)
828
+ else:
829
+ def c2_repl(m):
830
+ return CAFFE2_MAP[m.group(0)]
831
+ output_source = RE_CAFFE2_PREPROCESSOR.sub(c2_repl, output_source)
832
+
833
+ # Header rewrites
834
+ def mk_repl(templ, include_current_dir=True):
835
+ def repl(m):
836
+ f = m.group(1)
837
+ dirpath, filename = os.path.split(f)
838
+ if (
839
+ f.startswith(("ATen/cuda",
840
+ "ATen/native/cuda",
841
+ "ATen/native/nested/cuda",
842
+ "ATen/native/quantized/cuda",
843
+ "ATen/native/sparse/cuda",
844
+ "ATen/native/transformers/cuda",
845
+ "THC/")) or
846
+ (f.startswith("THC") and not f.startswith("THCP"))
847
+ ):
848
+ return templ.format(get_hip_file_path(m.group(1), is_pytorch_extension))
849
+ # if filename is one of the files being hipified for this extension
850
+ if (is_pytorch_extension and any(s.endswith(filename) for s in all_files)):
851
+ header_dir = None
852
+ header_filepath = None
853
+ # If include_current_dir True, look first in same dir as the including source file
854
+ if include_current_dir:
855
+ header_dir_to_check = os.path.dirname(fin_path)
856
+ header_path_to_check = os.path.abspath(os.path.join(header_dir_to_check, f))
857
+ if os.path.exists(header_path_to_check):
858
+ header_dir = header_dir_to_check
859
+ header_filepath = header_path_to_check
860
+ # If not found, look in include dirs one by one and first match wins
861
+ if header_filepath is None:
862
+ for header_include_dir in header_include_dirs:
863
+ header_dir_to_check = os.path.join(output_directory, header_include_dir)
864
+ header_path_to_check = os.path.abspath(os.path.join(header_dir_to_check, f))
865
+ if os.path.exists(header_path_to_check):
866
+ header_dir = header_dir_to_check
867
+ header_filepath = header_path_to_check
868
+ # If header file not found, keep as is
869
+ if header_filepath is None:
870
+ return m.group(0)
871
+ # Hipify header file first if needed
872
+ if header_filepath not in HIPIFY_FINAL_RESULT:
873
+ preprocess_file_and_save_result(output_directory,
874
+ header_filepath,
875
+ all_files, header_include_dirs, stats, hip_clang_launch,
876
+ is_pytorch_extension, clean_ctx, show_progress)
877
+ elif header_filepath in HIPIFY_FINAL_RESULT:
878
+ header_result = HIPIFY_FINAL_RESULT[header_filepath]
879
+ if header_result.current_state == CurrentState.INITIALIZED:
880
+ # get_hip_file_path needs a relative path to work correctly
881
+ header_rel_path = os.path.relpath(header_filepath, output_directory)
882
+ header_fout_path = os.path.abspath(os.path.join(output_directory,
883
+ get_hip_file_path(header_rel_path, is_pytorch_extension)))
884
+ header_result.hipified_path = header_fout_path
885
+ HIPIFY_FINAL_RESULT[header_filepath] = header_result
886
+ return templ.format(os.path.relpath(header_fout_path if header_fout_path is not None
887
+ else header_filepath, header_dir))
888
+ hipified_header_filepath = HIPIFY_FINAL_RESULT[header_filepath].hipified_path
889
+ return templ.format(os.path.relpath(hipified_header_filepath if hipified_header_filepath is not None
890
+ else header_filepath, header_dir))
891
+
892
+ return m.group(0)
893
+ return repl
894
+ output_source = RE_QUOTE_HEADER.sub(mk_repl('#include "{0}"', True), output_source)
895
+ output_source = RE_ANGLE_HEADER.sub(mk_repl('#include <{0}>', False), output_source)
896
+ output_source = RE_THC_GENERIC_FILE.sub(mk_repl('#define THC_GENERIC_FILE "{0}"'), output_source)
897
+
898
+ # CMakeLists.txt rewrites
899
+ if filepath.endswith('CMakeLists.txt'):
900
+ output_source = output_source.replace('CUDA', 'HIP')
901
+ output_source = output_source.replace('THC', 'THH')
902
+ output_source = RE_CU_SUFFIX.sub('.hip', output_source)
903
+
904
+ # Perform Kernel Launch Replacements
905
+ if not hip_clang_launch:
906
+ output_source = processKernelLaunches(output_source, stats)
907
+
908
+ # Replace std:: with non-std:: versions
909
+ if (filepath.endswith((".cu", ".cuh"))) and "PowKernel" not in filepath:
910
+ output_source = replace_math_functions(output_source)
911
+
912
+ # Include header if device code is contained.
913
+ output_source = hip_header_magic(output_source)
914
+
915
+ # Replace the extern __shared__
916
+ # NOTE: No longer needed after transition from hcc to hipclang.
917
+ # output_source = replace_extern_shared(output_source)
918
+
919
+ # Don't write out identical hipified files for extensions if dirpath has not changed
920
+ if (
921
+ is_pytorch_extension
922
+ and orig_output_source == output_source
923
+ and os.path.dirname(fin_path) == os.path.dirname(fout_path)
924
+ ):
925
+ hipify_result.hipified_path = fin_path
926
+ hipify_result.status = "[skipped, no changes]"
927
+ hipify_result.current_state = CurrentState.DONE
928
+ return hipify_result
929
+
930
+ # Add hipify breadcrumb for C-style files to avoid re-hipification
931
+ if fin_path != fout_path and match_extensions(fin_path, (".cu", ".cuh", ".c", ".cc", ".cpp", ".h", ".hpp")):
932
+ output_source = HIPIFY_C_BREADCRUMB + output_source
933
+
934
+ do_write = True
935
+ if os.path.exists(fout_path):
936
+ with open(fout_path, encoding='utf-8') as fout_old:
937
+ do_write = fout_old.read() != output_source
938
+ if do_write:
939
+ try:
940
+ with clean_ctx.open(fout_path, 'w', encoding='utf-8') as fout:
941
+ fout.write(output_source)
942
+ hipify_result.hipified_path = fout_path
943
+ hipify_result.status = "[ok]"
944
+ hipify_result.current_state = CurrentState.DONE
945
+ return hipify_result
946
+ except PermissionError as e:
947
+ print(f"{bcolors.WARNING}Failed to save {fout_path} with \"{e.strerror}\", leaving {fin_path} unchanged.{bcolors.ENDC}",
948
+ file=sys.stderr)
949
+ hipify_result.hipified_path = fin_path
950
+ hipify_result.status = "[skipped, no permissions]"
951
+ hipify_result.current_state = CurrentState.DONE
952
+ return hipify_result
953
+ else:
954
+ hipify_result.hipified_path = fout_path
955
+ hipify_result.status = "[skipped, already hipified]"
956
+ hipify_result.current_state = CurrentState.DONE
957
+ return hipify_result
958
+
959
+ def file_specific_replacement(filepath, search_string, replace_string, strict=False):
960
+ with openf(filepath, "r+") as f:
961
+ contents = f.read()
962
+ if strict:
963
+ contents = re.sub(fr'\b({re.escape(search_string)})\b', lambda x: replace_string, contents)
964
+ else:
965
+ contents = contents.replace(search_string, replace_string)
966
+ f.seek(0)
967
+ f.write(contents)
968
+ f.truncate()
969
+
970
+
971
+ def file_add_header(filepath, header):
972
+ with openf(filepath, "r+") as f:
973
+ contents = f.read()
974
+ if header[0] != "<" and header[-1] != ">":
975
+ header = f'"{header}"'
976
+ contents = (f'#include {header} \n') + contents
977
+ f.seek(0)
978
+ f.write(contents)
979
+ f.truncate()
980
+
981
+
982
+ def fix_static_global_kernels(in_txt):
983
+ """Static global kernels in HIP results in a compilation error."""
984
+ in_txt = in_txt.replace(" __global__ static", "__global__")
985
+ return in_txt
986
+
987
+
988
+ RE_INCLUDE = re.compile(r"#include .*\n")
989
+
990
+
991
+ def extract_arguments(start, string):
992
+ """ Return the list of arguments in the upcoming function parameter closure.
993
+ Example:
994
+ string (input): '(blocks, threads, 0, THCState_getCurrentStream(state))'
995
+ arguments (output):
996
+ '[{'start': 1, 'end': 7},
997
+ {'start': 8, 'end': 16},
998
+ {'start': 17, 'end': 19},
999
+ {'start': 20, 'end': 53}]'
1000
+ """
1001
+
1002
+ arguments = []
1003
+ closures = {
1004
+ "<": 0,
1005
+ "(": 0
1006
+ }
1007
+ current_position = start
1008
+ argument_start_pos = current_position + 1
1009
+
1010
+ # Search for final parenthesis
1011
+ while current_position < len(string):
1012
+ if string[current_position] == "(":
1013
+ closures["("] += 1
1014
+ elif string[current_position] == ")":
1015
+ closures["("] -= 1
1016
+ elif string[current_position] == "<":
1017
+ closures["<"] += 1
1018
+ elif string[current_position] == ">" and string[current_position - 1] != "-" and closures["<"] > 0:
1019
+ closures["<"] -= 1
1020
+
1021
+ # Finished all arguments
1022
+ if closures["("] == 0 and closures["<"] == 0:
1023
+ # Add final argument
1024
+ arguments.append({"start": argument_start_pos, "end": current_position})
1025
+ break
1026
+
1027
+ # Finished current argument
1028
+ if closures["("] == 1 and closures["<"] == 0 and string[current_position] == ",":
1029
+ arguments.append({"start": argument_start_pos, "end": current_position})
1030
+ argument_start_pos = current_position + 1
1031
+
1032
+ current_position += 1
1033
+
1034
+ return arguments
1035
+
1036
+
1037
+ def str2bool(v):
1038
+ """ArgumentParser doesn't support type=bool. Thus, this helper method will convert
1039
+ from possible string types to True / False."""
1040
+ if v.lower() in ('yes', 'true', 't', 'y', '1'):
1041
+ return True
1042
+ elif v.lower() in ('no', 'false', 'f', 'n', '0'):
1043
+ return False
1044
+ else:
1045
+ raise argparse.ArgumentTypeError('Boolean value expected.')
1046
+
1047
+
1048
+ def hipify(
1049
+ project_directory: str,
1050
+ show_detailed: bool = False,
1051
+ extensions: Iterable = (".cu", ".cuh", ".c", ".cc", ".cpp", ".h", ".in", ".hpp"),
1052
+ header_extensions: Iterable = (".cuh", ".h", ".hpp"),
1053
+ output_directory: str = "",
1054
+ header_include_dirs: Iterable = (),
1055
+ includes: Iterable = ('*',),
1056
+ extra_files: Iterable = (),
1057
+ out_of_place_only: bool = False,
1058
+ ignores: Iterable = (),
1059
+ show_progress: bool = True,
1060
+ hip_clang_launch: bool = False,
1061
+ is_pytorch_extension: bool = False,
1062
+ hipify_extra_files_only: bool = False,
1063
+ clean_ctx: Optional[GeneratedFileCleaner] = None
1064
+ ) -> HipifyFinalResult:
1065
+ if project_directory == "":
1066
+ project_directory = os.getcwd()
1067
+
1068
+ # Verify the project directory exists.
1069
+ if not os.path.exists(project_directory):
1070
+ print("The project folder specified does not exist.")
1071
+ sys.exit(1)
1072
+
1073
+ # If no output directory, provide a default one.
1074
+ if not output_directory:
1075
+ project_directory.rstrip("/")
1076
+ output_directory = project_directory + "_amd"
1077
+
1078
+ if project_directory != output_directory:
1079
+ includes = [include.replace(project_directory, output_directory) for include in includes]
1080
+ ignores = [ignore.replace(project_directory, output_directory) for ignore in ignores]
1081
+
1082
+ # Copy from project directory to output directory if not done already.
1083
+ if not os.path.exists(output_directory):
1084
+ shutil.copytree(project_directory, output_directory)
1085
+
1086
+ all_files = list(matched_files_iter(output_directory, includes=includes,
1087
+ ignores=ignores, extensions=extensions,
1088
+ out_of_place_only=out_of_place_only,
1089
+ is_pytorch_extension=is_pytorch_extension))
1090
+ all_files_set = set(all_files)
1091
+ for f in extra_files:
1092
+ if not os.path.isabs(f):
1093
+ f = os.path.join(output_directory, f)
1094
+ if f not in all_files_set:
1095
+ all_files.append(f)
1096
+
1097
+ # List all files in header_include_paths to ensure they are hipified
1098
+ from pathlib import Path
1099
+ for header_include_dir in header_include_dirs:
1100
+ if os.path.isabs(header_include_dir):
1101
+ header_include_dir_path = Path(header_include_dir)
1102
+ else:
1103
+ header_include_dir_path = Path(os.path.join(output_directory, header_include_dir))
1104
+ for path in header_include_dir_path.rglob('*'):
1105
+ if (
1106
+ path.is_file()
1107
+ and _fnmatch(str(path), includes)
1108
+ and (not _fnmatch(str(path), ignores))
1109
+ and match_extensions(path.name, header_extensions)
1110
+ ):
1111
+ all_files.append(str(path))
1112
+
1113
+ if clean_ctx is None:
1114
+ clean_ctx = GeneratedFileCleaner(keep_intermediates=True)
1115
+
1116
+ # Preprocessing statistics.
1117
+ stats: Dict[str, List] = {"unsupported_calls": [], "kernel_launches": []}
1118
+
1119
+ for filepath in (all_files if not hipify_extra_files_only else extra_files):
1120
+ preprocess_file_and_save_result(output_directory, filepath, all_files, header_include_dirs,
1121
+ stats, hip_clang_launch, is_pytorch_extension, clean_ctx, show_progress)
1122
+
1123
+ print(bcolors.OKGREEN + "Successfully preprocessed all matching files." + bcolors.ENDC, file=sys.stderr)
1124
+
1125
+ # Show detailed summary
1126
+ if show_detailed:
1127
+ compute_stats(stats)
1128
+
1129
+ return HIPIFY_FINAL_RESULT
llava_next/lib/python3.10/site-packages/torch/utils/hipify/version.py ADDED
@@ -0,0 +1 @@
 
 
1
+ __version__ = '1.0.0'
llava_next/lib/python3.10/site-packages/torch/utils/jit/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
llava_next/lib/python3.10/site-packages/torch/utils/jit/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (171 Bytes). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/jit/__pycache__/log_extract.cpython-310.pyc ADDED
Binary file (4.14 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/jit/log_extract.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from contextlib import contextmanager
2
+ from typing import Any, List, Tuple, cast
3
+ import random
4
+ import torch
5
+ import time
6
+ from torch.utils.benchmark import Timer
7
+
8
+ def extract_ir(filename: str) -> List[str]:
9
+ BEGIN = "<GRAPH_EXPORT>"
10
+ END = "</GRAPH_EXPORT>"
11
+ pfx = None
12
+ current = ""
13
+ graphs = []
14
+ with open(filename) as f:
15
+ split_strs = f.read().split(BEGIN)
16
+ for i, split_str in enumerate(split_strs):
17
+ if i == 0:
18
+ continue
19
+ end_loc = split_str.find(END)
20
+ if end_loc == -1:
21
+ continue
22
+ s = split_str[:end_loc]
23
+ pfx = split_strs[i - 1].splitlines()[-1]
24
+ lines = [x[len(pfx):] for x in s.splitlines(keepends=True)]
25
+ graphs.append(''.join(lines))
26
+
27
+ return graphs
28
+
29
+
30
+ def make_tensor_from_type(inp_type: torch._C.TensorType):
31
+ size = inp_type.sizes()
32
+ stride = inp_type.strides()
33
+ device = inp_type.device()
34
+ dtype = inp_type.dtype()
35
+ assert size is not None
36
+ assert stride is not None
37
+ assert device is not None
38
+ assert dtype is not None
39
+ return torch.empty_strided(size=size, stride=stride, device=device, dtype=dtype)
40
+
41
+ def load_graph_and_inputs(ir: str) -> Tuple[Any, List[Any]]:
42
+ graph = torch._C.parse_ir(ir, parse_tensor_constants=True)
43
+ graph.makeMultiOutputIntoTuple()
44
+ inputs = []
45
+ for inp in graph.inputs():
46
+ if isinstance(inp.type(), torch._C.FloatType):
47
+ inputs.append(random.uniform(.1, 100))
48
+ elif isinstance(inp.type(), torch._C.IntType):
49
+ inputs.append(random.randint(1, 100))
50
+ elif isinstance(inp.type(), torch._C.TensorType):
51
+ tensorType = cast(torch._C.TensorType, inp.type())
52
+ inputs.append(make_tensor_from_type(tensorType))
53
+ elif isinstance(inp.type(), torch._C.BoolType):
54
+ inputs.append(random.randint(0, 1) == 1)
55
+ else:
56
+ raise NotImplementedError(f"A default value is not implemented for type {inp.type()}")
57
+
58
+ func = torch._C._create_function_from_graph("forward", graph)
59
+ torch._C._jit_pass_erase_shape_information(func.graph)
60
+ return (func, inputs)
61
+
62
+ def time_cuda(fn, inputs, test_runs):
63
+ t = Timer(stmt="fn(*inputs)", globals={"fn": fn, "inputs" : inputs})
64
+ times = t.blocked_autorange()
65
+ return times.median * 1000 # time in ms
66
+
67
+ def time_cpu(fn, inputs, test_runs):
68
+ s = time.perf_counter()
69
+ for _ in range(test_runs):
70
+ fn(*inputs)
71
+ e = time.perf_counter()
72
+ return (e - s) / test_runs * 1000 # time in ms
73
+
74
+ def run_test(ir, inputs, *, warmup_runs=10, test_runs=20) -> float:
75
+ graph, _ = load_graph_and_inputs(ir)
76
+ for _ in range(warmup_runs):
77
+ graph(*inputs)
78
+
79
+ is_cpu = None
80
+ for input in inputs:
81
+ if isinstance(input, torch.Tensor):
82
+ is_cpu = input.device.type == "cpu"
83
+ break
84
+ assert is_cpu is not None
85
+
86
+ out = time_cpu(graph, inputs, test_runs) if is_cpu else time_cuda(graph, inputs, test_runs)
87
+ return out
88
+
89
+ @contextmanager
90
+ def no_fuser(*args, **kwargs):
91
+ old_optimize = torch._C._get_graph_executor_optimize(False)
92
+ try:
93
+ yield
94
+ finally:
95
+ torch._C._get_graph_executor_optimize(old_optimize)
96
+
97
+ def run_baseline_no_fusion(ir, inputs) -> float:
98
+ with no_fuser():
99
+ return run_test(ir, inputs)
100
+
101
+
102
+ def run_nnc(ir, inputs, dynamic) -> float:
103
+ try:
104
+ strat = [("DYNAMIC", 10)] if dynamic else [("STATIC", 10)]
105
+ old_strat = torch.jit.set_fusion_strategy(strat)
106
+ with torch.jit.fuser("fuser1"):
107
+ return run_test(ir, inputs)
108
+ finally:
109
+ torch.jit.set_fusion_strategy(old_strat)
110
+
111
+ def run_nvfuser(ir, inputs) -> float:
112
+ with torch.jit.fuser("fuser2"):
113
+ return run_test(ir, inputs)
llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (564 Bytes). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/__pycache__/_caffe2_graph.cpython-310.pyc ADDED
Binary file (24.8 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/__pycache__/_convert_np.cpython-310.pyc ADDED
Binary file (1.12 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/__pycache__/_embedding.cpython-310.pyc ADDED
Binary file (3.55 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/__pycache__/_onnx_graph.cpython-310.pyc ADDED
Binary file (1.93 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/__pycache__/_pytorch_graph.cpython-310.pyc ADDED
Binary file (10.7 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/__pycache__/_utils.cpython-310.pyc ADDED
Binary file (4.27 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/__pycache__/summary.cpython-310.pyc ADDED
Binary file (24.7 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/__pycache__/writer.cpython-310.pyc ADDED
Binary file (43.7 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/viz/__init__.py ADDED
File without changes
llava_next/lib/python3.10/site-packages/torch/utils/viz/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (171 Bytes). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/viz/__pycache__/_cycles.cpython-310.pyc ADDED
Binary file (14.2 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/viz/_cycles.py ADDED
@@ -0,0 +1,446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc
2
+ import sys
3
+ from typing import Any, Dict, List, NamedTuple, Optional, Tuple
4
+ import types
5
+ import weakref
6
+ import json
7
+ from tempfile import NamedTemporaryFile
8
+ import torch
9
+ from torch.cuda._memory_viz import _frames_fmt, _block_extra
10
+ import atexit
11
+ import logging
12
+ logger = logging.getLogger(__name__)
13
+
14
+ def observe_garbage(observer):
15
+ enabled = True
16
+
17
+ def disable():
18
+ # when GC runs during exit, things like `sys` will already be unloaded
19
+ # so we have to disable the callback to avoid hitting errors.
20
+ nonlocal enabled
21
+ enabled = False
22
+ atexit.register(disable)
23
+
24
+ def gc_callback(phase, info):
25
+ nonlocal enabled
26
+ if not enabled:
27
+ return
28
+ if phase == "start":
29
+ gc.set_debug(gc.DEBUG_SAVEALL)
30
+ elif phase == "stop":
31
+ orig_trace = sys.getprofile()
32
+ self_return = [False]
33
+
34
+ def do_collect(*args, **kwargs):
35
+ nonlocal enabled
36
+ if not self_return[0]:
37
+ self_return[0] = True
38
+ else:
39
+ sys.setprofile(orig_trace)
40
+ enabled = False
41
+ try:
42
+ # things in gc.garbage have survived a collection
43
+ # so to free them we have to collect a generation greater than them
44
+ # but that might _also_ free other stuff and we don't want to miss
45
+ # that stuff. So we have to now force gc at the highest level here,
46
+ # report all of what we found, _then_ we can free it up.
47
+ if info['generation'] != 2:
48
+ gc.collect()
49
+ observer(gc.garbage)
50
+ gc.garbage.clear()
51
+ # we have to re-run GC to clean up the cycles
52
+ # we saved from before.
53
+ gc.set_debug(0)
54
+ before = torch.cuda.memory_allocated()
55
+ gc.collect()
56
+ after = torch.cuda.memory_allocated()
57
+ if before != after:
58
+ logger.warning("CUDA Memory changed during GC, %d bytes freed.", before - after)
59
+ finally:
60
+ enabled = True
61
+ if orig_trace is not None:
62
+ return orig_trace(*args, **kwargs)
63
+ sys.setprofile(do_collect)
64
+
65
+ gc.callbacks.append(gc_callback)
66
+
67
+ # provide a way to disarm the callback
68
+ def remove():
69
+ gc.callbacks.remove(gc_callback)
70
+ return remove
71
+
72
+ # Function to visualize cycles adapated from refcycle:
73
+ # Copyright 2013 Mark Dickinson
74
+ #
75
+ # Licensed under the Apache License, Version 2.0 (the "License");
76
+ # you may not use this file except in compliance with the License.
77
+ # You may obtain a copy of the License at
78
+ #
79
+ # http://www.apache.org/licenses/LICENSE-2.0
80
+ #
81
+ # Unless required by applicable law or agreed to in writing, software
82
+ # distributed under the License is distributed on an "AS IS" BASIS,
83
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
84
+ # See the License for the specific language governing permissions and
85
+ # limitations under the License.
86
+
87
+ def _get_cell_type():
88
+ def f(x=None):
89
+ return lambda: x
90
+ return type(f().__closure__[0])
91
+
92
+ CellType = _get_cell_type()
93
+
94
+ def annotated_references(obj):
95
+ """
96
+ Return known information about references held by the given object.
97
+
98
+ Returns a mapping from referents to lists of descriptions. Note that there
99
+ may be more than one edge leading to any particular referent; hence the
100
+ need for a list. Descriptions are currently strings.
101
+
102
+ """
103
+ references: Dict[int, List[str]] = {}
104
+
105
+ def add_reference(name, obj):
106
+ references.setdefault(id(obj), []).append(name)
107
+
108
+ def add_attrs(*attrs):
109
+ for attr in attrs:
110
+ if hasattr(obj, attr):
111
+ add_reference(attr, getattr(obj, attr))
112
+
113
+ def add_cell_references():
114
+ try:
115
+ add_attrs("cell_contents")
116
+ except ValueError:
117
+ # if cell_contents is empty,
118
+ # accessing it raises ValueError
119
+ # in this case there is no object to
120
+ # annotate
121
+ pass
122
+
123
+ def add_function_references():
124
+ add_attrs("__defaults__",
125
+ "__closure__",
126
+ "__globals__",
127
+ "__code__",
128
+ "__name__",
129
+ "__module__",
130
+ "__doc__"
131
+ "__qualname__",
132
+ "__annotations__",
133
+ "__kwdefaults__")
134
+
135
+
136
+ def add_sequence_references():
137
+ for position, item in enumerate(obj):
138
+ add_reference(f"[{position}]", item)
139
+
140
+ def add_dict_references():
141
+ for key, value in obj.items():
142
+ add_reference("key", key)
143
+ add_reference(f"[{repr(key)}]", value)
144
+
145
+ def add_set_references():
146
+ for elt in obj:
147
+ add_reference("element", elt)
148
+
149
+ def add_bound_method_references():
150
+ add_attrs("__self__", "__func__", "im_class")
151
+
152
+ def add_weakref_references():
153
+ # For subclasses of weakref, we can't reliably distinguish the
154
+ # callback (if any) from other attributes.
155
+ if type(obj) is weakref.ref:
156
+ referents = gc.get_referents(obj)
157
+ if len(referents) == 1:
158
+ target = referents[0]
159
+ add_reference("__callback__", target)
160
+
161
+
162
+ def add_frame_references():
163
+ f_locals = obj.f_locals
164
+ add_attrs("f_back", "f_code", "f_builtins", "f_globals", "f_trace", "f_locals")
165
+ # Some badly-behaved code replaces the f_locals dict with
166
+ # something that doesn't support the full dict interface. So we
167
+ # only continue with the annotation if f_locals is a Python dict.
168
+ if type(f_locals) is dict:
169
+ for name, local in obj.f_locals.items():
170
+ add_reference(f"local {name}", local)
171
+
172
+ def add_getset_descriptor_references():
173
+ add_attrs("__objclass__", "__name__", "__doc__")
174
+
175
+ type_based_references = {
176
+ tuple: add_sequence_references,
177
+ list: add_sequence_references,
178
+ dict: add_dict_references,
179
+ set: add_set_references,
180
+ frozenset: add_set_references,
181
+ types.FunctionType: add_function_references,
182
+ types.FrameType: add_frame_references,
183
+ CellType: add_cell_references,
184
+ types.MethodType: add_bound_method_references,
185
+ weakref.ref: add_weakref_references,
186
+ types.GetSetDescriptorType: add_getset_descriptor_references,
187
+ }
188
+
189
+ for type_ in type(obj).__mro__:
190
+ if type_ in type_based_references:
191
+ type_based_references[type_]()
192
+
193
+ add_attrs("__dict__", "__class__")
194
+ if isinstance(obj, type):
195
+ add_attrs("__mro__")
196
+
197
+ return references
198
+
199
+ ###############################################################################
200
+ # Object annotations.
201
+
202
+
203
+ BASE_TYPES = (int, float, complex, type(None), str, bytes)
204
+ FRAME_FILENAME_LIMIT = 32
205
+
206
+ def object_annotation(obj):
207
+ """
208
+ Return a string to be used for Graphviz nodes. The string
209
+ should be short but as informative as possible.
210
+
211
+ """
212
+
213
+ def format_sequence(obj):
214
+ body = ','.join(repr(x) if isinstance(x, BASE_TYPES) else type(x).__name__ for i, x in zip(range(8), obj))
215
+ if len(obj) > 8:
216
+ body = f'{body}, ...{len(obj) - 8}'
217
+ return body
218
+
219
+ # For basic types, use the repr.
220
+ if isinstance(obj, BASE_TYPES):
221
+ return repr(obj)
222
+ if type(obj).__name__ == 'function':
223
+ return f"function\n{obj.__name__}"
224
+ elif isinstance(obj, types.MethodType):
225
+ try:
226
+ func_name = obj.__func__.__qualname__
227
+ except AttributeError:
228
+ func_name = "<anonymous>"
229
+ return f"instancemethod\n{func_name}"
230
+ elif isinstance(obj, list):
231
+ return f"[{format_sequence(obj)}]"
232
+ elif isinstance(obj, tuple):
233
+ return f"({format_sequence(obj)})"
234
+ elif isinstance(obj, dict):
235
+ return f"dict[{len(obj)}]"
236
+ elif isinstance(obj, types.ModuleType):
237
+ return f"module\n{obj.__name__}"
238
+ elif isinstance(obj, type):
239
+ return f"type\n{obj.__name__}"
240
+ elif isinstance(obj, weakref.ref):
241
+ referent = obj()
242
+ if referent is None:
243
+ return "weakref (dead referent)"
244
+ else:
245
+ return f"weakref to id 0x{id(referent):x}"
246
+ elif isinstance(obj, types.FrameType):
247
+ filename = obj.f_code.co_filename
248
+ if len(filename) > FRAME_FILENAME_LIMIT:
249
+ filename = "..." + filename[-(FRAME_FILENAME_LIMIT - 3):]
250
+ return f"frame\n{filename}:{obj.f_lineno}"
251
+ else:
252
+ return f"object\n{type(obj).__module__}.{type(obj).__name__}"
253
+
254
+
255
+
256
+ class Node(NamedTuple):
257
+ label: str
258
+ context: Optional[str]
259
+ root: bool
260
+ referrents: List[Tuple[str, int]]
261
+
262
+ def create_graph(objects, *, context=None, filter=None):
263
+ if context is None:
264
+ context = cuda_allocation_context()
265
+ if filter is None:
266
+ filter = is_cuda_tensor
267
+
268
+ nodes = [Node(object_annotation(obj), context(obj), filter(obj), []) for obj in objects]
269
+ node_referrers: List[List[int]] = [[] for obj in objects]
270
+
271
+ id_to_node = {id(obj): i for i, obj in enumerate(objects)}
272
+ for obj in objects:
273
+ fidx = id_to_node[id(obj)]
274
+ f = nodes[fidx]
275
+ references = annotated_references(obj)
276
+ for referrent in gc.get_referents(obj):
277
+ rid = id(referrent)
278
+ tidx = id_to_node.get(rid, None)
279
+ if tidx is None:
280
+ continue
281
+ t = nodes[tidx]
282
+ labels = references.get(rid, ["?"])
283
+ node_referrers[tidx].append(fidx)
284
+ for label in labels:
285
+ f.referrents.append((label, tidx))
286
+
287
+ to_search = [i for i, n in enumerate(nodes) if n.root]
288
+ to_keep = set()
289
+ while to_search:
290
+ idx = to_search.pop()
291
+ if idx in to_keep:
292
+ continue
293
+ to_keep.add(idx)
294
+ referrers = node_referrers[idx]
295
+ to_search.extend(referrers)
296
+ id_to_filtered_id: Dict[int, int] = {}
297
+ filtered: List[Any] = []
298
+ for i, n in enumerate(nodes):
299
+ if i in to_keep:
300
+ id_to_filtered_id[i] = len(id_to_filtered_id)
301
+ filtered.append(n)
302
+ for n in filtered:
303
+ n.referrents[:] = [(label, id_to_filtered_id[idx])
304
+ for (label, idx) in n.referrents
305
+ if idx in id_to_filtered_id]
306
+ return filtered
307
+
308
+ def escape(n):
309
+ return json.dumps(n)
310
+
311
+
312
+ def is_cuda_tensor(obj):
313
+ return isinstance(obj, torch.Tensor) and obj.is_cuda
314
+
315
+ def cuda_allocation_context():
316
+ snapshot = torch.cuda.memory._snapshot()
317
+ addr_to_frame = {}
318
+ for seg in snapshot['segments']:
319
+ addr = seg['address']
320
+ for blk in seg['blocks']:
321
+ if blk['state'] == 'active_allocated':
322
+ frames, real_size = _block_extra(blk)
323
+ addr_to_frame[addr] = frames
324
+ addr += blk['size']
325
+
326
+ def object_context(obj):
327
+ if is_cuda_tensor(obj):
328
+ addr = obj.untyped_storage().data_ptr()
329
+ frames = addr_to_frame.get(addr)
330
+ if frames is not None:
331
+ return '\n'.join(_frames_fmt(frames, full_filename=True))
332
+ return None
333
+ return object_context
334
+
335
+ def to_dot(nodes):
336
+ lines = ["digraph GraphName {", "node [shape=rect];", 'rankdir=LR;']
337
+ for i, n in enumerate(nodes):
338
+ lines.append(f'{i} [label={escape(n.label)}, color={ "red" if n.root else "black"}];')
339
+
340
+ for i, f in enumerate(nodes):
341
+ for label, j in f.referrents:
342
+ lines.append(f'{i} -> {j} [label = {escape(label)}]')
343
+ lines.append("}\n")
344
+ return '\n'.join(lines)
345
+
346
+ _template = """
347
+ <!DOCTYPE html>
348
+ <html>
349
+ <head>
350
+ <style>
351
+ body {
352
+ margin: 0;
353
+ padding: 0;
354
+ overflow: hidden;
355
+ }
356
+
357
+ #container {
358
+ display: flex;
359
+ flex-direction: column;
360
+ height: 100vh;
361
+ }
362
+
363
+ #main {
364
+ flex: 2;
365
+ overflow: auto;
366
+ }
367
+
368
+ #preContainer {
369
+ flex: 1;
370
+ overflow: auto;
371
+ }
372
+
373
+ svg {
374
+ overflow: scroll;
375
+ }
376
+
377
+ pre {
378
+ margin: 0;
379
+ padding: 10px;
380
+ }
381
+ </style>
382
+ </head>
383
+ <body>
384
+ <div id="container">
385
+ <div id="main">
386
+ </div>
387
+ <div id="preContainer">
388
+ <pre id="stacktrace">Mouse over tensor objects to see where they were allocated.</pre>
389
+ </div>
390
+ </div>
391
+ <script src='https://cdnjs.cloudflare.com/ajax/libs/viz.js/1.8.0/viz-lite.js'></script>
392
+ <script>
393
+ let dot = $DOT
394
+ let image = Viz(dot, {format: 'svg'});
395
+ document.getElementById('main').innerHTML = image
396
+ $LISTENERS
397
+ </script>
398
+ </body>
399
+ </html>
400
+ """
401
+ _listener_template = """
402
+ document.getElementById('node{id}').addEventListener('mouseover', function(event) {{
403
+ document.getElementById("stacktrace").textContent = {stack}
404
+ }})
405
+ """
406
+ def to_html(nodes):
407
+ listeners = []
408
+ for i, n in enumerate(nodes):
409
+ if n.context is None:
410
+ continue
411
+ s = _listener_template.format(id=str(i + 1), stack=escape(f'{n.label}:\n{n.context}'))
412
+ listeners.append(s)
413
+ dot = to_dot(nodes)
414
+ return _template.replace('$DOT', repr(dot)).replace('$LISTENERS', '\n'.join(listeners))
415
+
416
+ def observe_tensor_cycles(callback):
417
+ torch.cuda.memory._record_memory_history(max_entries=100000)
418
+
419
+ def observer(garbage):
420
+ if garbage:
421
+ if not any(is_cuda_tensor(obj) for obj in garbage):
422
+ logger.info("No CUDA Tensors found in garbage")
423
+ return
424
+ callback(to_html(create_graph(garbage)))
425
+ return observe_garbage(observer)
426
+
427
+
428
+ def warn_tensor_cycles():
429
+ """
430
+ Reference cycles are freed by the cycle collector rather than being cleaned up
431
+ when the objects in the cycle first become unreachable. If a cycle points to a tensor,
432
+ the CUDA memory for that tensor will not be freed until garbage collection runs.
433
+ Accumulation of CUDA allocations can lead to out of memory errors (OOMs), as well as
434
+ non-deterministic allocation behavior which is harder to debug.
435
+
436
+ This function installs a warning that is reports whenever a cycle that is holding CUDA
437
+ memory is observed. The warning produces a html file that visualizes the cycle,
438
+ and links it to the stack frame that allocted the CUDA tensor.
439
+ """
440
+ logger.info("Watching Python reference cycles for CUDA Tensors.")
441
+
442
+ def write_and_log(html):
443
+ with NamedTemporaryFile('w', suffix='.html', delete=False) as f:
444
+ f.write(html)
445
+ logger.warning('Reference cycle includes a CUDA Tensor see visualization of cycle %s', f.name)
446
+ return observe_tensor_cycles(write_and_log)
vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/__init__.pyi ADDED
File without changes
vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/storage.pyi ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ from typing import Any, IO, List, Optional, Tuple, Type
3
+
4
+ from django.core.files.base import File
5
+ from django.utils.functional import LazyObject
6
+
7
+ class Storage:
8
+ def open(self, name: str, mode: str = ...) -> File: ...
9
+ def save(self, name: Optional[str], content: IO[Any], max_length: Optional[int] = ...) -> str: ...
10
+ def get_valid_name(self, name: str) -> str: ...
11
+ def get_available_name(self, name: str, max_length: Optional[int] = ...) -> str: ...
12
+ def generate_filename(self, filename: str) -> str: ...
13
+ def path(self, name: str) -> str: ...
14
+ def delete(self, name: str) -> None: ...
15
+ def exists(self, name: str) -> bool: ...
16
+ def listdir(self, path: str) -> Tuple[List[str], List[str]]: ...
17
+ def size(self, name: str) -> int: ...
18
+ def url(self, name: Optional[str]) -> str: ...
19
+ def get_accessed_time(self, name: str) -> datetime: ...
20
+ def get_created_time(self, name: str) -> datetime: ...
21
+ def get_modified_time(self, name: str) -> datetime: ...
22
+
23
+ class FileSystemStorage(Storage):
24
+ OS_OPEN_FLAGS: int = ...
25
+ def __init__(
26
+ self,
27
+ location: Optional[str] = ...,
28
+ base_url: Optional[str] = ...,
29
+ file_permissions_mode: Optional[int] = ...,
30
+ directory_permissions_mode: Optional[int] = ...,
31
+ ) -> None: ...
32
+ @property
33
+ def base_location(self) -> str: ...
34
+ @property
35
+ def location(self) -> str: ...
36
+ @property
37
+ def base_url(self) -> str: ...
38
+ @property
39
+ def file_permissions_mode(self) -> Optional[int]: ...
40
+ @property
41
+ def directory_permissions_mode(self) -> Optional[int]: ...
42
+
43
+ class DefaultStorage(LazyObject): ...
44
+
45
+ default_storage: Any
46
+
47
+ def get_storage_class(import_path: Optional[str] = ...) -> Type[Storage]: ...
vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/uploadhandler.pyi ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Stubs for django.core.files.uploadhandler (Python 3.5)
2
+
3
+ from typing import Any, Dict, IO, Optional, Tuple
4
+ from django.core.files.uploadedfile import UploadedFile, TemporaryUploadedFile
5
+ from django.http.request import HttpRequest, QueryDict
6
+ from django.utils.datastructures import MultiValueDict
7
+
8
+ class UploadFileException(Exception): ...
9
+
10
+ class StopUpload(UploadFileException):
11
+ connection_reset: bool = ...
12
+ def __init__(self, connection_reset: bool = ...) -> None: ...
13
+
14
+ class SkipFile(UploadFileException): ...
15
+ class StopFutureHandlers(UploadFileException): ...
16
+
17
+ class FileUploadHandler:
18
+ chunk_size: int = ...
19
+ file_name: Optional[str] = ...
20
+ content_type: Optional[str] = ...
21
+ content_length: Optional[int] = ...
22
+ charset: Optional[str] = ...
23
+ content_type_extra: Optional[Dict[str, str]] = ...
24
+ request: Optional[HttpRequest] = ...
25
+ field_name: str = ...
26
+ def __init__(self, request: Optional[HttpRequest] = ...) -> None: ...
27
+ def handle_raw_input(
28
+ self,
29
+ input_data: IO[bytes],
30
+ META: Dict[str, str],
31
+ content_length: int,
32
+ boundary: str,
33
+ encoding: Optional[str] = ...,
34
+ ) -> Optional[Tuple[QueryDict, MultiValueDict[str, UploadedFile]]]: ...
35
+ def new_file(
36
+ self,
37
+ field_name: str,
38
+ file_name: str,
39
+ content_type: str,
40
+ content_length: Optional[int],
41
+ charset: Optional[str] = ...,
42
+ content_type_extra: Optional[Dict[str, str]] = ...,
43
+ ) -> None: ...
44
+ def receive_data_chunk(self, raw_data: bytes, start: int) -> Optional[bytes]: ...
45
+ def file_complete(self, file_size: int) -> Optional[UploadedFile]: ...
46
+ def upload_complete(self) -> None: ...
47
+
48
+ class TemporaryFileUploadHandler(FileUploadHandler):
49
+ def __init__(self, request: Optional[HttpRequest] = ...) -> None: ...
50
+ file = ... # type: TemporaryUploadedFile
51
+ def new_file(
52
+ self,
53
+ field_name: str,
54
+ file_name: str,
55
+ content_type: str,
56
+ content_length: Optional[int],
57
+ charset: Optional[str] = ...,
58
+ content_type_extra: Optional[Dict[str, str]] = ...,
59
+ ) -> None: ...
60
+ def receive_data_chunk(self, raw_data: bytes, start: int) -> Optional[bytes]: ...
61
+ def file_complete(self, file_size: int) -> Optional[UploadedFile]: ...
62
+
63
+ class MemoryFileUploadHandler(FileUploadHandler):
64
+ activated = ... # type: bool
65
+ file = ... # type: IO[bytes]
66
+ def handle_raw_input(
67
+ self,
68
+ input_data: IO[bytes],
69
+ META: Dict[str, str],
70
+ content_length: int,
71
+ boundary: str,
72
+ encoding: Optional[str] = ...,
73
+ ) -> Optional[Tuple[QueryDict, MultiValueDict[str, UploadedFile]]]: ...
74
+ def new_file(
75
+ self,
76
+ field_name: str,
77
+ file_name: str,
78
+ content_type: str,
79
+ content_length: Optional[int],
80
+ charset: Optional[str] = ...,
81
+ content_type_extra: Optional[Dict[str, str]] = ...,
82
+ ) -> None: ...
83
+ def receive_data_chunk(self, raw_data: bytes, start: int) -> Optional[bytes]: ...
84
+ def file_complete(self, file_size: int) -> Optional[UploadedFile]: ...
85
+
86
+ def load_handler(path: str, *args: Any, **kwargs: Any) -> FileUploadHandler: ...
vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/handlers/base.pyi ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Callable
2
+
3
+ from django.http.request import HttpRequest
4
+ from django.http.response import HttpResponse, HttpResponseBase
5
+
6
+ logger: Any
7
+
8
+ class BaseHandler:
9
+ def load_middleware(self) -> None: ...
10
+ def make_view_atomic(self, view: Callable) -> Callable: ...
11
+ def get_exception_response(self, request: Any, resolver: Any, status_code: Any, exception: Any): ...
12
+ def get_response(self, request: HttpRequest) -> HttpResponseBase: ...
13
+ def process_exception_by_middleware(self, exception: Exception, request: HttpRequest) -> HttpResponse: ...