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,270 @@
1
+ """Device-resident FC3 Fourier transforms and phonon-mode contractions."""
2
+
3
+ import os
4
+ from itertools import permutations
5
+
6
+ import numpy as np
7
+ from phono3py.phonon3.triplets import get_nosym_triplets_at_q, get_triplets_at_q
8
+
9
+ from phono3py_gpu.backend import batch_size, cupy, kernel
10
+ from phono3py_gpu.fourier import GPUFC3Transform
11
+ from phono3py_gpu.integration import TetrahedronTopology
12
+
13
+ MIN_STREAMED_BANDS = 192
14
+
15
+
16
+ def initial_band_block(nb, free_bytes):
17
+ """Choose the largest projection tile within the existing half-free budget."""
18
+ reciprocal_bytes = 16 * nb**3
19
+ bytes_per_band = 128 * nb**2
20
+ for width in (32, 16, 8, 4, 2):
21
+ if reciprocal_bytes + width * bytes_per_band <= free_bytes // 2:
22
+ return width
23
+ return 1
24
+
25
+
26
+ class InteractionKernel:
27
+ """Share force constants and phonons between RTA, LBTE and WTE."""
28
+
29
+ def __init__(self, pp, frequencies, eigenvectors):
30
+ cp = cupy()
31
+ self.pp = pp
32
+ self.frequencies = frequencies
33
+ self.eigenvectors = eigenvectors
34
+ self.nb = frequencies.shape[1]
35
+ self.mass_eigenvectors = cp.ascontiguousarray(
36
+ eigenvectors
37
+ / cp.sqrt(cp.repeat(cp.asarray(pp.primitive.masses), 3))[None, :, None]
38
+ )
39
+ self._fourier = None
40
+ self._tetrahedron = None
41
+ # Batch more triplets for small primitive cells to reduce launch overhead.
42
+ default_batch = 1024 if self.nb <= 12 else 64
43
+ maximum = int(
44
+ os.environ.get("PHONO3PY_GPU_TRIPLET_BATCH_SIZE", str(default_batch))
45
+ )
46
+ if maximum < 1:
47
+ raise ValueError("PHONO3PY_GPU_TRIPLET_BATCH_SIZE must be positive.")
48
+ self.band_block = 32
49
+ self.streamed = (
50
+ self.nb >= MIN_STREAMED_BANDS
51
+ and not pp.symmetrize_fc3q
52
+ and os.environ.get("PHONO3PY_GPU_FOURIER", "tiled") == "tiled"
53
+ )
54
+ if self.streamed:
55
+ # One complex reciprocal tensor, plus FP64/complex projection and
56
+ # integration tiles. Work on one triplet at a time in this layout.
57
+ self.band_block = initial_band_block(
58
+ self.nb, cp.cuda.runtime.memGetInfo()[0]
59
+ )
60
+ work_bytes = 16 * self.nb**3 + 128 * self.band_block * self.nb**2
61
+ self.batch_size = batch_size(work_bytes, maximum=1)
62
+ else:
63
+ self.batch_size = batch_size(16 * self.nb**3 * 9, maximum=maximum)
64
+
65
+ @property
66
+ def tetrahedron(self):
67
+ if self._tetrahedron is None:
68
+ self._tetrahedron = TetrahedronTopology(self.pp)
69
+ return self._tetrahedron
70
+
71
+ def set_grid_point(self, grid_point):
72
+ """Prepare RTA triplets with a batched momentum-conservation check."""
73
+ pp = self.pp
74
+ # Keep upstream Gamma phonons and directional NAC.
75
+ if grid_point == pp.bz_grid.gp_Gamma or pp.nac_q_direction is not None:
76
+ pp.set_grid_point(grid_point)
77
+ return
78
+ prepare = get_triplets_at_q if pp._is_mesh_symmetry else get_nosym_triplets_at_q
79
+ triplets, weights, _, _ = prepare(grid_point, pp.bz_grid)
80
+ if pp._is_mesh_symmetry and pp._done_nac_at_gamma:
81
+ pp.run_phonon_solver_at_gamma()
82
+ sums = pp.bz_grid.addresses[triplets].sum(axis=1)
83
+ if np.any(sums % pp.mesh_numbers):
84
+ # Preserve upstream diagnostics for any invalid triplet.
85
+ pp.set_grid_point(grid_point)
86
+ return
87
+ pp._triplets_at_q = triplets
88
+ pp._weights_at_q = weights
89
+
90
+ @property
91
+ def fourier(self):
92
+ """Allocate FC3 only when a scattering calculation actually needs it."""
93
+ if self._fourier is None:
94
+ self._fourier = GPUFC3Transform.from_interaction(self.pp)
95
+ return self._fourier
96
+
97
+ def project_slice(self, tensor, triplet, bands, zero):
98
+ """Contract the three legs for a tile of initial bands in complex128."""
99
+ cp = cupy()
100
+ nb = self.nb
101
+ q0, q1, q2 = triplet
102
+ ids = cp.asarray(bands, dtype=cp.int64)
103
+ packed = None
104
+ if zero is not None and nb >= MIN_STREAMED_BANDS:
105
+ active = cp.any(zero == 0, axis=2)
106
+ width = int(active.sum(axis=1).max())
107
+ if width == 0:
108
+ return cp.zeros(zero.shape, dtype=cp.float64)
109
+ if width < nb // 2:
110
+ packed = self._pack_second_leg(q1, active, width)
111
+ e0 = self.mass_eigenvectors[q0][:, ids]
112
+ first = (e0.T @ tensor.reshape(nb, -1)).reshape(len(bands), nb, nb)
113
+ if packed is not None:
114
+ vectors, pair_map = packed
115
+ second = vectors.swapaxes(1, 2) @ first
116
+ result = cp.empty(zero.shape, dtype=cp.float64)
117
+ kernel("interaction.cu", "packed_projection")(
118
+ ((result.size + 127) // 128,),
119
+ (128,),
120
+ (
121
+ result,
122
+ second,
123
+ self.mass_eigenvectors,
124
+ self.frequencies,
125
+ cp.asarray(triplet),
126
+ ids,
127
+ zero,
128
+ pair_map,
129
+ np.int32(len(bands)),
130
+ np.int32(nb),
131
+ np.int32(width),
132
+ np.float64(self.pp.cutoff_frequency),
133
+ ),
134
+ )
135
+ return result
136
+ second = self.mass_eigenvectors[q1].T @ first
137
+ if zero is not None:
138
+ return self._masked_projection(
139
+ second[None], cp.asarray(triplet)[None], bands, zero[None]
140
+ )[0]
141
+ amplitude = second.reshape(-1, nb) @ self.mass_eigenvectors[q2]
142
+ result = cp.empty((len(bands), nb, nb), dtype=cp.float64)
143
+ kernel("interaction.cu", "amplitude_squared")(
144
+ ((result.size + 255) // 256,),
145
+ (256,),
146
+ (
147
+ result,
148
+ cp.ascontiguousarray(amplitude),
149
+ cp.ascontiguousarray(zero) if zero is not None else np.uint64(0),
150
+ self.frequencies[q0],
151
+ self.frequencies[q1],
152
+ self.frequencies[q2],
153
+ ids,
154
+ np.int32(nb),
155
+ np.int64(result.size),
156
+ np.float64(self.pp.cutoff_frequency),
157
+ ),
158
+ )
159
+ return result
160
+
161
+ def _pack_second_leg(self, grid_point, active, width):
162
+ """Pack second-leg bands with nonzero weights, preserving band indices."""
163
+ cp = cupy()
164
+ nb0, nb = active.shape
165
+ selected = cp.empty((nb0, nb), dtype=cp.int32)
166
+ pair_map = cp.empty_like(selected)
167
+ kernel("interaction.cu", "pack_active_bands")(
168
+ ((nb0 + 31) // 32,),
169
+ (32,),
170
+ (selected, pair_map, active, np.int32(nb0), np.int32(nb)),
171
+ )
172
+ vectors = cp.empty((nb0, nb, width), dtype=cp.complex128)
173
+ kernel("interaction.cu", "gather_second_leg")(
174
+ ((vectors.size + 127) // 128,),
175
+ (128,),
176
+ (
177
+ vectors,
178
+ self.mass_eigenvectors[grid_point],
179
+ selected,
180
+ np.int32(nb0),
181
+ np.int32(nb),
182
+ np.int32(width),
183
+ ),
184
+ )
185
+ return vectors, pair_map
186
+
187
+ def _masked_projection(self, second, triplets, bands, zero):
188
+ """Skip zero-support final-leg dot products before forming amplitudes."""
189
+ cp = cupy()
190
+ result = cp.empty((len(triplets), len(bands), self.nb, self.nb))
191
+ kernel("interaction.cu", "masked_projection")(
192
+ ((result.size + 127) // 128,),
193
+ (128,),
194
+ (
195
+ result,
196
+ second,
197
+ self.mass_eigenvectors,
198
+ self.frequencies,
199
+ triplets,
200
+ cp.asarray(bands, dtype=cp.int64),
201
+ cp.ascontiguousarray(zero, dtype=cp.int8),
202
+ np.int32(len(triplets)),
203
+ np.int32(len(bands)),
204
+ np.int32(self.nb),
205
+ np.float64(self.pp.cutoff_frequency),
206
+ *(np.int64(s // second.itemsize) for s in second.strides),
207
+ ),
208
+ )
209
+ return result
210
+
211
+ def project(self, triplets, bands, zero=None):
212
+ """Contract atom-first reciprocal FC3 without conjugating eigenvectors."""
213
+ cp = cupy()
214
+ n = len(triplets)
215
+ reciprocal = self.fourier.transform(triplets)
216
+ # (atom, atom, atom, cart, cart, cart) -> (component, component, component)
217
+ tensor = reciprocal.transpose(0, 1, 4, 2, 5, 3, 6).reshape(
218
+ n, self.nb, self.nb, self.nb
219
+ )
220
+ tp = cp.asarray(triplets)
221
+ e0, e1 = [self.mass_eigenvectors[tp[:, i]] for i in range(2)]
222
+ e0 = e0[:, :, cp.asarray(bands)]
223
+ a = cp.einsum("tijk,tia->tajk", tensor, e0)
224
+ b = cp.einsum("tajk,tjb->tabk", a, e1)
225
+ if zero is not None:
226
+ return self._masked_projection(b, tp, bands, zero)
227
+ e2 = self.mass_eigenvectors[tp[:, 2]]
228
+ amplitude = cp.einsum("tabk,tkc->tabc", b, e2)
229
+ f0 = self.frequencies[tp[:, 0]][:, cp.asarray(bands)]
230
+ f1 = self.frequencies[tp[:, 1]]
231
+ f2 = self.frequencies[tp[:, 2]]
232
+ denom = f0[:, :, None, None] * f1[:, None, :, None] * f2[:, None, None, :]
233
+ cutoff = self.pp.cutoff_frequency
234
+ valid = (
235
+ (f0[:, :, None, None] > cutoff)
236
+ & (f1[:, None, :, None] > cutoff)
237
+ & (f2[:, None, None, :] > cutoff)
238
+ )
239
+ return cp.where(valid, cp.abs(amplitude) ** 2 / cp.where(valid, denom, 1), 0)
240
+
241
+ def compute(self, triplets, zero=None):
242
+ """Compute one bounded triplet batch, preserving q symmetrization."""
243
+ cp = cupy()
244
+ pp = self.pp
245
+ bands = pp.band_indices
246
+ if pp.constant_averaged_interaction is not None:
247
+ value = pp.constant_averaged_interaction / np.prod(pp.mesh_numbers)
248
+ return cp.full((len(triplets), len(bands), self.nb, self.nb), value)
249
+ if self.streamed:
250
+ result = cp.empty((len(triplets), len(bands), self.nb, self.nb))
251
+ for t, triplet in enumerate(triplets):
252
+ tensor = self.fourier.components(triplet)
253
+ for start in range(0, len(bands), self.band_block):
254
+ block = slice(start, start + self.band_block)
255
+ mask = None if zero is None else zero[t, block]
256
+ result[t, block] = self.project_slice(
257
+ tensor, triplet, bands[block], mask
258
+ )
259
+ del tensor
260
+ result *= pp.unit_conversion_factor
261
+ return result
262
+ if pp.symmetrize_fc3q:
263
+ result = cp.zeros((len(triplets), len(bands), self.nb, self.nb))
264
+ for permutation in permutations(range(3)):
265
+ values = self.project(triplets[:, permutation], np.arange(self.nb))
266
+ inverse = np.argsort(permutation)
267
+ result += values.transpose(0, *(inverse + 1))[:, cp.asarray(bands)] / 6
268
+ else:
269
+ result = self.project(triplets, bands, zero)
270
+ return result * pp.unit_conversion_factor
@@ -0,0 +1,116 @@
1
+ """Tamura isotope scattering on CUDA with upstream tetrahedron conventions."""
2
+
3
+ import numpy as np
4
+ from phono3py.conductivity.scattering_solvers import IsotopeScatteringSolver
5
+ from phonopy.phonon.grid import get_neighboring_grid_points
6
+ from phonopy.phonon.tetrahedron_method import get_tetrahedra_relative_gr_grid_address
7
+
8
+ from phono3py_gpu.backend import batch_size, cupy, host, kernel
9
+ from phono3py_gpu.integration import average_axis, average_batches
10
+
11
+
12
+ class GPUIsotopeSolver(IsotopeScatteringSolver):
13
+ def __init__(self, *args, device_phonons=None, **kwargs):
14
+ super().__init__(*args, **kwargs)
15
+ # Reuse this Interaction's phonon basis without uploading the grid again.
16
+ self._device_phonons = device_phonons
17
+ self._vertices = None
18
+
19
+ def compute(self, grid_point):
20
+ cp = cupy()
21
+ iso = self.isotope
22
+ iso.set_grid_point(grid_point)
23
+ if self._device_phonons is None:
24
+ f = cp.asarray(iso.phonons.frequencies)
25
+ e = cp.asarray(iso.phonons.eigenvectors)
26
+ else:
27
+ f, e = self._device_phonons
28
+ nb = f.shape[1]
29
+ gps = iso.bz_grid.grg2bzg
30
+ maximum = 2048 if nb <= 12 else 128
31
+ step = batch_size(32 * nb**2, maximum=maximum)
32
+ mass_variances = cp.asarray(iso.mass_variances)
33
+ outputs = []
34
+ for sigma in self._sigmas:
35
+ iso.sigma = sigma
36
+ bands = iso._get_calc_band_indices()
37
+ f0 = cp.ascontiguousarray(f[grid_point, cp.asarray(bands)])
38
+ e0 = cp.ascontiguousarray(e[grid_point][:, cp.asarray(bands)])
39
+ gamma = cp.zeros(len(bands))
40
+ if sigma is None and self._vertices is None:
41
+ relative = get_tetrahedra_relative_gr_grid_address(
42
+ iso.bz_grid, iso.symmetrize_tetrahedra
43
+ )
44
+ self._vertices = cp.asarray(
45
+ np.array(
46
+ [
47
+ get_neighboring_grid_points(int(gp), relative, iso.bz_grid)
48
+ for gp in gps
49
+ ],
50
+ dtype="int64",
51
+ )
52
+ )
53
+ for start in range(0, len(gps), step):
54
+ selected = gps[start : start + step]
55
+ ids = cp.asarray(selected)
56
+ if sigma is None:
57
+ w = cp.empty((len(ids), len(bands), nb))
58
+ count = w.size
59
+ kernel("tetrahedron.cu", "spectral_weights")(
60
+ ((count + 127) // 128,),
61
+ (128,),
62
+ (
63
+ w,
64
+ f,
65
+ f0,
66
+ self._vertices[start : start + step],
67
+ np.int32(len(ids)),
68
+ np.int32(len(bands)),
69
+ np.int32(nb),
70
+ np.int32(self._vertices.shape[1]),
71
+ ),
72
+ )
73
+ if iso._averaging:
74
+ if iso._average_over_initial_bands():
75
+ average_batches(
76
+ w,
77
+ iso.phonons.degenerate_ids[grid_point][None],
78
+ axis=1,
79
+ batch_axis=0,
80
+ )
81
+ average_batches(
82
+ w,
83
+ iso.phonons.degenerate_ids[selected],
84
+ axis=2,
85
+ batch_axis=0,
86
+ )
87
+ else:
88
+ delta = f0[None, :, None] - f[ids, None, :]
89
+ w = cp.exp(-(delta**2) / (2 * sigma * sigma)) / (
90
+ np.sqrt(2 * np.pi) * sigma
91
+ )
92
+ kernel("isotope.cu", "weighted_overlap")(
93
+ ((w.size + 127) // 128,),
94
+ (128,),
95
+ (
96
+ w,
97
+ e0,
98
+ e,
99
+ f,
100
+ ids,
101
+ mass_variances,
102
+ np.int32(len(ids)),
103
+ np.int32(len(bands)),
104
+ np.int32(nb),
105
+ np.float64(iso._cutoff_frequency),
106
+ ),
107
+ )
108
+ gamma += w.sum(axis=(0, 2))
109
+ gamma *= f0**2 * np.pi / (4 * int(np.prod(iso.bz_grid.D_diag)))
110
+ gamma[f0 < iso._cutoff_frequency] = 0.0
111
+ if iso._average_over_initial_bands():
112
+ average_axis(gamma, iso.phonons.degenerate_ids[grid_point], 0)
113
+ gamma = gamma[cp.asarray(iso.band_indices)]
114
+ iso._gamma = host(gamma)
115
+ outputs.append(iso.gamma)
116
+ return np.asarray(outputs)
phono3py_gpu/kappa.py ADDED
@@ -0,0 +1,39 @@
1
+ """Device reductions for standard BTE and effective linewidths."""
2
+
3
+ import numpy as np
4
+ from phono3py.conductivity.kappa_solvers import RTAKappaSolver
5
+
6
+ from phono3py_gpu.backend import cupy, host
7
+
8
+
9
+ def effective_gamma(aggregates):
10
+ cp = cupy()
11
+ gamma = cp.asarray(aggregates.gamma).copy()
12
+ if aggregates.gamma_isotope is not None:
13
+ gamma += cp.asarray(aggregates.gamma_isotope)[:, None]
14
+ if aggregates.gamma_boundary is not None:
15
+ gamma += cp.asarray(aggregates.gamma_boundary)[None, None]
16
+ if aggregates.gamma_elph is not None:
17
+ gamma += cp.asarray(aggregates.gamma_elph)
18
+ return gamma
19
+
20
+
21
+ class GPURTAKappaSolver(RTAKappaSolver):
22
+ def finalize(self, aggregates):
23
+ cp = cupy()
24
+ settings = self._kappa_settings
25
+ g = effective_gamma(aggregates)
26
+ cv = cp.asarray(aggregates.mode_heat_capacities)
27
+ vv = cp.asarray(aggregates.gv_by_gv)
28
+ mode = cp.nan_to_num(
29
+ vv[None, None]
30
+ * cv[None, ..., None]
31
+ / (2 * g[..., None])
32
+ * settings.conversion_factor
33
+ )
34
+ f = cp.asarray(
35
+ self._frequencies[settings.grid_points][:, settings.band_indices]
36
+ )
37
+ mode *= (f >= settings.cutoff_frequency)[None, None, ..., None]
38
+ self._kappa = host(mode.sum(axis=(2, 3)) / int(np.prod(settings.mesh_numbers)))
39
+ self._mode_kappa = host(mode)
@@ -0,0 +1,11 @@
1
+ // Each thread owns one symmetric pair in either row- or column-major storage.
2
+ extern "C" __global__ void symmetrize_collision(double* matrix, int n) {
3
+ long long index = (long long)blockIdx.x * blockDim.x + threadIdx.x;
4
+ if (index >= (long long)n * n) return;
5
+ int row = index / n, column = index % n;
6
+ if (row >= column) return;
7
+ long long transposed = (long long)column * n + row;
8
+ double mean = (matrix[index] + matrix[transposed]) / 2;
9
+ matrix[index] = mean;
10
+ matrix[transposed] = mean;
11
+ }
@@ -0,0 +1,36 @@
1
+ // Only the first band owns each group, so in-place reduction has no write races.
2
+ template <typename T, bool minimum>
3
+ __device__ void reduce_groups(T* values, const long long* ids, long long size,
4
+ int nb, long long inner, long long batch_stride,
5
+ int batches) {
6
+ long long index = (long long)blockIdx.x * blockDim.x + threadIdx.x;
7
+ if (index >= size) return;
8
+ int band = (index / inner) % nb;
9
+ int batch = (index / batch_stride) % batches;
10
+ const long long* groups = ids + (long long)batch * nb;
11
+ if (groups[band] != band) return;
12
+ int end = band + 1;
13
+ while (end < nb && groups[end] == band) ++end;
14
+ if (end == band + 1) return;
15
+ T result = values[index];
16
+ for (int b = band + 1; b < end; ++b) {
17
+ T value = values[index + (b - band) * inner];
18
+ if (minimum) result = value < result ? value : result;
19
+ else result += value;
20
+ }
21
+ if (!minimum) result /= end - band;
22
+ for (int b = band; b < end; ++b)
23
+ values[index + (b - band) * inner] = result;
24
+ }
25
+
26
+ extern "C" __global__ void average_groups(
27
+ double* values, const long long* ids, long long size, int nb,
28
+ long long inner, long long batch_stride, int batches) {
29
+ reduce_groups<double, false>(values, ids, size, nb, inner, batch_stride, batches);
30
+ }
31
+
32
+ extern "C" __global__ void minimum_groups(
33
+ signed char* values, const long long* ids, long long size, int nb,
34
+ long long inner, long long batch_stride, int batches) {
35
+ reduce_groups<signed char, true>(values, ids, size, nb, inner, batch_stride, batches);
36
+ }
@@ -0,0 +1,89 @@
1
+ // Compact final-band rows that have at least one nonzero integration weight.
2
+ extern "C" __global__ void pack_active_bands(
3
+ int* selected, int* pair_map, const bool* active, int nb0, int nb) {
4
+ int a = blockIdx.x * blockDim.x + threadIdx.x;
5
+ if (a >= nb0) return;
6
+ int count = 0;
7
+ for (int b = 0; b < nb; ++b) {
8
+ pair_map[a * nb + b] = -1;
9
+ if (active[a * nb + b]) {
10
+ selected[a * nb + count] = b;
11
+ pair_map[a * nb + b] = count++;
12
+ }
13
+ }
14
+ for (int b = count; b < nb; ++b) selected[a * nb + b] = -1;
15
+ }
16
+
17
+ extern "C" __global__ void gather_second_leg(
18
+ double2* out, const double2* eigenvectors, const int* selected,
19
+ int nb0, int nb, int width) {
20
+ long long index = (long long)blockIdx.x * blockDim.x + threadIdx.x;
21
+ if (index >= (long long)nb0 * nb * width) return;
22
+ int a = index / (nb * width), j = (index / width) % nb;
23
+ int b = selected[a * nb + index % width];
24
+ out[index] = b < 0 ? make_double2(0., 0.) : eigenvectors[j * nb + b];
25
+ }
26
+
27
+ extern "C" __global__ void packed_projection(
28
+ double* out, const double2* partial, const double2* eigenvectors,
29
+ const double* freq, const long long* triplet, const long long* bands,
30
+ const signed char* zero, const int* pair_map, int nb0, int nb,
31
+ int width, double cutoff) {
32
+ long long index = (long long)blockIdx.x * blockDim.x + threadIdx.x;
33
+ if (index >= (long long)nb0 * nb * nb) return;
34
+ int c = index % nb, b = (index / nb) % nb, a = index / (nb * nb);
35
+ out[index] = 0.;
36
+ if (zero[index]) return;
37
+ long long q0 = triplet[0], q1 = triplet[1], q2 = triplet[2];
38
+ double f0 = freq[q0 * nb + bands[a]], f1 = freq[q1 * nb + b];
39
+ double f2 = freq[q2 * nb + c];
40
+ if (f0 <= cutoff || f1 <= cutoff || f2 <= cutoff) return;
41
+ long long base = ((long long)a * width + pair_map[a * nb + b]) * nb;
42
+ double re = 0., im = 0.;
43
+ for (int k = 0; k < nb; ++k) {
44
+ double2 x = partial[base + k], y = eigenvectors[(q2 * nb + k) * nb + c];
45
+ re += x.x * y.x - x.y * y.y;
46
+ im += x.x * y.y + x.y * y.x;
47
+ }
48
+ out[index] = (re * re + im * im) / (f0 * f1 * f2);
49
+ }
50
+
51
+ // Last mode contraction: exact integration zeros never need an amplitude.
52
+ extern "C" __global__ void masked_projection(
53
+ double* out, const double2* partial, const double2* eigenvectors,
54
+ const double* freq, const long long* triplets, const long long* bands,
55
+ const signed char* zero, int nt, int nb0, int nb, double cutoff,
56
+ long long s0, long long s1, long long s2, long long s3) {
57
+ long long index = (long long)blockIdx.x*blockDim.x+threadIdx.x;
58
+ if (index >= (long long)nt*nb0*nb*nb) return;
59
+ int c = index % nb, b = (index/nb) % nb;
60
+ int a = (index/(nb*nb)) % nb0, t = index/(nb0*nb*nb);
61
+ out[index] = 0;
62
+ if (zero[index]) return;
63
+ long long q0 = triplets[t*3], q1 = triplets[t*3+1], q2 = triplets[t*3+2];
64
+ double f0 = freq[q0*nb+bands[a]], f1 = freq[q1*nb+b], f2 = freq[q2*nb+c];
65
+ if (f0 <= cutoff || f1 <= cutoff || f2 <= cutoff) return;
66
+ long long base = t*s0+a*s1+b*s2;
67
+ double re = 0, im = 0;
68
+ for (int k=0; k<nb; ++k) {
69
+ double2 x = partial[base+k*s3], y = eigenvectors[(q2*nb+k)*nb+c];
70
+ re += x.x*y.x-x.y*y.y;
71
+ im += x.x*y.y+x.y*y.x;
72
+ }
73
+ out[index] = (re*re+im*im)/(f0*f1*f2);
74
+ }
75
+
76
+ extern "C" __global__ void amplitude_squared(
77
+ double* out, const double2* amplitude, const signed char* zero,
78
+ const double* f0, const double* f1, const double* f2, const long long* bands,
79
+ int nb, long long size, double cutoff) {
80
+ long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x;
81
+ if (i >= size) return;
82
+ double x = f0[bands[i/(nb*nb)]], y = f1[(i/nb)%nb], z = f2[i%nb];
83
+ if ((zero && zero[i]) || x <= cutoff || y <= cutoff || z <= cutoff) {
84
+ out[i] = 0.;
85
+ } else {
86
+ double2 v = amplitude[i];
87
+ out[i] = (v.x*v.x + v.y*v.y)/(x*y*z);
88
+ }
89
+ }
@@ -0,0 +1,28 @@
1
+ // Accumulate Tamura overlaps only at nonzero integration weights.
2
+ extern "C" __global__ void weighted_overlap(
3
+ double* weights, const double2* e0, const double2* eigenvectors,
4
+ const double* frequencies, const long long* grid_points,
5
+ const double* mass_variances, int nq, int nb0, int nb, double cutoff) {
6
+ long long index = (long long)blockIdx.x * blockDim.x + threadIdx.x;
7
+ if (index >= (long long)nq * nb0 * nb) return;
8
+ int b = index % nb, a = (index / nb) % nb0;
9
+ long long q = grid_points[index / (nb0 * nb)];
10
+ double weight = weights[index];
11
+ weights[index] = 0.;
12
+ if (weight == 0. || frequencies[q * nb + b] < cutoff) return;
13
+ double strength = 0.;
14
+ for (int atom = 0; atom < nb / 3; ++atom) {
15
+ double variance = mass_variances[atom];
16
+ if (variance == 0.) continue;
17
+ double re = 0., im = 0.;
18
+ for (int cart = 0; cart < 3; ++cart) {
19
+ int row = atom * 3 + cart;
20
+ double2 x = e0[row * nb0 + a];
21
+ double2 y = eigenvectors[(q * nb + row) * nb + b];
22
+ re += x.x * y.x + x.y * y.y;
23
+ im += x.x * y.y - x.y * y.x;
24
+ }
25
+ strength += variance * (re * re + im * im);
26
+ }
27
+ weights[index] = weight * strength;
28
+ }
@@ -0,0 +1,85 @@
1
+ // FP64 three-phonon reductions in the upstream band and channel order.
2
+ extern "C" __global__ void linewidth(
3
+ double* out, const double* strength, const double* g,
4
+ const double* freq, const double* occupation, const long long* triplets,
5
+ int nt, int nb0, int nb, double cutoff, double unit) {
6
+ long long index = (long long)blockIdx.x * blockDim.x + threadIdx.x;
7
+ long long size = (long long)nt * nb0 * nb * nb;
8
+ if (index >= size) return;
9
+ int k = index % nb, j = (index / nb) % nb;
10
+ int t = index / (nb0 * nb * nb);
11
+ long long q1 = triplets[3*t+1]*nb+j, q2 = triplets[3*t+2]*nb+k;
12
+ double value = 0;
13
+ if (freq[q1] > cutoff && freq[q2] > cutoff) {
14
+ double n1 = occupation[q1], n2 = occupation[q2];
15
+ value = strength[index] * ((n1+n2+1)*g[index] +
16
+ (n1-n2)*g[size+index]) * unit;
17
+ }
18
+ out[index] = value;
19
+ }
20
+
21
+ // Reduce both q1/q2 orientations once per irreducible triplet. The symmetry
22
+ // rotations reuse these values instead of replicating a four-index tensor.
23
+ extern "C" __global__ void collision_reduce(
24
+ double* out, const double* strength, const double* g,
25
+ const double* inv_sinh, const long long* triplets,
26
+ int nt, int nb0, int nb, double unit) {
27
+ long long index = (long long)blockIdx.x * blockDim.x + threadIdx.x;
28
+ long long size = (long long)nt * nb0 * nb;
29
+ if (index >= 2*size) return;
30
+ int j = index % nb, b = (index / nb) % nb0;
31
+ int t = (index / (nb*nb0)) % nt, swapped = index / size;
32
+ long long partner = triplets[3*t+(swapped ? 1 : 2)];
33
+ long long base = ((long long)t*nb0+b)*nb*nb;
34
+ double value = 0;
35
+ for (int k=0; k<nb; ++k) {
36
+ long long p = base + (swapped ? k*nb+j : j*nb+k);
37
+ value += strength[p] * g[p] * inv_sinh[partner*nb+k];
38
+ }
39
+ out[index] = value * unit;
40
+ }
41
+
42
+ // One thread owns each output element: no atomics or duplicated rotations.
43
+ extern "C" __global__ void collision_rows(
44
+ double* row, const double* reduced, const long long* triplet_index,
45
+ const signed char* swapped, const double* rotations,
46
+ int nt, int nb0, int nb, int ni, int nr, int start, int nc, int nq) {
47
+ long long index = (long long)blockIdx.x * blockDim.x + threadIdx.x;
48
+ long long size = (long long)nq*nb0*nc*ni*nb*nc;
49
+ if (index >= size) return;
50
+ long long rest = index;
51
+ int c = rest % nc; rest /= nc;
52
+ int j = rest % nb; rest /= nb;
53
+ int i = rest % ni; rest /= ni;
54
+ int a = rest % nc, b = (rest / nc) % nb0;
55
+ int q = rest / (nc*nb0);
56
+ double value = 0;
57
+ for (int r=0; r<nr; ++r) {
58
+ long long target = ((long long)q*ni+i)*nr+r;
59
+ long long t = triplet_index[target]-start;
60
+ if (t < 0 || t >= nt) continue;
61
+ long long p = (((long long)swapped[target]*nt+t)*nb0+b)*nb+j;
62
+ value += reduced[p] * (nc == 1 ? 1.0 : rotations[r*9+a*3+c]);
63
+ }
64
+ row[index] += value;
65
+ }
66
+
67
+ // Each q and initial branch owns its sum; interleaved triplets retain their
68
+ // original order within q. No floating-point atomics are needed.
69
+ extern "C" __global__ void sum_by_q(
70
+ double* out, const double* values, const long long* multiplicity,
71
+ const long long* owner, const signed char* normal,
72
+ int nt, int nb0, int nq, int channels) {
73
+ int index = blockIdx.x*blockDim.x+threadIdx.x;
74
+ if (index >= channels*nq*nb0) return;
75
+ int b = index % nb0, q = (index/nb0) % nq;
76
+ int channel = index/(nb0*nq);
77
+ double value = 0;
78
+ for (int t=0; t<nt; ++t) {
79
+ if (owner[t] != q) continue;
80
+ if (channel == 1 && !normal[t]) continue;
81
+ if (channel == 2 && normal[t]) continue;
82
+ value += values[(long long)t*nb0+b]*multiplicity[t];
83
+ }
84
+ out[index] += value;
85
+ }