Advertisement
Guest User

Untitled

a guest
Sep 19th, 2020
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.54 KB | None | 0 0
  1. #!/usr/bin/env python
  2. from multiprocessing import Lock, Process, Queue, current_process
  3. import time
  4. import queue # imported for using queue.Empty exception
  5. import numpy as np
  6. import time
  7. from scipy._lib._util import _asarray_validated
  8. import sys
  9.  
  10. try:
  11.     import skcuda.magma as magma
  12.  
  13.     useScipy = False
  14. except Exception as err:
  15.     print("#", err)
  16.     print("# Cannot import scikit-cuda. Fall back to scipy.linalg")
  17.     import scipy.linalg
  18.     useScipy = True
  19.  
  20. typedict = {'s': np.float32, 'd': np.float64, 'c': np.complex64, 'z': np.complex128}
  21. typedict_ = {v: k for k, v in typedict.items()}
  22.  
  23.  
  24. def gpu_eig(lock, a, left=False, right=True, check_finite=True, verbose=True, *args, **kwargs):
  25.     """
  26.        Eigenvalue solver using Magma GPU library (variants of Lapack's geev).
  27.  
  28.        Note:
  29.        - not a generalized eigenvalue solver
  30.    """
  31.     if useScipy:
  32.         return scipy.linalg.eig(a, left=left, right=right, check_finite=check_finite)
  33.     else:
  34.         if len(a.shape) != 2:
  35.             raise ValueError("M needs to be a rank 2 square array for eig.")
  36.  
  37.         a = _asarray_validated(a, check_finite=check_finite)
  38.  
  39.         lock.acquire()
  40.         #magma.magma_init()
  41.         dtype = type(a[0, 0])
  42.         t = typedict_[dtype]
  43.         N = a.shape[0]
  44.  
  45.         # Set up output buffers:
  46.         if t in ['s', 'd']:
  47.             wr = np.zeros((N,), dtype)  # eigenvalues
  48.             wi = np.zeros((N,), dtype)  # eigenvalues
  49.         elif t in ['c', 'z']:
  50.             w = np.zeros((N,), dtype)  # eigenvalues
  51.  
  52.         if left:
  53.             vl = np.zeros((N, N), dtype)
  54.             jobvl = 'V'
  55.         else:
  56.             vl = np.zeros((1, 1), dtype)
  57.             jobvl = 'N'
  58.         if right:
  59.             vr = np.zeros((N, N), dtype)
  60.             jobvr = 'V'
  61.         else:
  62.             vr = np.zeros((1, 1), dtype)
  63.             jobvr = 'N'
  64.  
  65.         # Set up workspace:
  66.         if t == 's':
  67.             nb = magma.magma_get_sgeqrf_nb(N, N)
  68.         if t == 'd':
  69.             nb = magma.magma_get_dgeqrf_nb(N, N)
  70.         if t == 'c':
  71.             nb = magma.magma_get_cgeqrf_nb(N, N)
  72.         if t == 'z':
  73.             nb = magma.magma_get_zgeqrf_nb(N, N)
  74.  
  75.         lwork = N * (1 + 2 * nb)
  76.         work = np.zeros((lwork,), dtype)
  77.         if t in ['c', 'z']:
  78.             rwork = np.zeros((2 * N,), dtype)
  79.  
  80.         # Compute:
  81.         gpu_time = time.time();
  82.         if t == 's':
  83.             status = magma.magma_sgeev(jobvl, jobvr, N, a.ctypes.data, N,
  84.                                        wr.ctypes.data, wi.ctypes.data,
  85.                                        vl.ctypes.data, N, vr.ctypes.data, N,
  86.                                        work.ctypes.data, lwork)
  87.         if t == 'd':
  88.             status = magma.magma_dgeev(jobvl, jobvr, N, a.ctypes.data, N,
  89.                                        wr.ctypes.data, wi.ctypes.data,
  90.                                        vl.ctypes.data, N, vr.ctypes.data, N,
  91.                                        work.ctypes.data, lwork)
  92.         if t == 'c':
  93.             status = magma.magma_cgeev(jobvl, jobvr, N, a.ctypes.data, N,
  94.                                        w.ctypes.data, vl.ctypes.data, N, vr.ctypes.data, N,
  95.                                        work.ctypes.data, lwork, rwork.ctypes.data)
  96.         if t == 'z':
  97.             status = magma.magma_zgeev(jobvl, jobvr, N, a.ctypes.data, N,
  98.                                        w.ctypes.data, vl.ctypes.data, N, vr.ctypes.data, N,
  99.                                        work.ctypes.data, lwork, rwork.ctypes.data)
  100.         gpu_time = time.time() - gpu_time;
  101.  
  102.         if verbose:
  103.             print("Time for eig: ", gpu_time)
  104.  
  105.         if t in ['s', 'd']:
  106.             w_gpu = wr + 1j * wi
  107.         else:
  108.             w_gpu = w
  109.  
  110.         lock.release()
  111.         #magma.magma_finalize()
  112.         return w_gpu, vr
  113.  
  114. def get_eigsys(lock, mat, tasks_to_accomplish, tasks_that_are_done):
  115.     while True:
  116.         try:
  117.             '''
  118.                try to get task from the queue. get_nowait() function will
  119.                raise queue.Empty exception if the queue is empty.
  120.                queue(False) function would do the same task also.
  121.            '''
  122.             task_ampl = tasks_to_accomplish.get_nowait()
  123.             w, v = gpu_eig(lock, mat, left=False, right=True)
  124.  
  125.         except queue.Empty:
  126.  
  127.             break
  128.         else:
  129.             '''
  130.                if no exception has been raised, add the task completion
  131.                message to task_that_are_done queue
  132.            '''
  133.             tasks_that_are_done.put((task_ampl,w,v))
  134.             time.sleep(.5)
  135.     return True
  136.  
  137.  
  138. def main():
  139.     size = 3
  140.     ampls = np.linspace(10.0, 30.0, 2)
  141.     number_of_task = len(ampls)
  142.     number_of_processes = number_of_task
  143.     tasks_to_accomplish = Queue()
  144.     tasks_that_are_done = Queue()
  145.     processes = []
  146.     magma.magma_init()
  147.  
  148.     for h in ampls:
  149.         tasks_to_accomplish.put(h)
  150.  
  151.     # creating processes
  152.     lock = Lock()
  153.     for h in ampls:
  154.         #Generate Floquet Matrix here. Random for now
  155.         floquet_matrix = np.random.random((size,size)) + (1j) * np.random.random((size,size))
  156.         p = Process(target=get_eigsys, args=(lock, floquet_matrix, tasks_to_accomplish, tasks_that_are_done))
  157.         processes.append(p)
  158.         p.start()
  159.  
  160.     # completing process
  161.     for p in processes:
  162.         p.join()
  163.  
  164.     magma.magma_finalize()
  165.  
  166.     # print the output
  167.     while not tasks_that_are_done.empty():
  168.         print(tasks_that_are_done.get())
  169.  
  170.     return True
  171.  
  172.  
  173. if __name__ == '__main__':
  174.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement