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 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
|
#!/usr/bin/env python
"""
Python interface to CUSPARSE functions.
Note: this module does not explicitly depend on PyCUDA.
"""
import atexit
import ctypes.util
import platform
from string import Template
import sys
import warnings
import numpy as np
import cuda
# Load library:
_version_list = [10.1, 10.0, 9.2, 9.1, 9.0, 8.0, 7.5, 7.0, 6.5, 6.0, 5.5, 5.0, 4.0]
if 'linux' in sys.platform:
_libcusparse_libname_list = ['libcusparse.so'] + \
['libcusparse.so.%s' % v for v in _version_list]
elif sys.platform == 'darwin':
_libcusparse_libname_list = ['libcusparse.dylib']
elif sys.platform == 'win32':
if platform.machine().endswith('64'):
_libcusparse_libname_list = ['cusparse.dll'] + \
['cusparse64_%s.dll' % (int(v) if v >= 10 else int(10*v))for v in _version_list]
else:
_libcusparse_libname_list = ['cusparse.dll'] + \
['cusparse32_%s.dll' % (int(v) if v >= 10 else int(10*v))for v in _version_list]
else:
raise RuntimeError('unsupported platform')
# Print understandable error message when library cannot be found:
_libcusparse = None
for _libcusparse_libname in _libcusparse_libname_list:
try:
if sys.platform == 'win32':
_libcusparse = ctypes.windll.LoadLibrary(_libcusparse_libname)
else:
_libcusparse = ctypes.cdll.LoadLibrary(_libcusparse_libname)
except OSError:
pass
else:
break
if _libcusparse == None:
OSError('CUDA sparse library not found')
class cusparseError(Exception):
"""CUSPARSE error"""
pass
class cusparseStatusNotInitialized(cusparseError):
"""CUSPARSE library not initialized"""
pass
class cusparseStatusAllocFailed(cusparseError):
"""CUSPARSE resource allocation failed"""
pass
class cusparseStatusInvalidValue(cusparseError):
"""Unsupported value passed to the function"""
pass
class cusparseStatusArchMismatch(cusparseError):
"""Function requires a feature absent from the device architecture"""
pass
class cusparseStatusMappingError(cusparseError):
"""An access to GPU memory space failed"""
pass
class cusparseStatusExecutionFailed(cusparseError):
"""GPU program failed to execute"""
pass
class cusparseStatusInternalError(cusparseError):
"""An internal CUSPARSE operation failed"""
pass
class cusparseStatusMatrixTypeNotSupported(cusparseError):
"""The matrix type is not supported by this function"""
pass
cusparseExceptions = {
1: cusparseStatusNotInitialized,
2: cusparseStatusAllocFailed,
3: cusparseStatusInvalidValue,
4: cusparseStatusArchMismatch,
5: cusparseStatusMappingError,
6: cusparseStatusExecutionFailed,
7: cusparseStatusInternalError,
8: cusparseStatusMatrixTypeNotSupported,
}
# Matrix types:
CUSPARSE_MATRIX_TYPE_GENERAL = 0
CUSPARSE_MATRIX_TYPE_SYMMETRIC = 1
CUSPARSE_MATRIX_TYPE_HERMITIAN = 2
CUSPARSE_MATRIX_TYPE_TRIANGULAR = 3
CUSPARSE_FILL_MODE_LOWER = 0
CUSPARSE_FILL_MODE_UPPER = 1
# Whether or not a matrix' diagonal entries are unity:
CUSPARSE_DIAG_TYPE_NON_UNIT = 0
CUSPARSE_DIAG_TYPE_UNIT = 1
# Matrix index bases:
CUSPARSE_INDEX_BASE_ZERO = 0
CUSPARSE_INDEX_BASE_ONE = 1
# Operation types:
CUSPARSE_OPERATION_NON_TRANSPOSE = 0
CUSPARSE_OPERATION_TRANSPOSE = 1
CUSPARSE_OPERATION_CONJUGATE_TRANSPOSE = 2
# Whether or not to parse elements of a dense matrix row or column-wise.
CUSPARSE_DIRECTION_ROW = 0
CUSPARSE_DIRECTION_COLUMN = 1
# Helper functions:
class cusparseMatDescr(ctypes.Structure):
_fields_ = [
('MatrixType', ctypes.c_int),
('FillMode', ctypes.c_int),
('DiagType', ctypes.c_int),
('IndexBase', ctypes.c_int)
]
def cusparseCheckStatus(status):
"""
Raise CUSPARSE exception
Raise an exception corresponding to the specified CUSPARSE error
code.
Parameters
----------
status : int
CUSPARSE error code.
See Also
--------
cusparseExceptions
"""
if status != 0:
try:
raise cusparseExceptions[status]
except KeyError:
raise cusparseError
_libcusparse.cusparseCreate.restype = int
_libcusparse.cusparseCreate.argtypes = [ctypes.c_void_p]
def cusparseCreate():
"""
Initialize CUSPARSE.
Initializes CUSPARSE and creates a handle to a structure holding
the CUSPARSE library context.
Returns
-------
handle : int
CUSPARSE library context.
"""
handle = ctypes.c_int()
status = _libcusparse.cusparseCreate(ctypes.byref(handle))
cusparseCheckStatus(status)
return handle.value
_libcusparse.cusparseDestroy.restype = int
_libcusparse.cusparseDestroy.argtypes = [ctypes.c_int]
def cusparseDestroy(handle):
"""
Release CUSPARSE resources.
Releases hardware resources used by CUSPARSE
Parameters
----------
handle : int
CUSPARSE library context.
"""
status = _libcusparse.cusparseDestroy(handle)
cusparseCheckStatus(status)
_libcusparse.cusparseGetVersion.restype = int
_libcusparse.cusparseGetVersion.argtypes = [ctypes.c_int,
ctypes.c_void_p]
def cusparseGetVersion(handle):
"""
Return CUSPARSE library version.
Returns the version number of the CUSPARSE library.
Parameters
----------
handle : int
CUSPARSE library context.
Returns
-------
version : int
CUSPARSE library version number.
"""
version = ctypes.c_int()
status = _libcusparse.cusparseGetVersion(handle,
ctypes.byref(version))
cusparseCheckStatus(status)
return version.value
_libcusparse.cusparseSetStream.restype = int
_libcusparse.cusparseSetStream.argtypes = [ctypes.c_int,
ctypes.c_int]
def cusparseSetStream(handle, id):
"""
Sets the CUSPARSE stream in which kernels will run.
Parameters
----------
handle : int
CUSPARSE library context.
id : int
Stream ID.
"""
status = _libcusparse.cusparseSetStream(handle, id)
cusparseCheckStatus(status)
_libcusparse.cusparseCreateMatDescr.restype = int
_libcusparse.cusparseCreateMatDescr.argtypes = [cusparseMatDescr]
def cusparseCreateMatDescr():
"""
Initialize a sparse matrix descriptor.
Initializes the `MatrixType` and `IndexBase` fields of the matrix
descriptor to the default values `CUSPARSE_MATRIX_TYPE_GENERAL`
and `CUSPARSE_INDEX_BASE_ZERO`.
Returns
-------
desc : cusparseMatDescr
Matrix descriptor.
"""
desc = cusparseMatrixDesc()
status = _libcusparse.cusparseCreateMatDescr(ctypes.byref(desc))
cusparseCheckStatus(status)
return desc
_libcusparse.cusparseDestroyMatDescr.restype = int
_libcusparse.cusparseDestroyMatDescr.argtypes = [ctypes.c_int]
def cusparseDestroyMatDescr(desc):
"""
Releases the memory allocated for the matrix descriptor.
Parameters
----------
desc : cusparseMatDescr
Matrix descriptor.
"""
status = _libcusparse.cusparseDestroyMatDescr(desc)
cusparseCheckStatus(status)
_libcusparse.cusparseSetMatType.restype = int
_libcusparse.cusparseSetMatType.argtypes = [cusparseMatDescr,
ctypes.c_int]
def cusparseSetMatType(desc, type):
"""
Sets the matrix type of the specified matrix.
Parameters
----------
desc : cusparseMatDescr
Matrix descriptor.
type : int
Matrix type.
"""
status = _libcusparse.cusparseSetMatType(desc, type)
cusparseCheckStatus(status)
_libcusparse.cusparseGetMatType.restype = int
_libcusparse.cusparseGetMatType.argtypes = [cusparseMatDescr]
def cusparseGetMatType(desc):
"""
Gets the matrix type of the specified matrix.
Parameters
----------
desc : cusparseMatDescr
Matrix descriptor.
Returns
-------
type : int
Matrix type.
"""
return _libcusparse.cusparseGetMatType(desc)
# Format conversion functions:
_libcusparse.cusparseSnnz.restype = int
_libcusparse.cusparseSnnz.argtypes = [ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
cusparseMatDescr,
ctypes.c_void_p,
ctypes.c_int,
ctypes.c_void_p,
ctypes.c_void_p]
def cusparseSnnz(handle, dirA, m, n, descrA, A, lda,
nnzPerRowColumn, nnzTotalDevHostPtr):
"""
Compute number of non-zero elements per row, column, or dense matrix.
Parameters
----------
handle : int
CUSPARSE library context.
dirA : int
Data direction of elements.
m : int
Rows in A.
n : int
Columns in A.
descrA : cusparseMatDescr
Matrix descriptor.
A : pycuda.gpuarray.GPUArray
Dense matrix of dimensions (lda, n).
lda : int
Leading dimension of A.
Returns
-------
nnzPerRowColumn : pycuda.gpuarray.GPUArray
Array of length m or n containing the number of
non-zero elements per row or column, respectively.
nnzTotalDevHostPtr : pycuda.gpuarray.GPUArray
Total number of non-zero elements in device or host memory.
"""
# Unfinished:
nnzPerRowColumn = gpuarray.empty()
nnzTotalDevHostPtr = gpuarray.empty()
status = _libcusparse.cusparseSnnz(handle, dirA, m, n,
descrA, int(A), lda,
int(nnzPerRowColumn), int(nnzTotalDevHostPtr))
cusparseCheckStatus(status)
return nnzPerVector, nnzHost
_libcusparse.cusparseSdense2csr.restype = int
_libcusparse.cusparseSdense2csr.argtypes = [ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
cusparseMatDescr,
ctypes.c_void_p,
ctypes.c_int,
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_void_p]
def cusparseSdense2csr(handle, m, n, descrA, A, lda,
nnzPerRow, csrValA, csrRowPtrA, csrColIndA):
# Unfinished
pass
|