/
pythranizer.py
237 lines (176 loc) · 5.7 KB
/
pythranizer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
"""Use Pythran to create extensions
===================================
User API
--------
.. autofunction:: wait_for_all_extensions
Internal API
------------
.. autofunction:: make_hex
.. autoclass:: SchedulerPopen
:members:
:private-members:
.. autofunction:: name_ext_from_path_backend
.. autofunction:: compile_extensions
.. autofunction:: compile_extension
"""
import multiprocessing
import subprocess
import time
from typing import Union, Iterable, Optional
import sysconfig
import hashlib
import sys
import os
from datetime import datetime
from .. import mpi
from ..mpi import Path, PathSeq
from ..log import logger
ext_suffix = sysconfig.get_config_var("EXT_SUFFIX") or ".so"
def modification_date(filename):
"""Get the modification date of a file"""
return datetime.fromtimestamp(os.path.getmtime(str(filename)))
def has_to_build(output_file: Path, input_file: Path):
"""Check if a file has to be (re)built"""
output_file = PathSeq(output_file)
input_file = PathSeq(input_file)
if not output_file.exists():
return True
mod_date_output = modification_date(output_file)
if mod_date_output < modification_date(input_file):
return True
return False
def make_hex(src):
"""Produce a hash from a sting"""
return hashlib.md5(src.encode("utf8")).hexdigest()
def name_ext_from_path_backend(path_backend):
"""Return an extension name given the path of a Pythran file"""
name = None
if mpi.rank == 0:
path_backend = PathSeq(path_backend)
if path_backend.exists():
with open(path_backend) as file:
src = file.read()
else:
src = ""
name = path_backend.stem + "_" + make_hex(src) + ext_suffix
return mpi.bcast(name)
class SchedulerPopen:
"""Limit the number of Pythran compilations performed in parallel
"""
deltat = 0.2
def __init__(self, parallel=True):
if mpi.rank > 0:
return
self.processes = []
if parallel:
self.limit_nb_processes = max(1, multiprocessing.cpu_count() // 2)
else:
self.limit_nb_processes = 1
def block_until_avail(self, parallel=True):
if mpi.rank == 0:
if parallel:
limit = self.limit_nb_processes
else:
limit = 1
while len(self.processes) >= limit:
time.sleep(self.deltat)
self.processes = [
process
for process in self.processes
if process.is_alive_root()
]
mpi.barrier(timeout=None)
def wait_for_all_extensions(self):
"""Wait until all compilation processes are done"""
if mpi.rank == 0:
while self.processes:
time.sleep(self.deltat)
self.processes = [
process
for process in self.processes
if process.is_alive_root()
]
mpi.barrier(timeout=None)
def compile_extension(
self,
path: Path,
name_ext_file: Optional[str] = None,
native=False,
xsimd=False,
openmp=False,
str_pythran_flags: Optional[str] = None,
parallel=True,
force=True,
):
if name_ext_file is None:
name_ext_file = name_ext_from_path_backend(path)
if not force:
path_out = path.with_name(name_ext_file)
if not has_to_build(path_out, path):
logger.warning(
f"Do not pythranize {path} because it seems up-to-date "
"(but the compilation options may have changed). "
"You can force the compilation with the option -f."
)
return
if mpi.rank == 0:
logger.info(f"Schedule pythranization of file {path}")
if str_pythran_flags is not None:
flags = str_pythran_flags.strip().split()
else:
flags = []
def update_flags(flag):
if flag not in flags:
flags.append(flag)
if native and os.name != "nt":
update_flags("-march=native")
if xsimd:
update_flags("-DUSE_XSIMD")
if openmp:
update_flags("-fopenmp")
if logger.is_enable_for("debug"):
update_flags("-v")
words_command = [
sys.executable,
"-m",
"transonic_cl.run_pythran",
path.name,
]
words_command.extend(("-o", name_ext_file))
words_command.extend(flags)
cwd = path.parent
self.block_until_avail(parallel)
process = None
if mpi.rank == 0:
process = subprocess.Popen(words_command, cwd=cwd)
process = mpi.ShellProcessMPI(process)
if mpi.rank == 0:
self.processes.append(process)
return process
scheduler = SchedulerPopen()
def wait_for_all_extensions():
"""Wait until all compilation processes are done"""
scheduler.wait_for_all_extensions()
def compile_extensions(
paths: Iterable[Path], str_pythran_flags: str, parallel=True, force=True
):
for path in paths:
scheduler.compile_extension(
path,
str_pythran_flags=str_pythran_flags,
parallel=parallel,
force=force,
)
def compile_extension(
path: Union[Path, str],
name_ext_file: Optional[str] = None,
native=False,
xsimd=False,
openmp=False,
):
if not isinstance(path, Path):
path = Path(path)
# return the process
return scheduler.compile_extension(
path, name_ext_file, native=native, xsimd=xsimd, openmp=openmp
)