技术文章和时事通讯

gpu programming in matlab -凯发k8网页登录

by jill reese, mathworks and sarah zaranek, mathworks


multicore machines and hyper-threading technology have enabled scientists, engineers, and financial analysts to speed up computationally intensive applications in a variety of disciplines. today, another type of hardware promises even higher computational performance: the graphics processing unit (gpu).

originally used to accelerate graphics rendering, gpus are increasingly applied to scientific calculations. unlike a traditional cpu, which includes no more than a handful of cores, a gpu has a massively parallel array of integer and floating-point processors, as well as dedicated, high-speed memory. a typical gpu comprises hundreds of these smaller processors (figure 1).

figure 1. comparison of the number of cores on a cpu system and a gpu.

the greatly increased throughput made possible by a gpu, however, comes at a cost. first, memory access becomes a much more likely bottleneck for your calculations. data must be sent from the cpu to the gpu before calculation and then retrieved from it afterwards. because a gpu is attached to the host cpu via the pci express bus, the memory access is slower than with a traditional cpu.1 this means that your overall computational speedup is limited by the amount of data transfer that occurs in your algorithm. second, programming for gpus in c or fortran requires a different mental model and a skill set that can be difficult and time-consuming to acquire. additionally, you must spend time fine-tuning your code for your specific gpu to optimize your applications for peak performance.

this article demonstrates features in parallel computing toolbox that enable you to run your matlab® code on a gpu by making a few simple changes to your code. we illustrate this approach by solving a second-order wave equation using spectral methods.

why parallelize a wave equation solver?

wave equations are used in a wide range of engineering disciplines, including seismology, fluid dynamics, acoustics, and electromagnetics, to describe sound, light, and fluid waves.

an algorithm that uses spectral methods to solve wave equations is a good candidate for parallelization because it meets both of the criteria for acceleration using the gpu (see "will execution on a gpu accelerate my application?"):

it is computationally intensive. the algorithm performs many fast fourier transforms (ffts) and inverse fast fourier transforms (iffts). the exact number depends on the size of the grid (figure 2) and the number of time steps included in the simulation. each time step requires two ffts and four iffts on different matrices, and a single computation can involve hundreds of thousands of time steps.

it is massively parallel. the parallel fft algorithm is designed to "divide and conquer" so that a similar task is performed repeatedly on different data. additionally, the algorithm requires substantial communication between processing threads and plenty of memory bandwidth. the ifft can similarly be run in parallel.

video length is 0:08.

figure 2. a solution for a second-order wave equation on a 32 x 32 grid.

will execution on a gpu accelerate my application?

a gpu can accelerate an application if it fits both of the following criteria:

computationally intensive—the time spent on computation significantly exceeds the time spent on transferring data to and from gpu memory.

massively parallel—the computations can be broken down into hundreds or thousands of independent units of work.

applications that do not satisfy these criteria might actually run slower on a gpu than on a cpu.

gpu computing in matlab

before continuing with the wave equation example, let's quickly review how matlab works with the gpu.

fft, ifft, and linear algebraic operations are among more than 100 built-in matlab functions that can be executed directly on the gpu by providing an input argument of the type gpuarray, a special array type provided by parallel computing toolbox. these gpu-enabled functions are overloaded—in other words, they operate differently depending on the data type of the arguments passed to them.

for example, the following code uses an fft algorithm to find the discrete fourier transform of a vector of pseudorandom numbers on the cpu:

a = rand(2^16,1);

b = fft(a);

to perform the same operation on the gpu, we first use the gpuarray command to transfer data from the matlab workspace to device memory. then we can run fft, which is one of the overloaded functions on that data:

a = gpuarray(rand(2^16,1));

b = fft(a);

the fft operation is executed on the gpu rather than the cpu since its input (a gpuarray) is held on the gpu.

the result, b, is stored on the gpu. however, it is still visible in the matlab workspace. by running class(b), we can see that it is a gpuarray.

class(b)

ans =

parallel.gpu.gpuarray

we can continue to manipulate b on the device using gpu-enabled functions. for example, to visualize our results, the plot command automatically works on gpuarrays:

plot(b);

to return the data back to the local matlab workspace, you can use the gather command; for example

c = gather(b);

c is now a double in matlab and can be operated on by any of the matlab functions that work on doubles.

in this simple example, the time saved by executing a single fft function is often less than the time spent transferring the vector from the matlab workspace to the device memory. this is generally true but is dependent on your hardware and size of the array. data transfer overhead can become so significant that it degrades the application's overall performance, especially if you repeatedly exchange data between the cpu and gpu to execute relatively few computationally intensive operations. it is more efficient to perform several operations on the data while it is on the gpu, bringing the data back to the cpu only when required2.

note that gpus, like cpus, have finite memories. however, unlike cpus, they do not have the ability to swap memory to and from disk. thus, you must verify that the data you want to keep on the gpu does not exceed its memory limits, particularly when you are working with large matrices. by running gpudevice, you can query your gpu card, obtaining information such as name, total memory, and available memory.

implementing and accelerating the algorithm to solve a wave equation in matlab

to put the above example into context, let's implement the gpu functionality on a real problem. our computational goal is to solve the second-order wave equation

\[\frac{\partial^2 u}{\partial t^2} = \frac{\partial^2 u}{\partial x^2} \frac{\partial^2 u}{\partial y^2}\]

with the condition \(u = 0\) on the boundaries. we use an algorithm based on spectral methods to solve the equation in space and a second-order central finite difference method to solve the equation in time.

spectral methods are commonly used to solve partial differential equations. with spectral methods, the solution is approximated as a linear combination of continuous basis functions, such as sines and cosines. in this case, we apply the chebyshev spectral method, which uses chebyshev polynomials as the basis functions.

at every time step, we calculate the second derivative of the current solution in both the \(x\) and \(y\) dimensions using the chebyshev spectral method. using these derivatives together with the old solution and the current solution, we apply a second-order central difference method (also known as the leap-frog method) to calculate the new solution. we choose a time step that maintains the stability of this leap-frog method.

the matlab algorithm is computationally intensive, and as the number of elements in the grid over which we compute the solution grows, the time the algorithm takes to execute increases dramatically. when executed on a single cpu using a 2048 x 2048 grid, it takes more than a minute to complete just 50 time steps. note that this time already includes the performance benefit of the inherent multithreading in matlab. since r2007a, matlab supports multithreaded computation for a number of functions. these functions automatically execute on multiple threads without the need to explicitly specify commands to create threads in your code.

when considering how to accelerate this computation using parallel computing toolbox, we will focus on the code that performs computations for each time step. figure 3 illustrates the changes required to get the algorithm running on the gpu. note that the computations involve matlab operations for which gpu-enabled overloaded functions are available through parallel computing toolbox. these operations include fft and ifft, matrix multiplication, and various element-wise operations. as a result, we do not need to change the algorithm in any way to execute it on a gpu. we simply transfer the data to the gpu using gpuarray before entering the loop that computes results at each time step.

figure 3. code comparison tool showing the differences in the cpu and gpu versions of the code. the gpu and cpu versions share over 84% of their code in common (94 lines out of 111).

after the computations are performed on the gpu, we transfer the results from the gpu to the cpu. each variable referenced by the gpu-enabled functions must be created on the gpu or transferred to the gpu before it is used.

to convert one of the weights used for spectral differentiation to a gpuarray variable, we use

w1t = gpuarray(w1t);

certain types of arrays can be constructed directly on the gpu without our having to transfer them from the matlab workspace. for example, to create a matrix of zeros directly on the gpu, we use

uxx = parallel.gpu.gpuarray.zeros(n 1,n 1);

we use the gather function to bring data back from the gpu; for example:

vvg = gather(vv);

note that there is a single transfer of data to the gpu, followed by a single transfer of data from the gpu. all the computations for each time step are performed on the gpu.

comparing cpu and gpu execution speeds

to evaluate the benefits of using the gpu to solve second-order wave equations, we ran a benchmark study in which we measured the amount of time the algorithm took to execute 50 time steps for grid sizes of 64, 128, 512, 1024, and 2048 on an intel® xeon® processor x5650 and then using an nvidia® tesla c2050 gpu.

for a grid size of 2048, the algorithm shows a 7.5x decrease in compute time from more than a minute on the cpu to less than 10 seconds on the gpu (figure 4). the log scale plot shows that the cpu is actually faster for small grid sizes. as the technology evolves and matures, however, gpu solutions are increasingly able to handle smaller problems, a trend that we expect to continue.

figure 4. plot of benchmark results showing the time required to complete 50 time steps for different grid sizes, using either a linear scale (left) or a log scale (right).

advanced gpu programming with matlab

parallel computing toolbox provides a straightforward way to speed up matlab code by executing it on a gpu. you simply change the data type of a function's input to take advantage of the many matlab commands that have been overloaded for gpuarrays. (a complete list of built-in matlab functions that support gpuarray is available in the parallel computing toolbox documentation.)

to accelerate an algorithm with multiple simple operations on a gpu, you can use arrayfun, which applies a function to each element of an array. because arrayfun is a gpu-enabled function, you incur the memory transfer overhead only on the single call to arrayfun, not on each individual operation.

finally, experienced programmers who write their own cuda code can use the cudakernel interface in parallel computing toolbox to integrate this code with matlab. the cudakernel interface enables even more fine-grained control to speed up portions of code that were performance bottlenecks. it creates a matlab object that provides access to your existing kernel compiled into ptx code (ptx is a low-level parallel thread execution instruction set). you then invoke the feval command to evaluate the kernel on the gpu, using matlab arrays as input and output.

summary

engineers and scientists are successfully employing gpu technology, originally intended for accelerating graphics rendering, to accelerate their discipline-specific calculations. with minimal effort and without extensive knowledge of gpus, you can now use the promising power of gpus with matlab. gpuarrays and gpu-enabled matlab functions help you speed up matlab operations without low-level cuda programming. if you are already familiar with programming for gpus, matlab also lets you integrate your existing cuda kernels into matlab applications without requiring any additional c programming.

to achieve speedups with the gpus, your application must satisfy some criteria, among them the fact that sending the data between the cpu and gpu must take less time than the performance gained by running on the gpu. if your application satisfies these criteria, it is a good candidate for the range of gpu functionality available with matlab.

gpu glossary

cpu (central processing unit). the central unit in a computer responsible for calculations and for controlling or supervising other parts of the computer. the cpu performs logical and floating point operations on data held in the computer memory.

gpu (graphics processing unit). programmable chip originally intended for graphics rendering. the highly parallel structure of a gpu makes them more effective than general-purpose cpus for algorithms where processing of large blocks of data is done in parallel.

core. a single independent computational unit within a cpu or gpu chip. cpu and gpu cores are not equivalent to each other; gpu cores perform specialized operations whereas cpu cores are designed for general-purpose programs.

cuda®. a parallel computing technology from nvidia® that consists of a parallel computing architecture and developer tools, libraries, and programming directives for gpu computing.

device. a hardware card containing the gpu and its associated memory.

host. the cpu and system memory.

kernel. code written for execution on the gpu. kernels are functions that can run on a large number of threads. the parallelism arises from each thread independently running the same program on different data.

published 2011 - 91967v01

references

  1. see chapter 6 (memory optimization) of the nvidia “cuda c best practices” documentation for further information about potential gpu-computing bottlenecks and optimization of gpu memory access.

  2. see chapter 6 (memory optimization) of the nvidia “cuda c best practices” documentation for further information about improving performance by minimizing data transfers.

view articles for related capabilities

view articles for related industries

网站地图