Repository navigation
Expand file tree
/
Copy pathsampling_cuda.py
More file actions
89 lines (67 loc) · 3.08 KB
/
Copy pathsampling_cuda.py
File metadata and controls
89 lines (67 loc) · 3.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# %%
"""Same as the sampling.py demo, but E_loc is computed by the CUDA kernel.
Samples come from `sample(W, b, n_samples)` (Python), their local energies
from `cuda/eloc_batched.cu`, called through ctypes. The Python reference
`eloc_lookup_table` is run on the same samples for comparison.
Build the library first (no GPU needed to compile):
make -C cuda
Running needs a GPU; on the cluster go through SLURM, e.g.
srun -p uscm --gres=gpu:1 --time=00:10:00 python sampling_cuda.py
"""
import sys
import ctypes
import os
import time
from eloc_old import load_states, load_trained_rbm, square_lattice_bonds
import numpy as np
LIB_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cuda", "libeloc.so")
def load_library(path=LIB_PATH):
"""Load libeloc.so and declare the C signatures, so ctypes checks every call."""
if not os.path.exists(path):
raise FileNotFoundError(f"{path} not found -- build it with `make -C cuda`")
lib = ctypes.CDLL(path) # CDLL releases the GIL during calls
def array(dtype, ndim):
return np.ctypeslib.ndpointer(dtype=dtype, ndim=ndim, flags="C_CONTIGUOUS")
lib.eloc_cuda.argtypes = [
array(np.float32, 2), # W_T (M, N)
array(np.float32, 2), # samples (n_samples, N)
array(np.float32, 2), # theta (n_samples, M)
array(np.int32, 2), # bonds (2N, 2)
array(np.float64, 1), # elocs (n_samples,), output
ctypes.c_int, # nspins
ctypes.c_int, # nhidden
ctypes.c_int, # n_samples
]
lib.eloc_cuda.restype = ctypes.c_int # cudaError_t, 0 = success
lib.eloc_cuda_error_string.argtypes = [ctypes.c_int]
lib.eloc_cuda_error_string.restype = ctypes.c_char_p
return lib
def eloc_cuda(lib, samples, bonds, W, b):
"""E_loc of every sample, computed on the GPU (float32 inside).
Prepares exactly the arrays the kernel expects: W transposed, theta
precomputed on the host, everything float32 and C-contiguous.
"""
n_samples, N = samples.shape
M = W.shape[1]
assert bonds.shape == (2 * N, 2), "the kernel assumes 2N bonds (periodic square lattice)"
W_T = np.ascontiguousarray(W.T, dtype=np.float32)
samples32 = np.ascontiguousarray(samples, dtype=np.float32)
theta = np.ascontiguousarray(b + samples @ W, dtype=np.float32)
bonds32 = np.ascontiguousarray(bonds, dtype=np.int32)
elocs = np.zeros(n_samples, dtype=np.float64)
code = lib.eloc_cuda(W_T, samples32, theta, bonds32, elocs, N, M, n_samples)
if code != 0:
raise RuntimeError(f"eloc_cuda failed: {lib.eloc_cuda_error_string(code).decode()}")
return elocs
if __name__ == "__main__":
args = sys.argv
alpha, L, runs, gamma = int(args[1]), int(args[2]), int(args[3]), float(args[4])
N = L * L
W, b = load_trained_rbm(N, alpha)
lib = load_library()
bonds = square_lattice_bonds(L, L)
samples = load_states(N, runs)
start = time.perf_counter()
results = eloc_cuda(lib, samples, bonds, W, b) / (N * 4)
rt = time.perf_counter() - start
print(f"{rt*1000:.6f} {sum(results):.6f}")