phono3py-gpu 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- phono3py_gpu/__init__.py +19 -0
- phono3py_gpu/_wte.py +521 -0
- phono3py_gpu/backend.py +65 -0
- phono3py_gpu/batching.py +211 -0
- phono3py_gpu/collision.py +432 -0
- phono3py_gpu/eigensolver.py +222 -0
- phono3py_gpu/factory.py +353 -0
- phono3py_gpu/fourier.py +474 -0
- phono3py_gpu/harmonic.py +258 -0
- phono3py_gpu/initialization.py +50 -0
- phono3py_gpu/integration.py +183 -0
- phono3py_gpu/interaction.py +270 -0
- phono3py_gpu/isotope.py +116 -0
- phono3py_gpu/kappa.py +39 -0
- phono3py_gpu/kernels/collision.cu +11 -0
- phono3py_gpu/kernels/degeneracy.cu +36 -0
- phono3py_gpu/kernels/interaction.cu +89 -0
- phono3py_gpu/kernels/isotope.cu +28 -0
- phono3py_gpu/kernels/scattering.cu +85 -0
- phono3py_gpu/kernels/tetrahedron.cu +801 -0
- phono3py_gpu/multigpu.py +347 -0
- phono3py_gpu/scattering.py +449 -0
- phono3py_gpu/velocity.py +175 -0
- phono3py_gpu-1.0.0.dist-info/METADATA +151 -0
- phono3py_gpu-1.0.0.dist-info/RECORD +32 -0
- phono3py_gpu-1.0.0.dist-info/WHEEL +5 -0
- phono3py_gpu-1.0.0.dist-info/entry_points.txt +2 -0
- phono3py_gpu-1.0.0.dist-info/licenses/LICENSE +26 -0
- phono3py_gpu-1.0.0.dist-info/licenses/LICENSE.phono3py +26 -0
- phono3py_gpu-1.0.0.dist-info/licenses/LICENSE.phonopy +26 -0
- phono3py_gpu-1.0.0.dist-info/licenses/LICENSE.wte +28 -0
- phono3py_gpu-1.0.0.dist-info/top_level.txt +1 -0
phono3py_gpu/multigpu.py
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
"""Single-node GPU workers for independent initial-q scattering tasks.
|
|
2
|
+
|
|
3
|
+
The primary GPU reuses the parent solver; other GPUs use fresh subprocesses.
|
|
4
|
+
A copy-on-write mapped snapshot shares large host arrays while preserving private
|
|
5
|
+
mutable state and the canonical phonon basis. Only NumPy results cross processes.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import mmap
|
|
9
|
+
import pickle
|
|
10
|
+
import queue
|
|
11
|
+
import struct
|
|
12
|
+
import subprocess
|
|
13
|
+
import sys
|
|
14
|
+
import tempfile
|
|
15
|
+
import threading
|
|
16
|
+
import time
|
|
17
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
18
|
+
from contextlib import redirect_stdout
|
|
19
|
+
from copy import copy
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
from phono3py.phonon3.triplets import get_nosym_triplets_at_q, get_triplets_at_q
|
|
23
|
+
|
|
24
|
+
from phono3py_gpu.backend import cupy
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _write_snapshot(payload, stream):
|
|
28
|
+
"""Keep large NumPy buffers outside the pickle for shared mapped loading."""
|
|
29
|
+
buffers = []
|
|
30
|
+
|
|
31
|
+
def collect(buffer):
|
|
32
|
+
view = buffer.raw()
|
|
33
|
+
if view.nbytes < 1024**2:
|
|
34
|
+
return True
|
|
35
|
+
buffers.append(view)
|
|
36
|
+
return False
|
|
37
|
+
|
|
38
|
+
metadata = pickle.dumps(payload, protocol=5, buffer_callback=collect)
|
|
39
|
+
for view in buffers:
|
|
40
|
+
stream.write(struct.pack("<Q", view.nbytes))
|
|
41
|
+
stream.write(b"\0" * (-stream.tell() % 64))
|
|
42
|
+
stream.write(view)
|
|
43
|
+
offset = stream.tell()
|
|
44
|
+
stream.write(metadata)
|
|
45
|
+
stream.write(struct.pack("<Q", offset))
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _load_snapshot(stream):
|
|
49
|
+
"""Workers share file pages; writes remain private through copy-on-write."""
|
|
50
|
+
mapping = mmap.mmap(stream.fileno(), 0, access=mmap.ACCESS_COPY)
|
|
51
|
+
view = memoryview(mapping)
|
|
52
|
+
(offset,) = struct.unpack_from("<Q", view, len(view) - 8)
|
|
53
|
+
|
|
54
|
+
def buffers():
|
|
55
|
+
position = 0
|
|
56
|
+
while position < offset:
|
|
57
|
+
(size,) = struct.unpack_from("<Q", view, position)
|
|
58
|
+
position = (position + 8 + 63) // 64 * 64
|
|
59
|
+
yield view[position : position + size]
|
|
60
|
+
position += size
|
|
61
|
+
|
|
62
|
+
stream.seek(offset)
|
|
63
|
+
return pickle.load(stream, buffers=buffers())
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def devices():
|
|
67
|
+
"""Use every GPU visible to the CUDA runtime."""
|
|
68
|
+
return list(range(cupy().cuda.runtime.getDeviceCount()))
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _exchange(process, value):
|
|
72
|
+
pickle.dump(value, process.stdin, protocol=5)
|
|
73
|
+
process.stdin.flush()
|
|
74
|
+
return pickle.load(process.stdout)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _serve(device, snapshot, tasks, results, processes, cancelled, ready):
|
|
78
|
+
process = None
|
|
79
|
+
try:
|
|
80
|
+
process = subprocess.Popen(
|
|
81
|
+
[sys.executable, "-m", "phono3py_gpu.multigpu", str(device), str(snapshot)],
|
|
82
|
+
stdin=subprocess.PIPE,
|
|
83
|
+
stdout=subprocess.PIPE,
|
|
84
|
+
)
|
|
85
|
+
processes.append(process)
|
|
86
|
+
if cancelled.is_set():
|
|
87
|
+
raise RuntimeError("GPU worker startup was cancelled.")
|
|
88
|
+
setup = pickle.load(process.stdout)
|
|
89
|
+
results.put(("ready", device, setup))
|
|
90
|
+
ready.wait()
|
|
91
|
+
while not cancelled.is_set():
|
|
92
|
+
try:
|
|
93
|
+
task = tasks.get_nowait()
|
|
94
|
+
except queue.Empty:
|
|
95
|
+
break
|
|
96
|
+
payload = _exchange(process, task)
|
|
97
|
+
results.put(("result", device, (task, payload)))
|
|
98
|
+
pickle.dump(None, process.stdin, protocol=5)
|
|
99
|
+
process.stdin.flush()
|
|
100
|
+
if process.wait() != 0:
|
|
101
|
+
raise RuntimeError(f"GPU {device} worker exited with {process.returncode}.")
|
|
102
|
+
except BaseException as error:
|
|
103
|
+
results.put(("error", device, error))
|
|
104
|
+
raise
|
|
105
|
+
finally:
|
|
106
|
+
if process is not None:
|
|
107
|
+
if process.poll() is None:
|
|
108
|
+
process.terminate()
|
|
109
|
+
process.wait()
|
|
110
|
+
process.stdin.close()
|
|
111
|
+
process.stdout.close()
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _compute_task(solver, task, collision):
|
|
115
|
+
from phono3py_gpu.batching import compute_q_batch
|
|
116
|
+
|
|
117
|
+
_, gps, last = task
|
|
118
|
+
solver.q_batch_stats = dict(triplet_batches=0, max_q_per_launch=0)
|
|
119
|
+
start = time.perf_counter()
|
|
120
|
+
answers = compute_q_batch(solver, gps, collision=collision, last_batch=last)
|
|
121
|
+
pp = solver._pp
|
|
122
|
+
state = (
|
|
123
|
+
(pp.interaction_strength, pp.zero_value_positions)
|
|
124
|
+
if last and collision and solver.retain_pp
|
|
125
|
+
else None
|
|
126
|
+
)
|
|
127
|
+
return answers, time.perf_counter() - start, solver.q_batch_stats, state
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _serve_primary(device, solver, collision, tasks, results, cancelled, ready):
|
|
131
|
+
"""Reuse phonons on the primary GPU without copying the grid to a new process."""
|
|
132
|
+
try:
|
|
133
|
+
cupy().cuda.Device(device).use()
|
|
134
|
+
start = time.perf_counter()
|
|
135
|
+
solver.engine.fourier
|
|
136
|
+
results.put(
|
|
137
|
+
(
|
|
138
|
+
"ready",
|
|
139
|
+
device,
|
|
140
|
+
dict(
|
|
141
|
+
setup_seconds=time.perf_counter() - start,
|
|
142
|
+
triplet_batch=solver.engine.batch_size,
|
|
143
|
+
),
|
|
144
|
+
)
|
|
145
|
+
)
|
|
146
|
+
ready.wait()
|
|
147
|
+
while not cancelled.is_set():
|
|
148
|
+
try:
|
|
149
|
+
task = tasks.get_nowait()
|
|
150
|
+
except queue.Empty:
|
|
151
|
+
break
|
|
152
|
+
payload = _compute_task(solver, task, collision)
|
|
153
|
+
results.put(("result", device, (task, payload)))
|
|
154
|
+
except BaseException as error:
|
|
155
|
+
results.put(("error", device, error))
|
|
156
|
+
raise
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def iterate(calculator, solver, ids, indices, q_batch, collision, callback=None):
|
|
160
|
+
"""Schedule heavier q groups first, store results in original global slots."""
|
|
161
|
+
pp = calculator._pp
|
|
162
|
+
grid_points = calculator._kappa_settings.grid_points
|
|
163
|
+
counts = {}
|
|
164
|
+
get_triplets = (
|
|
165
|
+
get_triplets_at_q if pp._is_mesh_symmetry else get_nosym_triplets_at_q
|
|
166
|
+
)
|
|
167
|
+
for index in indices:
|
|
168
|
+
# Scheduling needs counts only; workers prepare and validate q state.
|
|
169
|
+
counts[index] = len(get_triplets(int(grid_points[index]), pp.bz_grid)[0])
|
|
170
|
+
groups = [indices[i : i + q_batch] for i in range(0, len(indices), q_batch)]
|
|
171
|
+
final_group = groups[-1]
|
|
172
|
+
groups.sort(key=lambda group: sum(counts[i] for i in group), reverse=True)
|
|
173
|
+
tasks, results = queue.Queue(), queue.Queue()
|
|
174
|
+
last = indices[-1]
|
|
175
|
+
for group in groups:
|
|
176
|
+
tasks.put((group, grid_points[group], group is final_group))
|
|
177
|
+
options = dict(
|
|
178
|
+
sigmas=solver._sigmas,
|
|
179
|
+
sigma_cutoff=solver._sigma_cutoff,
|
|
180
|
+
temperatures=solver._temperatures,
|
|
181
|
+
)
|
|
182
|
+
payload = dict(pp=copy(pp), collision=collision, options=options, lang=pp._lang)
|
|
183
|
+
if collision:
|
|
184
|
+
options["retain_pp"] = solver.retain_pp
|
|
185
|
+
payload["rot_grid_points"] = (
|
|
186
|
+
None
|
|
187
|
+
if solver._collision._is_reducible_collision_matrix
|
|
188
|
+
else pp.bz_grid.grg2bzg[solver._collision._rot_grid_points]
|
|
189
|
+
)
|
|
190
|
+
payload["is_kappa_star"] = calculator._kappa_settings.is_kappa_star
|
|
191
|
+
else:
|
|
192
|
+
options["is_N_U"] = calculator._is_N_U
|
|
193
|
+
options["lang"] = pp._lang
|
|
194
|
+
# Previous calculator runs can leave a large last-q interaction tensor.
|
|
195
|
+
payload["pp"].set_interaction_strength(None)
|
|
196
|
+
stats = calculator.multi_gpu_stats = dict(devices=ids, per_device={})
|
|
197
|
+
cancelled, processes = threading.Event(), []
|
|
198
|
+
ready = threading.Barrier(len(ids))
|
|
199
|
+
calculator._grid_point_count = 0
|
|
200
|
+
last_state = None
|
|
201
|
+
pending = {}
|
|
202
|
+
with tempfile.TemporaryDirectory(prefix="phono3py-gpu-") as directory:
|
|
203
|
+
snapshot = Path(directory) / "interaction.pickle"
|
|
204
|
+
with snapshot.open("wb") as stream:
|
|
205
|
+
_write_snapshot(payload, stream)
|
|
206
|
+
executor = ThreadPoolExecutor(max_workers=len(ids))
|
|
207
|
+
# Other GPUs use separate processes to avoid GIL contention during collection.
|
|
208
|
+
futures = [
|
|
209
|
+
executor.submit(
|
|
210
|
+
_serve_primary,
|
|
211
|
+
ids[0],
|
|
212
|
+
solver,
|
|
213
|
+
collision,
|
|
214
|
+
tasks,
|
|
215
|
+
results,
|
|
216
|
+
cancelled,
|
|
217
|
+
ready,
|
|
218
|
+
)
|
|
219
|
+
] + [
|
|
220
|
+
executor.submit(
|
|
221
|
+
_serve, d, snapshot, tasks, results, processes, cancelled, ready
|
|
222
|
+
)
|
|
223
|
+
for d in ids[1:]
|
|
224
|
+
]
|
|
225
|
+
try:
|
|
226
|
+
completed = 0
|
|
227
|
+
while completed < len(groups):
|
|
228
|
+
kind, device, value = results.get()
|
|
229
|
+
if kind == "error":
|
|
230
|
+
raise RuntimeError(
|
|
231
|
+
f"GPU {device} scattering worker failed."
|
|
232
|
+
) from value
|
|
233
|
+
if kind == "ready":
|
|
234
|
+
stats["per_device"][device] = dict(
|
|
235
|
+
**value, q_points=0, triplets=0, compute_seconds=0.0
|
|
236
|
+
)
|
|
237
|
+
continue
|
|
238
|
+
(group, gps, _), (answers, elapsed, batch_stats, state) = value
|
|
239
|
+
record = stats["per_device"][device]
|
|
240
|
+
record["q_points"] += len(group)
|
|
241
|
+
record["triplets"] += sum(counts[i] for i in group)
|
|
242
|
+
record["compute_seconds"] += elapsed
|
|
243
|
+
calculator.q_batch_stats["q_batches"] += 1
|
|
244
|
+
calculator.q_batch_stats["triplet_batches"] += batch_stats[
|
|
245
|
+
"triplet_batches"
|
|
246
|
+
]
|
|
247
|
+
calculator.q_batch_stats["max_q_per_launch"] = max(
|
|
248
|
+
calculator.q_batch_stats["max_q_per_launch"],
|
|
249
|
+
batch_stats["max_q_per_launch"],
|
|
250
|
+
)
|
|
251
|
+
for index, answer in zip(group, answers, strict=True):
|
|
252
|
+
if collision:
|
|
253
|
+
calculator._gamma[:, :, index] = answer.gamma
|
|
254
|
+
if calculator._grid_point_indices is None or index == last:
|
|
255
|
+
calculator._kappa_solver.store(index, answer)
|
|
256
|
+
else:
|
|
257
|
+
pending[index] = answer
|
|
258
|
+
calculator._grid_point_count += 1
|
|
259
|
+
if state is not None:
|
|
260
|
+
last_state = state
|
|
261
|
+
if calculator._log_level:
|
|
262
|
+
print(
|
|
263
|
+
f"phono3py-gpu: GPU {device}: completed "
|
|
264
|
+
f"{calculator._grid_point_count}/"
|
|
265
|
+
f"{len(indices)} q points.",
|
|
266
|
+
flush=True,
|
|
267
|
+
)
|
|
268
|
+
completed += 1
|
|
269
|
+
for future in futures:
|
|
270
|
+
future.result()
|
|
271
|
+
finally:
|
|
272
|
+
cancelled.set()
|
|
273
|
+
ready.abort()
|
|
274
|
+
for process in processes:
|
|
275
|
+
if process.poll() is None:
|
|
276
|
+
process.terminate()
|
|
277
|
+
executor.shutdown(wait=True)
|
|
278
|
+
solver.q_batch_stats = calculator.q_batch_stats
|
|
279
|
+
pp.set_grid_point(int(grid_points[last]))
|
|
280
|
+
if last_state is not None:
|
|
281
|
+
pp.set_interaction_strength(last_state[0], g_zero=last_state[1])
|
|
282
|
+
if not collision:
|
|
283
|
+
calculator._gamma_detail_at_q = None
|
|
284
|
+
for count, index in enumerate(indices):
|
|
285
|
+
answer = pending.pop(index)
|
|
286
|
+
calculator._store_scattering_result(
|
|
287
|
+
index, answer["result"], answer["gamma_N"], answer["gamma_U"]
|
|
288
|
+
)
|
|
289
|
+
solver._gamma_N, solver._gamma_U = answer["gamma_N"], answer["gamma_U"]
|
|
290
|
+
calculator._grid_point_count = count + 1
|
|
291
|
+
if callback is not None:
|
|
292
|
+
# Match the batched single-GPU callback using computed metadata.
|
|
293
|
+
pp._triplets_at_q = answer["triplets"]
|
|
294
|
+
pp._weights_at_q = answer["weights"]
|
|
295
|
+
callback(index)
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _worker():
|
|
299
|
+
from phono3py.phonon3.collision_matrix import CollisionMatrix
|
|
300
|
+
|
|
301
|
+
from phono3py_gpu.interaction import InteractionKernel
|
|
302
|
+
from phono3py_gpu.scattering import GPUCollisionSolver, GPUScatteringSolver
|
|
303
|
+
|
|
304
|
+
output, commands = sys.stdout.buffer, sys.stdin.buffer
|
|
305
|
+
with redirect_stdout(sys.stderr):
|
|
306
|
+
start = time.perf_counter()
|
|
307
|
+
cp = cupy()
|
|
308
|
+
cp.cuda.Device(int(sys.argv[1])).use()
|
|
309
|
+
with open(sys.argv[2], "rb") as stream:
|
|
310
|
+
payload = _load_snapshot(stream)
|
|
311
|
+
pp = payload["pp"]
|
|
312
|
+
engine = InteractionKernel(
|
|
313
|
+
pp, cp.asarray(pp.phonons.frequencies), cp.asarray(pp.phonons.eigenvectors)
|
|
314
|
+
)
|
|
315
|
+
if payload["collision"]:
|
|
316
|
+
collision = CollisionMatrix(
|
|
317
|
+
pp,
|
|
318
|
+
rot_grid_points=payload["rot_grid_points"],
|
|
319
|
+
is_kappa_star=payload["is_kappa_star"],
|
|
320
|
+
lang=payload["lang"],
|
|
321
|
+
)
|
|
322
|
+
solver = GPUCollisionSolver(
|
|
323
|
+
pp, collision, engine=engine, **payload["options"]
|
|
324
|
+
)
|
|
325
|
+
else:
|
|
326
|
+
solver = GPUScatteringSolver(pp, engine=engine, **payload["options"])
|
|
327
|
+
engine.fourier # Prepare the resident FC3 before taking tasks.
|
|
328
|
+
pickle.dump(
|
|
329
|
+
dict(
|
|
330
|
+
setup_seconds=time.perf_counter() - start,
|
|
331
|
+
triplet_batch=engine.batch_size,
|
|
332
|
+
),
|
|
333
|
+
output,
|
|
334
|
+
protocol=5,
|
|
335
|
+
)
|
|
336
|
+
output.flush()
|
|
337
|
+
while (task := pickle.load(commands)) is not None:
|
|
338
|
+
pickle.dump(
|
|
339
|
+
_compute_task(solver, task, payload["collision"]),
|
|
340
|
+
output,
|
|
341
|
+
protocol=5,
|
|
342
|
+
)
|
|
343
|
+
output.flush()
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
if __name__ == "__main__":
|
|
347
|
+
_worker()
|