So far, we have been importing pycuda.autoinit at the beginning of all of our PyCUDA programs; this effectively creates a context at the beginning of our program and has it destroyed at the end.
Let's try doing this manually. We will make a small program that just copies a small array to the GPU, copies it back to the host, prints the array, and exits.
We start with the imports:
import numpy as np
from pycuda import gpuarray
import pycuda.driver as drv
First, we initialize CUDA with the pycuda.driver.init function, which is here aliased as drv:
drv.init()
Now we choose which GPU we wish to work with; this is necessary for the cases where one has more than one GPU. We can select a specific GPU with pycuda.driver.Device; if you only have one GPU, as I do, you can access it with pycuda.driver.Device(0), as follows:
dev = drv.Device(0)
We can now create a new context on this device with make_context, as follows:
ctx = dev.make_context()
Now that we have a new context, this will automatically become the default context. Let's copy an array into the GPU, copy it back to the host, and print it:
x = gpuarray.to_gpu(np.float32([1,2,3]))
print x.get()
Now we are done. We can destroy the context by calling the pop function:
ctx.pop()
That's it! We should always remember to destroy contexts that we explicitly created with pop before our program exists.
(This example can be seen in the simple_context_create.py file under this chapter's directory in the repository.)