找回密码
 注册
关于网站域名变更的通知
查看: 741|回复: 2
打印 上一主题 下一主题

Matlab应用之GPU加速

[复制链接]

该用户从未签到

跳转到指定楼层
1#
发表于 2020-1-20 09:44 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式

EDA365欢迎您登录!

您需要 登录 才可以下载或查看,没有帐号?注册

x
6 A0 q0 W; n2 }+ I5 K4 K
由于GPU近几年地迅速发展,GPU在多线程计算等方面逐渐超越CPU成为计算的主力军。而Matlab是常用的数学应用软件,现在讲解一下如何在Matlab中使用GPU加速计算
1 P4 m+ i4 H9 U: f3 Y6 T" N) z5 L+ W1 [1 d2 ~) t/ f
文章目录, |, b# S# v. }" l
       0. 必要条件3 d3 c3 q- X0 Z, W7 r. M% d
       1.给GPU传输数据- [+ B" s* O) z5 i* ~' s! k
              1.1 CPU的数据复制到GPU
9 l, `. Q/ ?5 o              1.2 直接在GPU上设置数据:+ F2 t6 C* |( I/ U, ~4 Y7 x. l0 i6 j. j- G
       2.数据在GPU上运算  j- y* ~  W/ @" B0 l
       3.GPU数据回传% U5 E- B" |0 U# Y' \  a
       4.使用技巧9 ^/ J* R  V9 a9 O; q- o
              4.1 如果没有并行计算不建议使用GPU
$ z% V  }9 g; \' r              4.2 如果没有Nvidia显卡或者显卡驱动( N" c! M% {" L& y. p9 [( o
              4.3 双精度尽量转换为单精度
* J3 @9 A& c" m/ X  o- W! q7 s       附录
1 [* M" Y. F& I+ Q% y$ K6 j
( w4 `4 M' Q6 [1 M4 s, G
. ^% n1 Y( \7 k& P4 F' p: z
0 [0 m2 K' {: a) l2 p/ p: k0. 必要条件
9 b( E, F; C5 w! F! e! C5 }
1 e: g% L& u3 Y$ a3 ]( A* w要想在Matlab中使用GPU加速有两个必须的条件
! x& k' b6 E) ?' B
& m- v$ Z6 j8 P9 z: _" @; w# j
  • 计算机上安装了NVIDIA显卡,目前AMD与Intel显示是暂不支持的;
  • 安装NVIDIA显卡驱动。0 s7 C0 O6 V4 K4 [# d
" R4 ~) p! W4 Y) `
1 A, g, O) \2 ~4 [
1.给GPU传输数据* a  q/ c. n1 H
; p' ^  `$ w# [: C6 ^. ^
1.1 CPU的数据复制到GPU
/ D& r/ \+ L9 Y. n: Y+ N
- H8 f: x7 u! n3 Z# x8 Q在使用GPU计算的时候,只需要将CPU的数据复制到GPU中即可。$ o) P, m" k( D9 N3 t$ E' t

- x3 R$ }3 s' U4 @: o  ^
  • G = gpuArray(M);
    ! T7 O7 H8 x& D% d! r% k
2 V# N# H4 E! l7 |* N4 l
2 k/ `( r7 @! ?" z6 b
上边是对数据的名称做了修改,也可以直接进行重新赋值。
" T7 x+ k. {7 J& Y* G# k2 p: s: W2 p7 q3 r* W
  • M = gpuArray(M);
    : T& v$ o  _! U  `+ P" n( g

4 @2 Q7 E/ L2 V/ z  C, a, V) y4 h- K) n$ v
1.2 直接在GPU上设置数据:4 P0 N1 a1 P0 n# ^0 r
6 z! C% }# J! d# f; u6 G$ ^8 s
  • A = zeros(10, 'gpuArray');
    ; ]: y7 Y  ~2 J8 r5 |3 D* O

2 |' z) `, Z4 E& ?4 Z" Y3 M. J) `' B# |' @
可以对0矩阵以及1矩阵直接进行复制,但是在程序后边需要标注使用gpuArray。+ o7 ?" M; I; T, I

* C- u1 C7 a4 k6 g# D. M
  • r = gpuArray.rand(1, 100) % 一行,一百列, ~1 J; x) Z4 [" c8 n$ E
" C' i, w5 p; p9 P- [$ k
( q. Q* A) X: N* i6 }2 q; d
随机矩阵的产生。: Z, Y! H8 d6 e5 F0 \) a$ T* Z* D& z. }
7 y- J4 L* a6 ^. ]7 ?) M: T$ c
2.数据在GPU上运算. [! N2 K) R! T
& s2 K( o1 H; l! G
在GPU可以正常运行基本的运算,与正常矩阵计算方法相同
% Q+ o0 D7 J8 _' [' V. o0 H- S! l- S% x3 F3 p6 i
  • A=abs(A);+ {* _& _+ k9 L* L; e
7 \/ Y* n  Y) ~* H
/ K; M$ z& g/ X: V8 n+ J
具体的可以运行的运算可以使用命令
; O6 R' m) T1 h  k/ }1 A, \! `3 r) W$ T9 @
  • methods(gpuArray)0 o7 z! n+ {- v+ s' i0 M$ ?) H0 D- E
+ ~- N6 |& q) C* i9 f/ a& Z8 \
4 F$ @9 U6 P( q9 q  w" w# C
进行查看,Matlab可以在GPU运行的具体运算可以查看附录,附录中是Matlab给出的结果。$ V# x( U  @, q
( i- `- n6 B/ H; k
3.GPU数据回传1 e# K1 m4 X/ a
$ J! @$ {4 v8 c4 J- k5 n8 ^# n+ i4 V
  • B = gather (A);# S. I: g$ D- X6 |* f$ v
/ f/ ~$ o0 F1 c9 W
9 E; ~& o# G# P- Q" {2 A
直接使用上边的命令就能够将GPU中的数据回传给CPU。+ f2 w: w6 B! W
4 G- p9 D% |# n  _3 I% h
4.使用技巧
2 c$ |0 r, b6 g) K: ~
3 z% i" e4 x2 B4.1 如果没有并行计算不建议使用GPU: s7 A! [& \3 K  E) k

& C. ^5 S8 R0 w
  • index = 0;
  • index = gpuArray(index);
  • for i = 1 : 10000
  •     tic
  •     for j = 1 : 100000
  •         index = index + 1;
  •     end
  •     toc
  • end
  • disp(index)
    # p/ K8 g& R& d& y& m

' J6 C, o! {. q9 u: T& s# A4 f+ Q9 ], _1 z7 f: h0 w6 Z, z
通过上边程序第二行程序就可以在GPU上运行,注释掉就会在CPU上运行。在我的电脑上运行时间如下表所示。$ c! `" y  g. Y3 j3 o2 U( D
( u' y) j. W2 @6 J0 w# ?: y% G
设备                 CPU                      GPU. `: `4 t/ D, x8 a* t7 Z
时间              0.00010 s            1.973017 s! d2 G9 T1 n5 a# {# @8 F- s

9 F) W% g5 H5 H由此可以看出,单个线程运行程序还是建议在CPU上运行,CPU的主频还是高一点,GPU主要是支持多个线程同时运行。% M6 ?) N, D, _7 o+ A
2 ?+ \' @( a6 |( y2 k/ d
4.2 如果没有Nvidia显卡或者显卡驱动
. M5 {8 o  s8 {) ]4 v  ?2 r0 T5 f8 H) Z. m, G
如果没有Nvidia显卡或者显卡驱动,会显示下边的提示。
3 e  K2 e0 X( s6 J
. e+ C, {3 E$ ]3 }8 _  N+ P ; }2 q# v- \! N

1 L3 r4 M  G, ^9 ]4.3 双精度尽量转换为单精度
8 ?: z5 H! v4 ]& n
  b3 m! C5 X& g2 r) n在条件允许的情况下,尽量将计算过程中双精度转换为单精度。因为在GPU中单精度的计算速度明显优于双精度,在时间上会有很大的缩减。
5 g' Z8 C( T' I附:单精度与上精度区别3 ^7 s& k4 |- u" [

# T- @) e) P9 g) q: V  n$ Q数据类型                    大小(字节)                     取值范围                  保留有效位数, ?% a! f5 o  L! v" V
单精度                   4个字节(32位)         3.4E-38~3.4E+38               7位
6 U; V6 t- q' V& g' [6 M( G$ B% E/ _  t双精度                   8个字节(64位)         1.7E-308~1.7E+308           16位; I0 w) L/ U( Q1 i) @
' s2 B, n4 ^( i6 J# q
" I  Y3 ?1 C, D: U+ E
附录
8 F3 r# d! k1 ~* ~
" L: T% Z: w% z* h* j6 w# R
  • >> methods(gpuArray)
  • Methods for class gpuArray:
  • abs                   eq                    ipermute              quiver3
  • accumarray            eRF                   iradon                rad2deg
  • acos                  erfc                  isaUnderlying         radon
  • acosd                 erfcinv               isbanded              rdivide
  • acosh                 erfcx                 isdiag                real
  • acot                  erfinv                isempty               reallog
  • acotd                 errorbar              isequal               realpow
  • acoth                 existsOnGPU           isequaln              realsqrt
  • acsc                  exp                   isequalwithequalnans  reducepatch
  • acscd                 expint                isfinite              reducevolume
  • acsch                 expm                  isfloat               regionprops
  • all                   expm1                 ishermitian           rem
  • and                   eye                   isinf                 repelem
  • angle                 ezcontour             isinteger             repmat
  • any                   ezcontourf            islogical             reshape
  • applylut              ezgraph3              ismember              rgb2gray
  • area                  ezmesh                ismembertol           rgb2hsv
  • arrayfun              ezmeshc               isnan                 rgb2ycbcr
  • asec                  ezplot                isnumeric             ribbon
  • asecd                 ezplot3               isocaps               roots
  • asech                 ezpolar               isocolors             rose
  • asin                  ezsurf                isonormals            rot90
  • asind                 ezsurfc               isosurface            round
  • asinh                 factorial             isreal                scatter
  • assert                false                 issorted              scatter3
  • atan                  feather               issparse              sec
  • atan2                 fft                   issymmetric           secd
  • atan2d                fft2                  istril                sech
  • atand                 fftfilt               istriu                semilogx
  • atanh                 fftn                  kmeans                semilogy
  • bandwidth             fill                  knnsearch             setdiff
  • bar                   fill3                 ldivide               setxor
  • bar3                  filter                le                    shiftdim
  • bar3h                 filter2               legendre              shrinkfaces
  • barh                  find                  length                sign
  • besselj               fix                   line                  sin
  • bessely               flip                  linspace              sind
  • beta                  flipdim               log                   single
  • betainc               fliplr                log10                 sinh
  • betaincinv            flipud                log1p                 size
  • betaln                floor                 log2                  slice
  • bicg                  fplot                 logical               smooth3
  • bicgstab              fprintf               loglog                sort
  • bicgstabl             full                  logspace              sortrows
  • bitand                gamma                 lsqr                  sparse
  • bitcmp                gammainc              lt                    spfun
  • bitget                gammaincinv           lu                    spones
  • bitor                 gammaln               mat2gray              sprand
  • bitset                gather                mat2str               sprandn
  • bitshift              ge                    max                   sprandsym
  • bitxor                gmres                 mean                  sprintf
  • bsxfun                gop                   medfilt2              spy
  • bwdist                gpuArray              mesh                  sqrt
  • bwlabel               gradient              meshc                 stairs
  • bwlookup              gt                    meshgrid              std2
  • bwmorph               head                  meshz                 stdfilt
  • cast                  hist                  min                   stem
  • cat                   histc                 minres                stem3
  • cconv                 histcounts            minus                 stream2
  • cdf2rdf               histeq                mldivide              stream3
  • ceil                  histogram             mod                   streamline
  • cgs                   horzcat               mode                  streamparticles
  • chol                  hsv2rgb               movmean               streamribbon
  • circshift             hypot                 movstd                streamslice
  • clabel                idivide               movsum                streamtube
  • classUnderlying       ifft                  movvar                stretchlim
  • comet                 ifft2                 mpower                sub2ind
  • comet3                ifftn                 mrdivide              subsasgn
  • compass               im2double             mtimes                subsindex
  • complex               im2int16              nan                   subspace
  • cond                  im2single             ndgrid                subsref
  • coneplot              im2uint16             ndims                 subvolume
  • conj                  im2uint8              ne                    sum
  • contour               imabsdiff             nextpow2              superiorfloat
  • contour3              imadjust              nnz                   surf
  • contourc              imag                  nonzeros              surfc
  • contourf              image                 norm                  surfl
  • contourslice          imagesc               normest               svd
  • conv                  imbothat              normxcorr2            svds
  • conv2                 imclose               not                   swapbytes
  • convn                 imcomplement          nthroot               symmlq
  • corr2                 imdilate              null                  tail
  • corrcoef              imerode               num2str               tan
  • cos                   imfill                numel                 tand
  • cosd                  imfilter              nzmax                 tanh
  • cosh                  imgaussfilt           ones                  tfqmr
  • cot                   imgaussfilt3          or                    times
  • cotd                  imgradient            padarray              transpose
  • coth                  imgradientxy          pagefun               trapz
  • cov                   imhist                pareto                tril
  • csc                   imlincomb             patch                 trimesh
  • cscd                  imnoise               pcg                   trisurf
  • csch                  imopen                pcolor                triu
  • ctranspose            imreconstruct         pdist                 true
  • cummax                imregdemons           pdist2                typecast
  • cummin                imregionalmax         permute               uint16
  • cumprod               imregionalmin         pie                   uint32
  • cumsum                imresize              pie3                  uint64
  • curl                  imrotate              planerot              uint8
  • deg2rad               imrotate_old          plot                  uminus
  • del2                  imshow                plot3                 union
  • det                   imtophat              plotmatrix            unique
  • detectFASTFeatures    ind2sub               plotyy                uniquetol
  • detectHarrisFeatures  inf                   plus                  unwrap
  • detrend               inpolygon             polar                 uplus
  • diag                  int16                 poly                  var
  • diff                  int2str               polyder               vertcat
  • discretize            int32                 polyfit               vissuite
  • disp                  int64                 polyval               volumebounds
  • display               int8                  polyvalm              voronoi
  • divergence            interp1               pow2                  waterfall
  • dot                   interp2               power                 xcorr
  • double                interp3               prod                  xor
  • edge                  interpn               psi                   ycbcr2rgb
  • eig                   interpstreamspeed     qmr                   zeros
  • end                   intersect             qr
  • eps                   inv                   quiver
  • Static methods:
  • colon                 rand                  randperm
  • freqspace             randi                 speye
  • loadobj               randn
    ) Y% A4 z1 n) l7 A
# Z+ I/ H$ i; U# U  U
9 ?/ u& P. I7 q7 J

' x1 k( }  r$ ?1 r, a' V: z& e

该用户从未签到

2#
发表于 2020-1-20 18:00 | 只看该作者
Matlab应用      GPU加速

该用户从未签到

3#
发表于 2020-1-21 17:51 | 只看该作者
Matlab应用之GPU加速
您需要登录后才可以回帖 登录 | 注册

本版积分规则

关闭

推荐内容上一条 /1 下一条

EDA365公众号

关于我们|手机版|EDA365电子论坛网 ( 粤ICP备18020198号-1 )

GMT+8, 2025-11-2 12:29 , Processed in 0.171875 second(s), 27 queries , Gzip On.

深圳市墨知创新科技有限公司

地址:深圳市南山区科技生态园2栋A座805 电话:19926409050

快速回复 返回顶部 返回列表