An array on the GPU.
| 354 | |
| 355 | @mod.export() |
| 356 | class DeviceArray(DeviceView): |
| 357 | """ |
| 358 | An array on the GPU. |
| 359 | """ |
| 360 | |
| 361 | def __init__(self, shape=None, dtype=None): |
| 362 | """ |
| 363 | Args: |
| 364 | shape (Tuple[int]): The initial shape of the buffer. |
| 365 | dtype (numpy.dtype): The data type of the buffer. |
| 366 | """ |
| 367 | super().__init__(ptr=0, shape=util.default(shape, tuple()), dtype=util.default(dtype, np.float32)) |
| 368 | self.allocated_nbytes = 0 |
| 369 | self.resize(self.shape) |
| 370 | |
| 371 | def __enter__(self): |
| 372 | return self |
| 373 | |
| 374 | @staticmethod |
| 375 | def raw(shape): |
| 376 | """ |
| 377 | Creates an untyped device array of the specified shape. |
| 378 | |
| 379 | Args: |
| 380 | shape (Tuple[int]): |
| 381 | The initial shape of the buffer, in units of bytes. |
| 382 | For example, a shape of ``(4, 4)`` would allocate a 16 byte array. |
| 383 | |
| 384 | Returns: |
| 385 | DeviceArray: The raw device array. |
| 386 | """ |
| 387 | return DeviceArray(shape=shape, dtype=np.byte) |
| 388 | |
| 389 | def resize(self, shape): |
| 390 | """ |
| 391 | Resizes or reshapes the array to the specified shape. |
| 392 | |
| 393 | If the allocated memory region is already large enough, |
| 394 | no reallocation is performed. |
| 395 | |
| 396 | Args: |
| 397 | shape (Tuple[int]): The new shape. |
| 398 | """ |
| 399 | nbytes = util.volume(shape) * self.itemsize |
| 400 | if nbytes > self.allocated_nbytes: |
| 401 | self.free() |
| 402 | self.ptr = wrapper().malloc(nbytes) |
| 403 | self.allocated_nbytes = nbytes |
| 404 | self.shape = shape |
| 405 | |
| 406 | def __exit__(self, exc_type, exc_value, traceback): |
| 407 | """ |
| 408 | Frees the underlying memory of this DeviceArray. |
| 409 | """ |
| 410 | self.free() |
| 411 | |
| 412 | def free(self): |
| 413 | """ |
no outgoing calls