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,474 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """FP64 CUDA FC3 Fourier transform for the shared GPU interaction engine.
3
+
4
+ The phase, multiplicity, pre-phase and r0-average conventions match phonors
5
+ 0.6.0. Each warp sums one atom triplet's 27 Cartesian components in the
6
+ original supercell-pair order. No fast-math or frequency approximation is used.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import time
13
+
14
+ import numpy as np
15
+
16
+ _KERNELS = r"""
17
+ extern "C" __global__ void phases(
18
+ const double* q, const double* sv, const long long* multi,
19
+ double2* out, int na, int ns, int nq) {
20
+ int index = blockIdx.x * blockDim.x + threadIdx.x;
21
+ if (index >= nq * na * ns) return;
22
+ int s = index % ns, a = (index / ns) % na, g = index / (ns * na);
23
+ long long count = multi[(s * na + a) * 2];
24
+ long long start = multi[(s * na + a) * 2 + 1];
25
+ double re = 0., im = 0.;
26
+ for (long long v = start; v < start + count; ++v) {
27
+ double angle = 6.2831853071795864769 *
28
+ (q[g*3]*sv[v*3] + q[g*3+1]*sv[v*3+1] + q[g*3+2]*sv[v*3+2]);
29
+ double si, co;
30
+ sincos(angle, &si, &co);
31
+ re += co; im += si;
32
+ }
33
+ out[index] = make_double2(re / count, im / count);
34
+ }
35
+ extern "C" __global__ void transform(
36
+ const double* fc, const long long* offsets, const int* pairs,
37
+ const signed char* shortest, const double2* phase,
38
+ const long long* triplets, double2* out,
39
+ int na, int ns, int batch, int average) {
40
+ int cart = threadIdx.x % 32;
41
+ int atom = blockIdx.x * (blockDim.x / 32) + threadIdx.x / 32;
42
+ int t = blockIdx.y, leg = blockIdx.z, blocks = na*na*na;
43
+ if (cart >= 27 || atom >= blocks) return;
44
+ int anchor = atom / (na*na);
45
+ int qa = (leg == 1) ? 0 : 1;
46
+ int qb = (leg == 2) ? 0 : 2;
47
+ long long p1 = (triplets[t*3+qa]*na + anchor)*ns;
48
+ long long p2 = (triplets[t*3+qb]*na + anchor)*ns;
49
+ double re = 0., im = 0.;
50
+ for (long long p = offsets[atom]; p < offsets[atom+1]; ++p) {
51
+ if (average && leg > 0 && shortest[p]) continue;
52
+ double2 x = phase[p1 + pairs[p*2]], y = phase[p2 + pairs[p*2+1]];
53
+ double weight = (average && leg == 0 && shortest[p]) ? 3. : 1.;
54
+ double f = fc[p*32+cart];
55
+ re += ((x.x*y.x - x.y*y.y)*weight)*f;
56
+ im += ((x.x*y.y + x.y*y.x)*weight)*f;
57
+ }
58
+ out[((long long)leg*batch+t)*blocks*27+atom*27+cart] = make_double2(re, im);
59
+ }
60
+ // Each block reuses a coalesced FC3 tile across several triplets. The inner
61
+ // supercell-pair accumulation order remains identical to transform().
62
+ extern "C" __global__ void transform_tiled(
63
+ const double* fc, const long long* offsets, const int* pairs,
64
+ const signed char* shortest, const double2* phase,
65
+ const long long* triplets, double2* out,
66
+ int na, int ns, int batch, int average) {
67
+ __shared__ double f[32*32];
68
+ __shared__ int js[32], ks[32];
69
+ __shared__ signed char flags[32];
70
+ int cart = threadIdx.x, lane = threadIdx.y*32+cart;
71
+ int atom = blockIdx.x, t = blockIdx.y*blockDim.y+threadIdx.y, leg = blockIdx.z;
72
+ int anchor = atom/(na*na), qa = leg == 1 ? 0 : 1, qb = leg == 2 ? 0 : 2;
73
+ bool valid = t < batch && cart < 27;
74
+ long long p1 = 0, p2 = 0;
75
+ if (valid) {
76
+ p1 = (triplets[t*3+qa]*na+anchor)*ns;
77
+ p2 = (triplets[t*3+qb]*na+anchor)*ns;
78
+ }
79
+ double re = 0., im = 0.;
80
+ long long begin = offsets[atom], end = offsets[atom+1];
81
+ for (long long base = begin; base < end; base += 32) {
82
+ int count = (end-base < 32) ? int(end-base) : 32;
83
+ for (int i=lane; i<count*32; i+=blockDim.y*32)
84
+ f[i] = fc[base*32+i];
85
+ if (lane < count) {
86
+ js[lane] = pairs[(base+lane)*2];
87
+ ks[lane] = pairs[(base+lane)*2+1];
88
+ flags[lane] = shortest[base+lane];
89
+ }
90
+ __syncthreads();
91
+ if (valid) {
92
+ for (int p=0; p<count; ++p) {
93
+ if (average && leg > 0 && flags[p]) continue;
94
+ double2 x = phase[p1+js[p]], y = phase[p2+ks[p]];
95
+ double w = average && leg == 0 && flags[p] ? 3. : 1.;
96
+ double value = f[p*32+cart];
97
+ re += ((x.x*y.x-x.y*y.y)*w)*value;
98
+ im += ((x.x*y.y+x.y*y.x)*w)*value;
99
+ }
100
+ }
101
+ __syncthreads();
102
+ }
103
+ if (valid)
104
+ out[((long long)leg*batch+t)*na*na*na*27+atom*27+cart] = make_double2(re, im);
105
+ }
106
+ __device__ double2 premultiply(double2 x, const double* q,
107
+ const double* origin, const long long* triplet, int a) {
108
+ double angle = 0.;
109
+ for (int d = 0; d < 3; ++d)
110
+ angle += origin[a*3+d] *
111
+ (q[triplet[0]*3+d]+q[triplet[1]*3+d]+q[triplet[2]*3+d]);
112
+ double si, co;
113
+ sincos(angle * 6.2831853071795864769, &si, &co);
114
+ return make_double2(x.x*co-x.y*si, x.x*si+x.y*co);
115
+ }
116
+ extern "C" __global__ void assemble(
117
+ const double2* legs, const double* q, const double* origin,
118
+ const long long* triplets, double2* out, int na, int batch, int average) {
119
+ long long index = (long long)blockIdx.x * blockDim.x + threadIdx.x;
120
+ int size = na*na*na*27;
121
+ if (index >= (long long)batch*size) return;
122
+ int t = index / size, elem = index % size, atom = elem / 27;
123
+ int i = atom/(na*na), j = (atom/na)%na, k = atom%na;
124
+ int cart = elem%27, l = cart/9, m = (cart/3)%3, n = cart%3;
125
+ double2 v = premultiply(legs[index], q, origin, triplets+t*3, i);
126
+ if (average) {
127
+ long long stride = (long long)batch*size;
128
+ double2 w = premultiply(legs[stride+t*size+((j*na+i)*na+k)*27+m*9+l*3+n],
129
+ q, origin, triplets+t*3, j);
130
+ double2 z = premultiply(legs[2*stride+t*size+((k*na+j)*na+i)*27+n*9+m*3+l],
131
+ q, origin, triplets+t*3, k);
132
+ v = make_double2(((v.x+w.x)+z.x)/3., ((v.y+w.y)+z.y)/3.);
133
+ }
134
+ out[index] = v;
135
+ }
136
+ // Evaluate each requested r0 permutation directly in the final component layout.
137
+ __device__ double2 component_leg(
138
+ const double* fc, const long long* offsets, const int* pairs,
139
+ const signed char* shortest, const double2* phase, const double2 pre,
140
+ int na, int ns, int i, int j, int k, int cart, int qj, int qk,
141
+ int leg, int average) {
142
+ long long atom = ((long long)i*na+j)*na+k;
143
+ const double2* pj = phase + ((long long)qj*na+i)*ns;
144
+ const double2* pk = phase + ((long long)qk*na+i)*ns;
145
+ double re = 0., im = 0.;
146
+ for (long long p=offsets[atom]; p<offsets[atom+1]; ++p) {
147
+ if (average && leg && shortest[p]) continue;
148
+ double2 x = pj[pairs[2*p]], y = pk[pairs[2*p+1]];
149
+ double w = (average && !leg && shortest[p]) ? 3. : 1.;
150
+ double v = fc[p*32+cart];
151
+ re += ((x.x*y.x-x.y*y.y)*w)*v;
152
+ im += ((x.x*y.y+x.y*y.x)*w)*v;
153
+ }
154
+ return make_double2(re*pre.x-im*pre.y, re*pre.y+im*pre.x);
155
+ }
156
+ extern "C" __global__ void transform_components(
157
+ const double* fc, const long long* offsets, const int* pairs,
158
+ const signed char* shortest, const double2* phase, const long long* tp,
159
+ const double2* pre, double2* out, int na, int ns, int average) {
160
+ long long index = (long long)blockIdx.x*blockDim.x+threadIdx.x;
161
+ int nb=3*na;
162
+ if (index >= (long long)nb*nb*nb) return;
163
+ int x=index/(nb*nb), y=(index/nb)%nb, z=index%nb;
164
+ int i=x/3, j=y/3, k=z/3, l=x%3, m=y%3, n=z%3;
165
+ double2 v=component_leg(fc,offsets,pairs,shortest,phase,pre[i],na,ns,
166
+ i,j,k,9*l+3*m+n,tp[1],tp[2],0,average);
167
+ if (average) {
168
+ double2 w=component_leg(fc,offsets,pairs,shortest,phase,pre[j],na,ns,
169
+ j,i,k,9*m+3*l+n,tp[0],tp[2],1,1);
170
+ double2 u=component_leg(fc,offsets,pairs,shortest,phase,pre[k],na,ns,
171
+ k,j,i,9*n+3*m+l,tp[1],tp[0],2,1);
172
+ v=make_double2(((v.x+w.x)+u.x)/3., ((v.y+w.y)+u.y)/3.);
173
+ }
174
+ out[index]=v;
175
+ }
176
+ // Reuse each FC3 block across triplets; phase products are the right GEMM operand.
177
+ extern "C" __global__ void phase_products(
178
+ const int* pairs, const signed char* shortest, const double2* phase,
179
+ const long long* triplets, double* real, double* imag,
180
+ int na, int ns, int npair, int tile, int start, int count,
181
+ int leg, int average) {
182
+ long long index = (long long)blockIdx.x*blockDim.x + threadIdx.x;
183
+ long long size = (long long)na*na*na*npair*tile;
184
+ if (index >= size) return;
185
+ int t = index % tile;
186
+ long long p = index / tile;
187
+ int atom = p / npair, anchor = atom / (na*na);
188
+ real[index] = imag[index] = 0.;
189
+ if (t >= count || (average && leg > 0 && shortest[p])) return;
190
+ int qa = leg == 1 ? 0 : 1, qb = leg == 2 ? 0 : 2;
191
+ long long p1 = (triplets[(start+t)*3+qa]*na+anchor)*ns;
192
+ long long p2 = (triplets[(start+t)*3+qb]*na+anchor)*ns;
193
+ double2 x = phase[p1+pairs[p*2]], y = phase[p2+pairs[p*2+1]];
194
+ double w = average && leg == 0 && shortest[p] ? 3. : 1.;
195
+ real[index] = (x.x*y.x-x.y*y.y)*w;
196
+ imag[index] = (x.x*y.y+x.y*y.x)*w;
197
+ }
198
+ extern "C" __global__ void store_gemm(
199
+ const double* real, const double* imag, double2* legs,
200
+ int atoms, int batch, int tile, int start, int count, int leg) {
201
+ long long index = (long long)blockIdx.x*blockDim.x + threadIdx.x;
202
+ if (index >= (long long)atoms*27*count) return;
203
+ int t = index % count, cart = (index/count)%27, atom = index/(count*27);
204
+ long long src = ((long long)atom*32+cart)*tile+t;
205
+ long long dst = (((long long)leg*batch+start+t)*atoms+atom)*27+cart;
206
+ legs[dst] = make_double2(real[src], imag[src]);
207
+ }
208
+ """
209
+
210
+
211
+ class GPUFC3Transform:
212
+ """Cache a snapshot of FC3 and BZ phases on the current CuPy device.
213
+
214
+ Input FC3/mappings must remain unchanged for this object's lifetime.
215
+ ``transform`` returns atom-first complex128 tensors on the device.
216
+ Triplet batches are bounded by the caller.
217
+ """
218
+
219
+ def __init__(
220
+ self,
221
+ fc3,
222
+ nonzero,
223
+ svecs,
224
+ multi,
225
+ p2s,
226
+ s2p,
227
+ all_shortest,
228
+ qpoints,
229
+ make_r0_average=True,
230
+ ):
231
+ import cupy as cp
232
+
233
+ if fc3.dtype != np.float64:
234
+ raise TypeError("GPU FC3 transform requires float64 force constants.")
235
+ self.na, self.ns = len(p2s), len(s2p)
236
+ self.average = bool(make_r0_average)
237
+ self.pool = cp.cuda.MemoryPool()
238
+ self.device = cp.cuda.Device().id
239
+ start = time.perf_counter()
240
+ compact = fc3.shape[0] != fc3.shape[1]
241
+ groups = [np.flatnonzero(s2p == p) for p in p2s]
242
+ # Pure translations give every primitive atom the same number of images.
243
+ # Flatten one anchor in (j atom, k atom, j image, k image) order.
244
+ images = np.asarray(groups, dtype=np.int32)
245
+ js, ks = np.broadcast_arrays(images[:, None, :, None], images[None, :, None, :])
246
+ js, ks = js.ravel(), ks.ravel()
247
+ rows = np.arange(self.na) if compact else p2s
248
+ counts = np.empty((self.na, self.na**2), dtype=np.int64)
249
+ for a, row in enumerate(rows):
250
+ counts[a] = np.count_nonzero(
251
+ nonzero[row, js, ks].reshape(self.na**2, -1), axis=1
252
+ )
253
+ offsets = np.empty(counts.size + 1, dtype=np.int64)
254
+ offsets[0] = 0
255
+ np.cumsum(counts.ravel(), out=offsets[1:])
256
+ self.uniform_pairs = (
257
+ int(counts.flat[0]) if np.all(counts == counts.flat[0]) else 0
258
+ )
259
+ self.method = os.environ.get("PHONO3PY_GPU_FOURIER", "tiled")
260
+ if self.method not in ("reference", "gemm", "tiled"):
261
+ raise ValueError("PHONO3PY_GPU_FOURIER must be reference, tiled or gemm.")
262
+ if self.method == "gemm" and not self.uniform_pairs:
263
+ raise ValueError("GEMM Fourier requires uniform FC3 pair blocks.")
264
+ self.tile = int(os.environ.get("PHONO3PY_GPU_FOURIER_TILE", "16"))
265
+ if self.tile < 1:
266
+ raise ValueError("PHONO3PY_GPU_FOURIER_TILE must be positive.")
267
+ if self.method == "tiled" and self.tile > 32:
268
+ raise ValueError("Tiled Fourier supports at most 32 triplets per block.")
269
+ with cp.cuda.using_allocator(self.pool.malloc):
270
+ n_pairs = int(offsets[-1])
271
+ self.fc = cp.empty((n_pairs, 32), dtype=cp.float64)
272
+ self.pairs = cp.empty((n_pairs, 2), dtype=cp.int32)
273
+ self.shortest = cp.empty(n_pairs, dtype=cp.int8)
274
+ for a, row in enumerate(rows):
275
+ block = slice(offsets[a * self.na**2], offsets[(a + 1) * self.na**2])
276
+ keep = nonzero[row, js, ks] != 0
277
+ j, k = js[keep], ks[keep]
278
+ packed = np.zeros((len(j), 32), dtype=np.float64)
279
+ packed[:, :27] = fc3[row, j, k].reshape(-1, 27)
280
+ self.fc[block].set(packed)
281
+ self.pairs[block].set(np.column_stack((j, k)))
282
+ self.shortest[block].set(
283
+ np.asarray(all_shortest[a, j, k], dtype=np.int8)
284
+ )
285
+ self.offsets = cp.asarray(offsets, dtype=cp.int64)
286
+ self.qpoints = cp.asarray(qpoints, dtype=cp.float64, order="C")
287
+ self.origins = cp.asarray(svecs[multi[p2s, 0, 1]], order="C")
288
+ self.phase = cp.empty((len(qpoints), self.na, self.ns), cp.complex128)
289
+ # FP64 FMA is disabled to retain the native summation convention.
290
+ module = cp.RawModule(code=_KERNELS, options=("--fmad=false",))
291
+ phase_kernel = module.get_function("phases")
292
+ self.components_kernel = module.get_function("transform_components")
293
+ self.kernel = module.get_function("transform")
294
+ self.tiled_kernel = module.get_function("transform_tiled")
295
+ self.assemble = module.get_function("assemble")
296
+ self.phase_products = module.get_function("phase_products")
297
+ self.store_gemm = module.get_function("store_gemm")
298
+ sv = cp.asarray(svecs, dtype=cp.float64, order="C")
299
+ multiplicity = cp.asarray(multi, dtype=cp.int64, order="C")
300
+ phase_kernel(
301
+ ((self.phase.size + 255) // 256,),
302
+ (256,),
303
+ (
304
+ self.qpoints,
305
+ sv,
306
+ multiplicity,
307
+ self.phase,
308
+ np.int32(self.na),
309
+ np.int32(self.ns),
310
+ np.int32(len(qpoints)),
311
+ ),
312
+ )
313
+ cp.cuda.get_current_stream().synchronize()
314
+ self.setup_seconds = time.perf_counter() - start
315
+
316
+ def components(self, triplet):
317
+ """One reciprocal FC3 in component order, including all requested origins."""
318
+ import cupy as cp
319
+
320
+ nb = 3 * self.na
321
+ tensor = cp.empty((nb, nb, nb), dtype=cp.complex128)
322
+ tp = cp.asarray(triplet, dtype=cp.int64)
323
+ prephase = cp.exp((2j * np.pi) * (self.origins @ self.qpoints[tp].sum(axis=0)))
324
+ self.components_kernel(
325
+ ((tensor.size + 255) // 256,),
326
+ (256,),
327
+ (
328
+ self.fc,
329
+ self.offsets,
330
+ self.pairs,
331
+ self.shortest,
332
+ self.phase,
333
+ tp,
334
+ prephase,
335
+ tensor,
336
+ np.int32(self.na),
337
+ np.int32(self.ns),
338
+ np.int32(self.average),
339
+ ),
340
+ )
341
+ return tensor
342
+
343
+ def transform(self, triplets):
344
+ """Transform a batch, returning a device tensor."""
345
+ import cupy as cp
346
+
347
+ if cp.cuda.Device().id != self.device:
348
+ raise RuntimeError("GPU FC3 cache belongs to a different CUDA device.")
349
+ batch = len(triplets)
350
+ shape = (batch, self.na, self.na, self.na, 3, 3, 3)
351
+ if not batch:
352
+ return cp.empty(shape, dtype="complex128")
353
+ with cp.cuda.using_allocator(self.pool.malloc):
354
+ ids = cp.asarray(triplets, dtype=cp.int64, order="C")
355
+ legs = cp.empty((3 if self.average else 1, *shape), cp.complex128)
356
+ result = cp.empty(shape, cp.complex128)
357
+ if self.method == "gemm":
358
+ self._gemm(ids, legs, batch)
359
+ elif self.method == "tiled":
360
+ self.tiled_kernel(
361
+ (self.na**3, (batch + self.tile - 1) // self.tile, len(legs)),
362
+ (32, self.tile),
363
+ (
364
+ self.fc,
365
+ self.offsets,
366
+ self.pairs,
367
+ self.shortest,
368
+ self.phase,
369
+ ids,
370
+ legs,
371
+ np.int32(self.na),
372
+ np.int32(self.ns),
373
+ np.int32(batch),
374
+ np.int32(self.average),
375
+ ),
376
+ )
377
+ else:
378
+ self.kernel(
379
+ ((self.na**3 + 3) // 4, batch, len(legs)),
380
+ (128,),
381
+ (
382
+ self.fc,
383
+ self.offsets,
384
+ self.pairs,
385
+ self.shortest,
386
+ self.phase,
387
+ ids,
388
+ legs,
389
+ np.int32(self.na),
390
+ np.int32(self.ns),
391
+ np.int32(batch),
392
+ np.int32(self.average),
393
+ ),
394
+ )
395
+ self.assemble(
396
+ ((result.size + 255) // 256,),
397
+ (256,),
398
+ (
399
+ legs,
400
+ self.qpoints,
401
+ self.origins,
402
+ ids,
403
+ result,
404
+ np.int32(self.na),
405
+ np.int32(batch),
406
+ np.int32(self.average),
407
+ ),
408
+ )
409
+ return result
410
+
411
+ def _gemm(self, ids, legs, batch):
412
+ """Use FP64 batched GEMM with fixed phase tiles to limit cached allocations."""
413
+ import cupy as cp
414
+
415
+ atoms, tile, npair = self.na**3, self.tile, self.uniform_pairs
416
+ fc = self.fc.reshape(atoms, npair, 32).swapaxes(1, 2)
417
+ real = cp.empty((atoms, npair, tile), dtype=cp.float64)
418
+ imag = cp.empty_like(real)
419
+ for start in range(0, batch, tile):
420
+ count = min(tile, batch - start)
421
+ for leg in range(len(legs)):
422
+ self.phase_products(
423
+ ((real.size + 255) // 256,),
424
+ (256,),
425
+ (
426
+ self.pairs,
427
+ self.shortest,
428
+ self.phase,
429
+ ids,
430
+ real,
431
+ imag,
432
+ np.int32(self.na),
433
+ np.int32(self.ns),
434
+ np.int32(npair),
435
+ np.int32(tile),
436
+ np.int32(start),
437
+ np.int32(count),
438
+ np.int32(leg),
439
+ np.int32(self.average),
440
+ ),
441
+ )
442
+ r, i = cp.matmul(fc, real), cp.matmul(fc, imag)
443
+ self.store_gemm(
444
+ ((atoms * 27 * count + 255) // 256,),
445
+ (256,),
446
+ (
447
+ r,
448
+ i,
449
+ legs,
450
+ np.int32(atoms),
451
+ np.int32(batch),
452
+ np.int32(tile),
453
+ np.int32(start),
454
+ np.int32(count),
455
+ np.int32(leg),
456
+ ),
457
+ )
458
+
459
+ @classmethod
460
+ def from_interaction(cls, interaction, **kwargs):
461
+ """Create a cache from a phono3py Interaction object."""
462
+ pp = interaction
463
+ return cls(
464
+ pp.fc3,
465
+ pp._fc3_nonzero_indices,
466
+ pp._svecs,
467
+ pp._multi,
468
+ pp._p2s,
469
+ pp._s2p,
470
+ pp._all_shortest,
471
+ pp.bz_grid.addresses @ pp.bz_grid.QDinv.T,
472
+ make_r0_average=pp._make_r0_average,
473
+ **kwargs,
474
+ )