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.
@@ -0,0 +1,19 @@
1
+ """GPU transport plugin; registration does not initialize CUDA."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ __version__ = version("phono3py-gpu")
6
+
7
+
8
+ def register():
9
+ """Register GPU calculators and the CPU-only geometry initialization hook."""
10
+ from phono3py.conductivity.factory import _REGISTRY
11
+
12
+ from phono3py_gpu.factory import make_lbte, make_rta
13
+ from phono3py_gpu.initialization import install
14
+
15
+ install()
16
+ _REGISTRY["gpu-rta"] = make_rta
17
+ _REGISTRY["gpu-lbte"] = make_lbte
18
+ _REGISTRY["wte-gpu-rta"] = lambda pp, config: make_rta(pp, config, wte=True)
19
+ _REGISTRY["wte-gpu-lbte"] = lambda pp, config: make_lbte(pp, config, wte=True)
phono3py_gpu/_wte.py ADDED
@@ -0,0 +1,521 @@
1
+ """Kappa solvers for the Wigner transport equation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import numpy as np
8
+ from numpy.typing import NDArray
9
+ from phono3py.conductivity.build_components import KappaSettings
10
+ from phono3py.conductivity.collision_matrix_kernel import CollisionMatrixKernel
11
+ from phono3py.conductivity.grid_point_data import GridPointAggregates
12
+ from phono3py.conductivity.lbte_collision_solver import LBTECollisionResult
13
+ from phono3py.conductivity.utils import (
14
+ log_kappa_header,
15
+ log_kappa_row,
16
+ log_sigma_header,
17
+ )
18
+ from phonopy.physical_units import get_physical_units
19
+
20
+ from phono3py_gpu.backend import cupy, host
21
+ from phono3py_gpu.kappa import effective_gamma
22
+
23
+ # Threshold in THz below which two modes are considered degenerate and treated
24
+ # as a population (diagonal) term instead of a coherence (off-diagonal) term.
25
+ DEGENERATE_FREQUENCY_THRESHOLD_THZ = 1e-4
26
+
27
+
28
+ def _get_conversion_factor_WTE(volume: float) -> float:
29
+ """Return unit conversion factor for Wigner transport equation kappa.
30
+
31
+ Parameters
32
+ ----------
33
+ volume : float
34
+ Primitive-cell volume in Angstrom^3.
35
+
36
+ Returns
37
+ -------
38
+ float
39
+ Conversion factor in W/(m*K).
40
+
41
+ """
42
+ u = get_physical_units()
43
+ return (u.THz * u.Angstrom) ** 2 * u.EV * u.Hbar / (volume * u.Angstrom**3)
44
+
45
+
46
+ def pair_contributions(f, g, cv, vv, cutoff, conversion):
47
+ """WTE mode pairs; g is a half width in THz, as in phono3py.gamma."""
48
+ cp = cupy()
49
+ f, g, cv, vv = (cp.asarray(x) for x in (f, g, cv, vv))
50
+ omega = f * get_physical_units().THzToEv
51
+ width = g * 2 * get_physical_units().THzToEv
52
+ total = width[..., :, None] + width[..., None, :]
53
+ delta = omega[:, None] - omega[None, :]
54
+ denom = delta**2 + total**2 / 4
55
+ c = cv / cp.where(omega > 0, omega, 1)
56
+ pref = (omega[:, None] + omega[None, :]) * (c[..., :, None] + c[..., None, :]) / 4
57
+ valid = (f[:, None] > cutoff) & (f[None, :] > cutoff) & (denom != 0)
58
+ scalar = cp.where(valid, pref * total / 2 / cp.where(denom != 0, denom, 1), 0)
59
+ return scalar[..., None] * vv * conversion
60
+
61
+
62
+ class GPUWignerRTAKappaSolver:
63
+ """Kappa solver for the Wigner transport equation (WTE).
64
+
65
+ Decomposes kappa into a population term (kappa_P_RTA) and a coherence
66
+ term (kappa_C). The total kappa is kappa_TOT_RTA = kappa_P_RTA + kappa_C.
67
+
68
+ The P and C arrays are allocated in ``finalize()``.
69
+
70
+ Parameters
71
+ ----------
72
+ kappa_settings : KappaSettings
73
+ Shared computation metadata (grid, phonon, symmetry, configuration).
74
+ volume : float
75
+ Primitive-cell volume in Angstrom^3.
76
+ log_level : int
77
+ Verbosity level.
78
+
79
+ """
80
+
81
+ def __init__(
82
+ self,
83
+ kappa_settings: KappaSettings,
84
+ frequencies: NDArray[np.double],
85
+ volume: float,
86
+ log_level: int = 0,
87
+ ) -> None:
88
+ """Init method."""
89
+ self._kappa_settings = kappa_settings
90
+ self._frequencies = frequencies
91
+ self._conversion_factor_WTE = _get_conversion_factor_WTE(volume)
92
+ self._log_level = log_level
93
+
94
+ self._kappa_P: NDArray[np.double] | None = None
95
+ self._mode_kappa_P: NDArray[np.double] | None = None
96
+ self._kappa_C: NDArray[np.double] | None = None
97
+ self._mode_kappa_C: NDArray[np.double] | None = None
98
+ self.velocity_operator: NDArray[np.cdouble] | None = None
99
+
100
+ def finalize(self, aggregates: GridPointAggregates) -> None:
101
+ """Compute mode kappa (P + C) and kappa from aggregated data."""
102
+ assert aggregates.vm_by_vm is not None
103
+
104
+ num_sigma, num_temp, num_gp, num_band = aggregates.gamma.shape
105
+ self._mode_kappa_P = np.zeros(
106
+ (num_sigma, num_temp, num_gp, num_band, 6), dtype="double", order="C"
107
+ )
108
+ self._mode_kappa_C = np.zeros(
109
+ (num_sigma, num_temp, num_gp, num_band, num_band, 6),
110
+ dtype="double",
111
+ order="C",
112
+ )
113
+
114
+ self._compute_mode_kappa(aggregates)
115
+
116
+ num_mesh_points = int(np.prod(self._kappa_settings.mesh_numbers))
117
+ self._kappa_P = np.sum(self._mode_kappa_P, axis=(2, 3)) / num_mesh_points
118
+ self._kappa_C = np.sum(self._mode_kappa_C, axis=(2, 3, 4)) / num_mesh_points
119
+
120
+ def _compute_mode_kappa(self, aggregates: GridPointAggregates) -> None:
121
+ cp = cupy()
122
+ gamma = effective_gamma(aggregates)
123
+ for i, gp in enumerate(self._kappa_settings.grid_points):
124
+ f = cp.asarray(self._frequencies[gp])
125
+ pair = pair_contributions(
126
+ f,
127
+ gamma[:, :, i],
128
+ aggregates.mode_heat_capacities[:, i],
129
+ aggregates.vm_by_vm[i],
130
+ self._kappa_settings.cutoff_frequency,
131
+ self._conversion_factor_WTE,
132
+ ).real
133
+ population = (
134
+ cp.abs(f[:, None] - f[None, :]) < DEGENERATE_FREQUENCY_THRESHOLD_THZ
135
+ )
136
+ p = pair * population[..., None]
137
+ self._mode_kappa_P[:, :, i] = host((p.sum(axis=-2) + p.sum(axis=-3)) / 2)
138
+ self._mode_kappa_C[:, :, i] = host(pair * (~population)[..., None])
139
+
140
+ @property
141
+ def kappa(self) -> NDArray[np.double] | None:
142
+ """Return total Wigner kappa (kappa_P + kappa_C)."""
143
+ if self._kappa_P is None or self._kappa_C is None:
144
+ return None
145
+
146
+ return self._kappa_P + self._kappa_C
147
+
148
+ @property
149
+ def kappa_TOT_RTA(self) -> NDArray[np.double] | None:
150
+ """Return total Wigner kappa (same as ``kappa``)."""
151
+ return self.kappa
152
+
153
+ @property
154
+ def kappa_P_RTA(self) -> NDArray[np.double] | None:
155
+ """Return population kappa, shape (num_sigma, num_temp, 6)."""
156
+ return self._kappa_P
157
+
158
+ @property
159
+ def mode_kappa(self) -> NDArray[np.double] | None:
160
+ """Return population mode kappa.
161
+
162
+ Shape: (num_sigma, num_temp, num_gp, num_band0, 6).
163
+
164
+ """
165
+ return self._mode_kappa_P
166
+
167
+ @property
168
+ def kappa_C(self) -> NDArray[np.double] | None:
169
+ """Return coherence kappa, shape (num_sigma, num_temp, 6)."""
170
+ return self._kappa_C
171
+
172
+ @property
173
+ def mode_kappa_C(self) -> NDArray[np.double] | None:
174
+ """Return coherence mode kappa.
175
+
176
+ Shape: (num_sigma, num_temp, num_gp, num_band0, num_band, 6).
177
+
178
+ """
179
+ return self._mode_kappa_C
180
+
181
+ # ------------------------------------------------------------------
182
+ # Properties — per-grid-point data
183
+ # ------------------------------------------------------------------
184
+
185
+ def get_extra_grid_point_output(self) -> dict[str, Any]:
186
+ """Return per-grid-point extra arrays for HDF5 output.
187
+
188
+ Returns the full velocity operator array. The caller is responsible
189
+ for slicing by grid-point index.
190
+
191
+ """
192
+ return {"velocity_operator": self.velocity_operator}
193
+
194
+ def log_kappa(
195
+ self,
196
+ num_ignored_phonon_modes: NDArray[np.int64] | None = None,
197
+ num_phonon_modes: int | None = None,
198
+ ) -> None:
199
+ """Print K_P, K_C, K_T rows for the Wigner-RTA conductivity."""
200
+ if not self._log_level:
201
+ return
202
+
203
+ kappa_tot = self.kappa
204
+ show_ipm = (
205
+ self._log_level > 1
206
+ and num_ignored_phonon_modes is not None
207
+ and num_phonon_modes is not None
208
+ )
209
+
210
+ for i, sigma in enumerate(self._kappa_settings.sigmas):
211
+ log_kappa_header(sigma, show_ipm=show_ipm)
212
+ for j, t in enumerate(self._kappa_settings.temperatures):
213
+ ipm = (
214
+ int(num_ignored_phonon_modes[i, j])
215
+ if show_ipm and num_ignored_phonon_modes is not None
216
+ else None
217
+ )
218
+ log_kappa_row("K_P\t", t, self._kappa_P[i, j], ipm, num_phonon_modes)
219
+ print(" ")
220
+ for j, t in enumerate(self._kappa_settings.temperatures):
221
+ ipm = (
222
+ int(num_ignored_phonon_modes[i, j])
223
+ if show_ipm and num_ignored_phonon_modes is not None
224
+ else None
225
+ )
226
+ log_kappa_row("K_C\t", t, self._kappa_C[i, j], ipm, num_phonon_modes)
227
+ print(" ")
228
+ for j, t in enumerate(self._kappa_settings.temperatures):
229
+ ipm = (
230
+ int(num_ignored_phonon_modes[i, j])
231
+ if show_ipm and num_ignored_phonon_modes is not None
232
+ else None
233
+ )
234
+ log_kappa_row("K_T\t", t, kappa_tot[i, j], ipm, num_phonon_modes)
235
+ print("", flush=True)
236
+
237
+ def get_extra_kappa_output(self) -> dict[str, Any]:
238
+ """Return Wigner-specific extra arrays keyed by HDF5 dataset name.
239
+
240
+ Sigma-dependent values have sigma as their first axis; the caller
241
+ slices them with ``value[i_sigma]``. Sigma-independent values
242
+ (e.g. velocity_operator) are written as-is for every sigma.
243
+
244
+ """
245
+ return {
246
+ "kappa_TOT_RTA": self.kappa_TOT_RTA,
247
+ "kappa_P_RTA": self._kappa_P,
248
+ "kappa_C": self._kappa_C,
249
+ "mode_kappa": self._mode_kappa_P,
250
+ "mode_kappa_P_RTA": self._mode_kappa_P,
251
+ "mode_kappa_C": self._mode_kappa_C,
252
+ "velocity_operator": self.velocity_operator,
253
+ }
254
+
255
+
256
+ class GPUWignerLBTEKappaSolver:
257
+ """LBTE kappa solver with added Wigner coherence (C) term.
258
+
259
+ Composes a CollisionMatrixKernel for the standard LBTE solve (P-term) and
260
+ adds the coherence (C) term from the stored velocity operator outer
261
+ products and linewidths.
262
+
263
+ Stage 1 (per-grid-point): store() delegates collision data to the solver.
264
+
265
+ Stage 2 (global): finalize() calls solver.solve() for the P-term kappa,
266
+ then computes the C-term from the stored outer products and linewidths.
267
+
268
+ Parameters
269
+ ----------
270
+ solver : CollisionMatrixKernel
271
+ Shared solver for the P-term (standard LBTE).
272
+ kappa_settings : KappaSettings
273
+ Shared computation metadata (grid, phonon, symmetry, configuration).
274
+ volume : float
275
+ Primitive-cell volume in Angstrom^3.
276
+ is_reducible_collision_matrix : bool, optional
277
+ When True the C-term is not computed (not implemented). Default False.
278
+ log_level : int, optional
279
+ Verbosity level. Default 0.
280
+
281
+ """
282
+
283
+ def __init__(
284
+ self,
285
+ solver: CollisionMatrixKernel,
286
+ kappa_settings: KappaSettings,
287
+ frequencies: NDArray[np.double],
288
+ volume: float,
289
+ is_reducible_collision_matrix: bool = False,
290
+ log_level: int = 0,
291
+ ) -> None:
292
+ """Init method."""
293
+ self._solver = solver
294
+ self._kappa_settings = kappa_settings
295
+ self._frequencies = frequencies
296
+ self._conversion_factor_WTE = _get_conversion_factor_WTE(volume)
297
+ self._is_reducible = is_reducible_collision_matrix
298
+ self._log_level = log_level
299
+
300
+ self.velocity_operator: NDArray[np.cdouble] | None = None
301
+
302
+ # C-term output arrays.
303
+ num_sigma = len(kappa_settings.sigmas)
304
+ num_temp = len(kappa_settings.temperatures)
305
+ num_ir = len(kappa_settings.grid_points)
306
+ num_band0 = len(kappa_settings.band_indices)
307
+ num_band = frequencies.shape[1]
308
+ self._mode_kappa_C: NDArray[np.cdouble] | None = np.zeros(
309
+ (num_sigma, num_temp, num_ir, num_band0, num_band, 6), dtype="complex128"
310
+ )
311
+ self._kappa_C: NDArray[np.double] | None = np.zeros(
312
+ (num_sigma, num_temp, 6), dtype="double"
313
+ )
314
+
315
+ # ------------------------------------------------------------------
316
+ # Public interface
317
+ # ------------------------------------------------------------------
318
+
319
+ def store(
320
+ self,
321
+ i_gp: int,
322
+ collision_result: LBTECollisionResult,
323
+ ) -> None:
324
+ """Store collision matrix row for this grid point.
325
+
326
+ Parameters
327
+ ----------
328
+ i_gp : int
329
+ Loop index over ir_grid_points (0-based).
330
+ collision_result : LBTECollisionResult
331
+ Result from LBTECollisionSolver.compute().
332
+
333
+ """
334
+ self._solver.store(i_gp, collision_result)
335
+
336
+ def finalize(
337
+ self,
338
+ aggregates: GridPointAggregates,
339
+ ) -> None:
340
+ """Finalize P-term via solver, then compute C-term.
341
+
342
+ The standard LBTE kappa table is suppressed (replaced by the Wigner
343
+ table printed at the end of this method) when log_level > 0.
344
+
345
+ """
346
+ if self._is_reducible:
347
+ print(
348
+ " WARNING: Coherences conductivity not implemented for "
349
+ "is_reducible_collision_matrix=True"
350
+ )
351
+ self._mode_kappa_C = None
352
+ self._kappa_C = None
353
+ prev_sigma = -1
354
+ for i_sigma, i_temp in self._solver.solve_iter(aggregates):
355
+ self._compute_coherence_kappa_at(aggregates, i_sigma, i_temp)
356
+ if self._log_level:
357
+ if i_sigma != prev_sigma:
358
+ log_sigma_header(self._kappa_settings.sigmas[i_sigma])
359
+ prev_sigma = i_sigma
360
+ self._log_wigner_kappa_at(i_sigma, i_temp)
361
+
362
+ # ------------------------------------------------------------------
363
+ # Properties — delegated to solver (LBTE P-term results)
364
+ # ------------------------------------------------------------------
365
+
366
+ @property
367
+ def solver(self) -> CollisionMatrixKernel:
368
+ """Return the underlying CollisionMatrixKernel."""
369
+ return self._solver
370
+
371
+ @property
372
+ def kappa(self) -> NDArray[np.double]:
373
+ """Return LBTE thermal conductivity, shape (num_sigma, num_temp, 6)."""
374
+ return self._solver.kappa
375
+
376
+ # ------------------------------------------------------------------
377
+ # Properties — Wigner-specific aliases
378
+ # ------------------------------------------------------------------
379
+
380
+ @property
381
+ def kappa_P_exact(self) -> NDArray[np.double]:
382
+ """Return LBTE kappa (P-exact term) — alias for kappa."""
383
+ return self._solver.kappa
384
+
385
+ @property
386
+ def kappa_P_RTA(self) -> NDArray[np.double]:
387
+ """Return RTA kappa (P-RTA term) — alias for kappa_RTA."""
388
+ return self._solver.kappa_RTA
389
+
390
+ @property
391
+ def mode_kappa_P_exact(self) -> NDArray[np.double]:
392
+ """Return mode LBTE kappa (P-exact term) — alias for mode_kappa."""
393
+ return self._solver.mode_kappa
394
+
395
+ @property
396
+ def mode_kappa_P_RTA(self) -> NDArray[np.double]:
397
+ """Return mode RTA kappa (P-RTA term) — alias for mode_kappa_RTA."""
398
+ return self._solver.mode_kappa_RTA
399
+
400
+ # ------------------------------------------------------------------
401
+ # Properties — C-term
402
+ # ------------------------------------------------------------------
403
+
404
+ @property
405
+ def kappa_C(self) -> NDArray[np.double] | None:
406
+ """Return coherence kappa, shape (num_sigma, num_temp, 6)."""
407
+ return self._kappa_C
408
+
409
+ @property
410
+ def mode_kappa_C(self) -> NDArray[np.cdouble] | None:
411
+ """Return per-mode coherence kappa (complex)."""
412
+ return self._mode_kappa_C
413
+
414
+ @property
415
+ def mode_kappa(self) -> NDArray[np.double]:
416
+ """Return mode LBTE kappa."""
417
+ return self._solver.mode_kappa
418
+
419
+ def get_extra_kappa_output(self) -> dict[str, NDArray | None]:
420
+ """Return Wigner-specific LBTE kappa arrays keyed by HDF5 dataset name.
421
+
422
+ Keys
423
+ ----
424
+ kappa_TOT_exact : (num_sigma, num_temp, 6)
425
+ kappa_TOT_RTA : (num_sigma, num_temp, 6)
426
+ kappa_P_exact : (num_sigma, num_temp, 6)
427
+ kappa_P_RTA : (num_sigma, num_temp, 6)
428
+ kappa_C : (num_sigma, num_temp, 6) or None
429
+ mode_kappa_P_exact : (num_sigma, num_temp, num_gp, num_band0, 6)
430
+ mode_kappa_P_RTA : (num_sigma, num_temp, num_gp, num_band0, 6)
431
+ mode_kappa_C : (num_sigma, num_temp, num_gp, num_band0, num_band, 6)
432
+ or None
433
+
434
+ """
435
+ kappa_P_exact = self._solver.kappa
436
+ kappa_P_RTA = self._solver.kappa_RTA
437
+ kappa_C = self._kappa_C
438
+ if kappa_C is not None:
439
+ kappa_TOT_exact: NDArray[np.double] | None = kappa_P_exact + kappa_C
440
+ kappa_TOT_RTA: NDArray[np.double] | None = kappa_P_RTA + kappa_C
441
+ else:
442
+ kappa_TOT_exact = kappa_P_exact
443
+ kappa_TOT_RTA = kappa_P_RTA
444
+ mode_kappa_C = self._mode_kappa_C
445
+ return {
446
+ "kappa_TOT_exact": kappa_TOT_exact,
447
+ "kappa_TOT_RTA": kappa_TOT_RTA,
448
+ "kappa_P_exact": kappa_P_exact,
449
+ "kappa_P_RTA": kappa_P_RTA,
450
+ "kappa_C": kappa_C,
451
+ "mode_kappa": self._solver.mode_kappa,
452
+ "mode_kappa_P_exact": self._solver.mode_kappa,
453
+ "mode_kappa_P_RTA": self._solver.mode_kappa_RTA,
454
+ "mode_kappa_C": None if mode_kappa_C is None else mode_kappa_C.real,
455
+ "velocity_operator": self.velocity_operator,
456
+ }
457
+
458
+ # ------------------------------------------------------------------
459
+ # Private: C-term computation
460
+ # ------------------------------------------------------------------
461
+
462
+ def _compute_coherence_kappa_at(
463
+ self,
464
+ aggregates: GridPointAggregates,
465
+ i_sigma: int,
466
+ i_temp: int,
467
+ ) -> None:
468
+ cp = cupy()
469
+ if self._mode_kappa_C is None:
470
+ return
471
+ total = cp.zeros(6)
472
+ for i, gp in enumerate(self._kappa_settings.grid_points):
473
+ f = cp.asarray(self._frequencies[gp])
474
+ g = self._solver.get_main_diagonal(i, i_sigma, i_temp)
475
+ pair = pair_contributions(
476
+ f,
477
+ g,
478
+ aggregates.mode_heat_capacities[i_temp, i],
479
+ aggregates.vm_by_vm[i],
480
+ self._kappa_settings.cutoff_frequency,
481
+ self._conversion_factor_WTE,
482
+ )
483
+ pair *= (
484
+ cp.abs(f[:, None] - f[None, :]) > DEGENERATE_FREQUENCY_THRESHOLD_THZ
485
+ )[..., None]
486
+ self._mode_kappa_C[i_sigma, i_temp, i] = host(pair)
487
+ total += pair.sum(axis=(0, 1)).real
488
+ self._kappa_C[i_sigma, i_temp] = host(
489
+ total / int(np.prod(self._kappa_settings.mesh_numbers))
490
+ )
491
+
492
+ def _log_wigner_kappa_at(self, i_sigma: int, i_temp: int) -> None:
493
+ """Print Wigner LBTE kappa for one (sigma, temperature) pair."""
494
+ t = self._kappa_settings.temperatures[i_temp]
495
+ if t <= 0:
496
+ return
497
+
498
+ kappa_P = self._solver._kappa[i_sigma, i_temp]
499
+ kappa_P_RTA = self._solver._kappa_RTA[i_sigma, i_temp]
500
+ kappa_C = self._kappa_C
501
+
502
+ print(
503
+ ("#%6s " + " %-10s" * 6)
504
+ % (" \t\t T(K)", "xx", "yy", "zz", "yz", "xz", "xy")
505
+ )
506
+ print("K_P_exact\t\t" + ("%7.1f " + " %10.3f" * 6) % ((t,) + tuple(kappa_P)))
507
+ print(
508
+ "(K_P_RTA)\t\t" + ("%7.1f " + " %10.3f" * 6) % ((t,) + tuple(kappa_P_RTA))
509
+ )
510
+ if kappa_C is not None:
511
+ print(
512
+ "K_C \t\t"
513
+ + ("%7.1f " + " %10.3f" * 6) % ((t,) + tuple(kappa_C[i_sigma, i_temp]))
514
+ )
515
+ print(" ")
516
+ kappa_tot = kappa_P + kappa_C[i_sigma, i_temp]
517
+ print(
518
+ "K_TOT=K_P_exact+K_C\t"
519
+ + ("%7.1f " + " %10.3f" * 6) % ((t,) + tuple(kappa_tot))
520
+ )
521
+ print("-" * 76, flush=True)
@@ -0,0 +1,65 @@
1
+ """Device arrays and bounded workspaces shared by the transport solvers."""
2
+
3
+ from functools import lru_cache
4
+ from pathlib import Path
5
+
6
+ import numpy as np
7
+
8
+
9
+ @lru_cache(maxsize=1)
10
+ def cupy():
11
+ """Return CuPy after checking that an accessible CUDA device exists."""
12
+ try:
13
+ import cupy as cp
14
+ except ModuleNotFoundError as exc:
15
+ if exc.name != "cupy":
16
+ raise
17
+ raise ModuleNotFoundError(
18
+ "CuPy is required for GPU calculations. Install phono3py-gpu with "
19
+ "one of the cuda11, cuda12, or cuda13 extras, or install a matching "
20
+ "CuPy package separately. See the README installation instructions."
21
+ ) from exc
22
+
23
+ if cp.cuda.runtime.getDeviceCount() == 0:
24
+ raise RuntimeError("phono3py-gpu requires a CUDA GPU.")
25
+ return cp
26
+
27
+
28
+ def report_devices(stage, device_ids, note=""):
29
+ runtime = cupy().cuda.runtime
30
+ labels = []
31
+ for device in device_ids:
32
+ name = runtime.getDeviceProperties(device)["name"].decode()
33
+ labels.append(f"GPU {device} ({name})")
34
+ print(f"phono3py-gpu: {stage}: {', '.join(labels)}{note}", flush=True)
35
+
36
+
37
+ def host(array):
38
+ """Synchronize a device result at the public NumPy API boundary."""
39
+ if isinstance(array, np.ndarray):
40
+ return array
41
+ return cupy().asnumpy(array)
42
+
43
+
44
+ def eigh(matrix):
45
+ """Diagonalize FP64 real-symmetric or complex-Hermitian device matrices."""
46
+ import cupyx
47
+
48
+ cp = cupy()
49
+ with cupyx.errstate(linalg="raise"):
50
+ return cp.linalg.eigh(matrix)
51
+
52
+
53
+ @lru_cache(maxsize=None)
54
+ def kernel(filename, name):
55
+ """Compile a packaged CUDA kernel, retaining FP64 arithmetic."""
56
+ code = (Path(__file__).parent / "kernels" / filename).read_text()
57
+ return cupy().RawKernel(code, name, options=("--std=c++11", "--fmad=false"))
58
+
59
+
60
+ def batch_size(bytes_per_item, maximum=128):
61
+ """Bound a temporary batch to one quarter of currently free memory."""
62
+ free, _ = cupy().cuda.runtime.memGetInfo()
63
+ if bytes_per_item > free // 2:
64
+ raise MemoryError("A single GPU work item exceeds available device memory.")
65
+ return max(1, min(maximum, free // 4 // max(1, bytes_per_item)))