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,258 @@
1
+ """FP64 dynamical matrices and analytical Cartesian derivatives on CUDA."""
2
+
3
+ import numpy as np
4
+ from phonopy.harmonic.dynamical_matrix import DynamicalMatrixGL, DynamicalMatrixWang
5
+
6
+ from phono3py_gpu.backend import batch_size, cupy, eigh
7
+
8
+
9
+ class Harmonic:
10
+ """Cache a snapshot of FC2, shortest vectors and NAC data on one device."""
11
+
12
+ def __init__(self, dm):
13
+ cp = cupy()
14
+ self.dm = dm
15
+ self.primitive = dm.primitive
16
+ self.na = len(dm.primitive)
17
+ self.nb = 3 * self.na
18
+ self.cell = cp.asarray(dm.primitive.cell)
19
+ self.recip = cp.linalg.inv(self.cell)
20
+ self.mass = cp.asarray(dm.normalization_masses)
21
+ self.p2s = dm.primitive.p2s_map
22
+ self.s2p = dm.primitive.s2p_map
23
+ self.groups = [np.flatnonzero(self.s2p == p) for p in self.p2s]
24
+ self.svecs, self.multi = dm.primitive.get_smallest_vectors()
25
+ self.sv = cp.asarray(self.svecs)
26
+ self.count = cp.asarray(self.multi[:, :, 0])
27
+ self.start = cp.asarray(self.multi[:, :, 1])
28
+ self.is_gl = isinstance(dm, DynamicalMatrixGL)
29
+ self.is_wang = isinstance(dm, DynamicalMatrixWang)
30
+ if self.is_gl and dm.short_range_force_constants is None:
31
+ dm.make_Gonze_nac_dataset()
32
+ fc = dm.short_range_force_constants if self.is_gl else dm.force_constants
33
+ self.fc = cp.asarray(fc if fc.shape[0] != fc.shape[1] else fc[self.p2s])
34
+ self.group_indices = cp.asarray(np.asarray(self.groups))
35
+ self.fc_blocks = self.fc[:, self.group_indices]
36
+ if self.is_gl or self.is_wang:
37
+ self.born = cp.asarray(dm.born)
38
+ self.eps = cp.asarray(dm.dielectric_constant)
39
+ if self.is_gl:
40
+ self.gs = cp.asarray(dm._G_list)
41
+ phase = cp.exp(
42
+ 2j * cp.pi * (self.gs @ cp.asarray(dm.primitive.positions).T)
43
+ )
44
+ self.gphase = phase[:, :, None] * phase[:, None, :].conj()
45
+
46
+ def _phase(self, q, derivative=False):
47
+ cp = cupy()
48
+ values = cp.exp(2j * cp.pi * (q @ self.sv.T))
49
+ if derivative:
50
+ values = values[:, None, :] * (2j * cp.pi * (self.sv @ self.cell).T)[None]
51
+ # Prefix sums permit arbitrary packed vector order and multiplicities.
52
+ prefix = cp.concatenate(
53
+ (
54
+ cp.zeros((*values.shape[:-1], 1), values.dtype),
55
+ cp.cumsum(values, axis=-1),
56
+ ),
57
+ axis=-1,
58
+ )
59
+ return (
60
+ prefix[..., self.start + self.count] - prefix[..., self.start]
61
+ ) / self.count
62
+
63
+ def matrices(self, qpoints, derivative=False, q_direction=None):
64
+ """Return D(q), or dD/dq_cart, with q as the first axis."""
65
+ cp = cupy()
66
+ q = cp.asarray(qpoints, dtype=cp.float64).reshape(-1, 3)
67
+ n = len(q)
68
+ shape = (n, 3, self.nb, self.nb) if derivative else (n, self.nb, self.nb)
69
+ phases = self._phase(q, derivative)
70
+ base_phases = self._phase(q) if derivative and self.is_wang else phases
71
+ nac, dnac = self._wang(q, q_direction) if self.is_wang else (None, None)
72
+ mass = cp.sqrt(self.mass[:, None] * self.mass[None, :])
73
+ if derivative:
74
+ grouped = phases[:, :, self.group_indices, :].transpose(0, 1, 4, 2, 3)
75
+ block = cp.einsum("qdijs,ijsab->qdiajb", grouped, self.fc_blocks)
76
+ if nac is not None:
77
+ extra = grouped.sum(axis=-1)[..., None, None] * nac[:, None]
78
+ plain = base_phases[:, self.group_indices, :].transpose(0, 3, 1, 2)
79
+ extra += plain.sum(axis=-1)[:, None, ..., None, None] * dnac
80
+ block += extra.transpose(0, 1, 2, 4, 3, 5)
81
+ block /= mass[None, None, :, None, :, None]
82
+ else:
83
+ grouped = phases[:, self.group_indices, :].transpose(0, 3, 1, 2)
84
+ block = cp.einsum("qijs,ijsab->qiajb", grouped, self.fc_blocks)
85
+ if nac is not None:
86
+ extra = grouped.sum(axis=-1)[..., None, None] * nac
87
+ block += extra.transpose(0, 1, 3, 2, 4)
88
+ block /= mass[None, :, None, :, None]
89
+ result = block.reshape(shape)
90
+ if self.is_gl:
91
+ result += self._gonze(q, derivative, q_direction)
92
+ return (result + result.swapaxes(-1, -2).conj()) * 0.5
93
+
94
+ def _wang(self, q, q_direction):
95
+ cp = cupy()
96
+ qc = q @ self.recip.T
97
+ if q_direction is not None:
98
+ qc = cp.broadcast_to(cp.asarray(q_direction) @ self.recip.T, qc.shape)
99
+ valid = cp.linalg.norm(qc, axis=1) > self.dm.Q_DIRECTION_TOLERANCE
100
+ b = cp.einsum("qi,ij,qj->q", qc, self.eps, qc, optimize=True)
101
+ b = cp.where(valid, b, 1)
102
+ a = cp.einsum("qb,iba->qia", qc, self.born)
103
+ outer = cp.einsum("qia,qjb->qijab", a, a)
104
+ scale = self.dm.nac_factor / (len(self.s2p) // self.na)
105
+ nac = outer / b[:, None, None, None, None]
106
+ dnac = cp.empty((len(q), 3, self.na, self.na, 3, 3))
107
+ for d in range(3):
108
+ top = cp.einsum("ia,qjb->qijab", self.born[:, d], a) + cp.einsum(
109
+ "qia,jb->qijab", a, self.born[:, d]
110
+ )
111
+ db = 2 * (qc @ self.eps)[:, d]
112
+ dnac[:, d] = (
113
+ top / b[:, None, None, None, None]
114
+ - outer * (db / b**2)[:, None, None, None, None]
115
+ )
116
+ return nac * (valid * scale)[:, None, None, None, None], dnac * (valid * scale)[
117
+ :, None, None, None, None, None
118
+ ]
119
+
120
+ def _gonze(self, q, derivative, q_direction):
121
+ cp = cupy()
122
+ dm = self.dm
123
+ # G summation is batched independently of q and atom pairs.
124
+ Q = self.gs[None] + (q @ self.recip.T)[:, None]
125
+ valid = cp.linalg.norm(Q, axis=-1) >= dm.Q_DIRECTION_TOLERANCE
126
+ zero = ~valid
127
+ if q_direction is not None:
128
+ direction = cp.asarray(q_direction) @ self.recip.T
129
+ if float(cp.linalg.norm(direction)) > 0:
130
+ Q = cp.where(zero[..., None], direction, Q)
131
+ valid = cp.ones_like(valid)
132
+ v = Q @ self.eps
133
+ b = cp.sum(Q * v, axis=-1)
134
+ b = cp.where(valid, b, 1)
135
+ c = cp.exp(-b / (4 * dm._Lambda**2))
136
+ if q_direction is not None and not derivative:
137
+ c = cp.where(zero, 1.0, c)
138
+ c *= valid
139
+ if derivative:
140
+ eye = cp.eye(3)
141
+ t = (
142
+ eye[None, None, :, :, None] * Q[:, :, None, None, :]
143
+ + Q[:, :, None, :, None] * eye[None, None, :, None, :]
144
+ ) / b[..., None, None, None]
145
+ k = v * (2 / b**2 + 1 / (2 * dm._Lambda**2 * b))[..., None]
146
+ t -= Q[:, :, None, :, None] * Q[:, :, None, None, :] * k[..., :, None, None]
147
+ t *= c[..., None, None, None]
148
+ out = cp.einsum(
149
+ "qgdbc,gij,iba,jce->qdiaje",
150
+ t,
151
+ self.gphase,
152
+ self.born,
153
+ self.born,
154
+ optimize=True,
155
+ )
156
+ out = out.reshape(len(q), 3, self.na, 3, self.na, 3)
157
+ else:
158
+ t = Q[..., :, None] * Q[..., None, :] * (c / b)[..., None, None]
159
+ out = cp.einsum(
160
+ "qgbc,gij,iba,jce->qiaje",
161
+ t,
162
+ self.gphase,
163
+ self.born,
164
+ self.born,
165
+ optimize=True,
166
+ )
167
+ if not dm._with_full_terms:
168
+ for i in range(self.na):
169
+ out[:, i, :, i, :] -= cp.asarray(dm._dd_q0[i])
170
+ out *= dm.nac_factor
171
+ if dm._with_full_terms:
172
+ # Full Ewald real-space terms use the same stored H tensor.
173
+ real = self._gonze_real(q, derivative)
174
+ out += real
175
+ if not derivative:
176
+ drift = cp.asarray(
177
+ dm._dd_q0 + dm._dd_limiting * self.na + dm._dd_real_q0
178
+ )
179
+ for i in range(self.na):
180
+ out[:, i, :, i, :] += cp.asarray(dm._dd_limiting) - drift[i]
181
+ mass = 1 / cp.sqrt(self.mass[:, None] * self.mass[None, :])
182
+ out *= (
183
+ mass[None, :, None, :, None]
184
+ if not derivative
185
+ else mass[None, None, :, None, :, None]
186
+ )
187
+ return out.reshape(
188
+ (len(q), 3, self.nb, self.nb) if derivative else (len(q), self.nb, self.nb)
189
+ )
190
+
191
+ def _gonze_real(self, q, derivative):
192
+ cp = cupy()
193
+ dm = self.dm
194
+ shape = (
195
+ (len(q), 3, self.na, 3, self.na, 3)
196
+ if derivative
197
+ else (len(q), self.na, 3, self.na, 3)
198
+ )
199
+ result = cp.zeros(shape, dtype=cp.complex128)
200
+ phase = cp.exp(2j * cp.pi * (q @ self.sv.T))
201
+ h = -(dm._Lambda**3) * cp.asarray(dm._H) * cp.linalg.det(self.eps) ** (-0.5)
202
+ for s in range(len(self.s2p)):
203
+ i = int(dm._s2pp_map[s])
204
+ for j in range(self.na):
205
+ count, start = self.multi[s, j]
206
+ val = phase[:, start, None, None] * h[:, :, start]
207
+ val = (val + val.swapaxes(-1, -2).conj()) / (2 * count)
208
+ if derivative:
209
+ # Differentiate before imposing the Hermitian block convention.
210
+ raw = phase[:, start, None, None] * h[:, :, start]
211
+ dval = (
212
+ raw[:, None]
213
+ * (2j * cp.pi * (self.sv[start] @ self.cell))[
214
+ None, :, None, None
215
+ ]
216
+ )
217
+ result[:, :, i, :, j, :] += (
218
+ dval + dval.swapaxes(-1, -2).conj()
219
+ ) / (2 * count)
220
+ else:
221
+ result[:, i, :, j, :] += val
222
+ return result
223
+
224
+ def solve(self, qpoints, factor):
225
+ """Solve a bounded batch and return frequencies and column eigenvectors."""
226
+ cp = cupy()
227
+ qpoints = np.asarray(qpoints).reshape(-1, 3)
228
+ n = len(qpoints)
229
+ freq = cp.empty((n, self.nb))
230
+ vectors = cp.empty((n, self.nb, self.nb), dtype=cp.complex128)
231
+ step = batch_size(16 * self.nb**2 * 6 + 16 * len(self.svecs), maximum=256)
232
+ for start in range(0, n, step):
233
+ vals, vecs = eigh(self.matrices(qpoints[start : start + step]))
234
+ freq[start : start + step] = cp.sign(vals) * cp.sqrt(cp.abs(vals)) * factor
235
+ vectors[start : start + step] = vecs
236
+ return freq, vectors
237
+
238
+
239
+ def prepare_phonons(pp):
240
+ """Upload canonical upstream phonons without changing their band convention.
241
+
242
+ Tetrahedron interpolation with unaveraged degenerate bands is basis
243
+ dependent. Frequencies exactly on tetrahedron vertices also require the
244
+ same rounding convention. The inexpensive mesh eigensolutions therefore
245
+ remain upstream; FC3 contraction, scattering, velocities, and LBTE solves
246
+ use CUDA. The standalone Harmonic.solve method supplies GPU eigensolutions
247
+ for callers that do not require this canonical convention.
248
+ """
249
+ cp = cupy()
250
+ pp.nac_q_direction = None
251
+ pp.run_phonon_solver_at_gamma()
252
+ if not pp.phonon_all_done:
253
+ pp.run_phonon_solver()
254
+ return (
255
+ Harmonic(pp.dynamical_matrix),
256
+ cp.asarray(pp.phonons.frequencies),
257
+ cp.asarray(pp.phonons.eigenvectors),
258
+ )
@@ -0,0 +1,50 @@
1
+ """Batch the geometry mask used by FC3 r0 averaging, without starting CUDA."""
2
+
3
+ import numpy as np
4
+ from phono3py.phonon3.interaction import Interaction
5
+
6
+ # Preserve the pinned upstream implementation for independent comparisons.
7
+ reference_all_shortest = Interaction._get_all_shortest
8
+
9
+
10
+ def all_shortest(interaction):
11
+ """Fill (primitive atom, supercell atom, supercell atom) shortest flags."""
12
+ svecs, multi = interaction._svecs, interaction._multi
13
+ primitive = interaction._primitive
14
+ perms = primitive.atomic_permutations
15
+ s2pp = np.array([primitive.p2p_map[i] for i in interaction._s2p])
16
+ lattice = primitive.cell
17
+ ns, na, _ = multi.shape
18
+ eps = np.finfo(np.float64).eps
19
+ for i in range(na):
20
+ for j in range(ns):
21
+ if multi[j, i, 0] > 1:
22
+ continue
23
+ jp = s2pp[j]
24
+ translation = np.flatnonzero(perms[:, j] == interaction._p2s[jp])
25
+ assert len(translation) == 1
26
+ mapped = perms[translation[0]]
27
+ valid = (multi[:, i, 0] <= 1) & (multi[mapped, jp, 0] <= 1)
28
+ k = np.flatnonzero(valid)
29
+ a = svecs[multi[k, i, 1]] - svecs[multi[j, i, 1]]
30
+ b = svecs[multi[mapped[k], jp, 1]]
31
+ da = np.linalg.norm(a @ lattice, axis=1)
32
+ db = np.linalg.norm(b @ lattice, axis=1)
33
+ difference = np.abs(db - da)
34
+ shortest = difference < interaction._symprec
35
+ # Batch BLAS/norm rounding may differ at the strict cutoff. Use the
36
+ # upstream scalar operations for comparisons within roundoff.
37
+ scale = ((np.abs(a) + np.abs(b)) @ np.abs(lattice)).sum(axis=1)
38
+ boundary = np.abs(difference - interaction._symprec) <= (
39
+ 32 * eps * np.maximum(scale, 1)
40
+ )
41
+ for index in np.flatnonzero(boundary):
42
+ distance = np.linalg.norm(a[index] @ lattice)
43
+ mapped_distance = np.linalg.norm(b[index] @ lattice)
44
+ shortest[index] = abs(mapped_distance - distance) < interaction._symprec
45
+ interaction._all_shortest[i, j, k[shortest]] = 1
46
+
47
+
48
+ def install():
49
+ """Install once per process; initialization precedes calculator selection."""
50
+ Interaction._get_all_shortest = all_shortest
@@ -0,0 +1,183 @@
1
+ """GPU Gaussian and linear-tetrahedron three-phonon integration weights."""
2
+
3
+ import numpy as np
4
+ from phonopy.phonon.grid import get_neighboring_grid_points
5
+ from phonopy.phonon.tetrahedron_method import get_tetrahedra_relative_gr_grid_address
6
+
7
+ from phono3py_gpu.backend import cupy, kernel
8
+
9
+ MIN_SHARED_FREQUENCIES = 24
10
+
11
+
12
+ class TetrahedronTopology:
13
+ """Reuse upstream integer BZ neighbours for a fixed interaction mesh."""
14
+
15
+ def __init__(self, pp):
16
+ self.grid = pp.bz_grid
17
+ self.relative = get_tetrahedra_relative_gr_grid_address(
18
+ pp.bz_grid, pp.symmetrize_tetrahedra
19
+ )
20
+ self.neighbours = ({}, {})
21
+
22
+ def vertices(self, triplets):
23
+ vertices = np.empty((len(triplets), 2, len(self.relative), 4), dtype="int64")
24
+ for leg, sign in enumerate((1, -1)):
25
+ cache = self.neighbours[leg]
26
+ for q in np.unique(triplets[:, leg + 1]):
27
+ if q not in cache:
28
+ cache[q] = get_neighboring_grid_points(
29
+ int(q), sign * self.relative, self.grid
30
+ )
31
+ vertices[:, leg] = [cache[q] for q in triplets[:, leg + 1]]
32
+ return vertices
33
+
34
+
35
+ def average_axis(values, ids, axis, minimum=False):
36
+ """Average or AND-mask each complete degenerate block, in place."""
37
+ cp = cupy()
38
+ for identifier in np.unique(ids):
39
+ indices = np.flatnonzero(ids == identifier)
40
+ if len(indices) < 2:
41
+ continue
42
+ key = [slice(None)] * values.ndim
43
+ key[axis] = cp.asarray(indices)
44
+ block = values[tuple(key)]
45
+ reduced = (
46
+ block.min(axis=axis, keepdims=True)
47
+ if minimum
48
+ else block.mean(axis=axis, keepdims=True)
49
+ )
50
+ values[tuple(key)] = reduced
51
+
52
+
53
+ def average_batches(values, ids, axis, batch_axis, minimum=False):
54
+ """Average contiguous float64 weights or reduce int8 masks in place.
55
+
56
+ Upstream ids contain each group's first band index, with shape (batch, band).
57
+ A single row shares the same degeneracy groups across all batches.
58
+ """
59
+ cp = cupy()
60
+ kernel("degeneracy.cu", "minimum_groups" if minimum else "average_groups")(
61
+ ((values.size + 127) // 128,),
62
+ (128,),
63
+ (
64
+ values,
65
+ cp.asarray(ids, order="C"),
66
+ np.int64(values.size),
67
+ np.int32(values.shape[axis]),
68
+ np.int64(np.prod(values.shape[axis + 1 :])),
69
+ np.int64(np.prod(values.shape[batch_axis + 1 :])),
70
+ np.int32(len(ids)),
71
+ ),
72
+ )
73
+
74
+
75
+ def channel_bounds(frequencies, vertices):
76
+ """Extrema over all tetrahedron vertices, reused by the initial-band tiles."""
77
+ cp = cupy()
78
+ nt, _, nth, _ = vertices.shape
79
+ nb = frequencies.shape[1]
80
+ bounds = cp.empty((4, nt, nb, nb), dtype=cp.float64)
81
+ kernel("tetrahedron.cu", "channel_bounds")(
82
+ ((nt * nb * nb + 127) // 128,),
83
+ (128,),
84
+ (
85
+ bounds,
86
+ frequencies,
87
+ cp.asarray(vertices),
88
+ np.int32(nt),
89
+ np.int32(nb),
90
+ np.int32(nth),
91
+ ),
92
+ )
93
+ return bounds
94
+
95
+
96
+ def weights(
97
+ pp,
98
+ triplets,
99
+ frequencies,
100
+ frequency_points,
101
+ sigma,
102
+ sigma_cutoff=None,
103
+ collision=False,
104
+ vertices=None,
105
+ bounds=None,
106
+ ):
107
+ """Return device (g, g_zero), in the upstream channel and band order."""
108
+ cp = cupy()
109
+ f0 = cp.asarray(frequency_points)
110
+ nb = frequencies.shape[1]
111
+ nf = f0.shape[-1]
112
+ nc = 3 if collision else 2
113
+ shape = (len(triplets), nf, nb, nb)
114
+ tp = cp.asarray(triplets)
115
+ if sigma is not None:
116
+ f1 = frequencies[tp[:, 1]][:, None, :, None]
117
+ f2 = frequencies[tp[:, 2]][:, None, None, :]
118
+ omega = f0[:, :, None, None] if f0.ndim == 2 else f0[None, :, None, None]
119
+ args = (omega - f1 - f2, omega + f1 - f2, omega - f1 + f2)
120
+ terms = [
121
+ cp.exp(-x * x / (2 * sigma * sigma)) / (np.sqrt(2 * np.pi) * sigma)
122
+ for x in args
123
+ ]
124
+ zero = cp.zeros(shape, dtype=cp.int8)
125
+ if sigma_cutoff is not None and sigma_cutoff > 0:
126
+ zero = (
127
+ (cp.abs(args[0]) > sigma_cutoff * sigma)
128
+ & (cp.abs(args[1]) > sigma_cutoff * sigma)
129
+ & (cp.abs(args[2]) > sigma_cutoff * sigma)
130
+ ).astype(cp.int8)
131
+ g = cp.stack(
132
+ [terms[0], terms[1] - terms[2]]
133
+ + ([terms[0] + terms[1] + terms[2]] if collision else [])
134
+ )
135
+ g *= (zero == 0)[None]
136
+ else:
137
+ if vertices is None:
138
+ vertices = TetrahedronTopology(pp).vertices(triplets)
139
+ shared = nf >= MIN_SHARED_FREQUENCIES
140
+ if shared and bounds is None:
141
+ bounds = channel_bounds(frequencies, vertices)
142
+ g = cp.empty((nc, *shape))
143
+ zero = cp.empty(shape, dtype=cp.int8)
144
+ work = len(triplets) * nb * nb * 32 if shared else zero.size
145
+ kernel("tetrahedron.cu", "weights_shared" if shared else "weights")(
146
+ ((work + 127) // 128,),
147
+ (128,),
148
+ (
149
+ g,
150
+ zero,
151
+ frequencies,
152
+ cp.ascontiguousarray(f0),
153
+ cp.asarray(vertices),
154
+ np.int32(len(triplets)),
155
+ np.int32(nf),
156
+ np.int32(nb),
157
+ np.int32(vertices.shape[2]),
158
+ np.int32(nc),
159
+ np.int32(nf if f0.ndim == 2 else 0),
160
+ bounds if bounds is not None else np.uint64(0),
161
+ ),
162
+ )
163
+ if pp.average_degenerate_weights and sigma is None:
164
+ ids = pp.phonons.degenerate_ids
165
+ for leg in (0, 1):
166
+ groups = cp.asarray(ids[triplets[:, leg + 1]])
167
+ average_batches(g, groups, axis=3 + leg, batch_axis=1)
168
+ average_batches(zero, groups, axis=2 + leg, batch_axis=0, minimum=True)
169
+ return g, zero
170
+
171
+
172
+ def sigma_weights(pp, triplets, frequencies, frequency_points, sigmas, **kwargs):
173
+ """Keep each sigma's weights and combine their nonzero supports."""
174
+ integrations = [
175
+ weights(pp, triplets, frequencies, frequency_points, sigma, **kwargs)
176
+ for sigma in sigmas
177
+ ]
178
+ zero = integrations[0][1]
179
+ if len(integrations) > 1:
180
+ zero = zero.copy()
181
+ for _, mask in integrations[1:]:
182
+ zero &= mask
183
+ return integrations, zero