Skip to content
Search

PyCUDA

lastmod 2024-07-11created 2024-06-183 edits

Install

pip install pycuda

Freeing CUDA memory with PyCUDA

CUDA context management

You can free GPU memory by creating and releasing a CUDA context in PyCUDA.

import pycuda.driver as cuda
import pycuda.autoinit  # 이 모듈은 기본 컨텍스트를 자동으로 초기화합니다.

# 메모리 할당 예시
d_a = cuda.mem_alloc(1000 * 4)  # 1000개의 float 메모리 할당

# 메모리 해제
d_a.free()

# 모든 컨텍스트 해제 (pycuda.autoinit 모듈을 사용하지 않는 경우)
cuda.Context.get_current().pop()

Explicit memory release

import pycuda.driver as cuda
import pycuda.autoinit  # 자동 초기화 (편리하지만 명시적으로 관리하고 싶다면 사용하지 않음)

# 메모리 할당
d_a = cuda.mem_alloc(1000 * 4)  # 1000개의 float 메모리 할당

# 할당된 메모리 사용
# (여기에 원하는 CUDA 연산 코드를 넣을 수 있습니다.)

# 메모리 해제
d_a.free()

# 자동 초기화 모듈 사용 시 현재 컨텍스트를 명시적으로 해제하지 않아도 됩니다.
# pycuda.autoinit 모듈을 사용하지 않았다면, 아래 코드로 컨텍스트를 해제해야 합니다.
# cuda.Context.pop()

Manual context management

To manage the context explicitly without automatic initialization, you can do the following.

import pycuda.driver as cuda

# 초기화
cuda.init()

# 첫 번째 GPU 선택
dev = cuda.Device(0)
ctx = dev.make_context()

# 메모리 할당 및 연산
d_a = cuda.mem_alloc(1000 * 4)  # 1000개의 float 메모리 할당

# 메모리 해제
d_a.free()

# 컨텍스트 해제
ctx.pop()
ctx.detach()

IPC Handle

Demonstrate how to pass IPC handles to GPU data between processes in Python

#!/usr/bin/env python

"""
Demonstrate how to pass IPC handles to GPU data between processes in Python.
"""

import ctypes
import numpy as np
import multiprocessing as mp
import zmq

import pycuda.driver as drv
import pycuda.gpuarray as gpuarray

N = 8
dtype = np.float64

def func1():
    drv.init()
    dev = drv.Device(0)
    ctx_gpu = dev.make_context()

    ctx = zmq.Context()
    sock = ctx.socket(zmq.REQ)
    sock.connect('tcp://localhost:6000')

    x = np.asarray(np.random.rand(N), dtype)
    print 'orig: ', x

    x_gpu = gpuarray.to_gpu(x)
    h = drv.mem_get_ipc_handle(x_gpu.ptr)

    sock.send_pyobj((h, x_gpu.shape, x_gpu.dtype))
    sock.recv()

    ctx_gpu.pop()

def func2():
    drv.init()
    dev = drv.Device(0)
    ctx_gpu = dev.make_context()

    ctx = zmq.Context()
    sock = ctx.socket(zmq.REP)
    sock.bind('tcp://*:6000')

    h, s, d = sock.recv_pyobj()
    sock.send('')

    x_ptr = drv.IPCMemoryHandle(h)
    x_gpu = gpuarray.GPUArray(s, d, gpudata=x_ptr)
    print 'gpu:  ', x_gpu.get()

    ctx_gpu.pop()

if __name__ == '__main__':
    p1 = mp.Process(target=func1)
    p2 = mp.Process(target=func2)

    p1.start()
    p2.start()

See also

author Zer0 sitemap