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

Matlab应用之GPU加速

[复制链接]

该用户从未签到

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

EDA365欢迎您登录!

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

x

7 i" z! g" a; T+ ~* \由于GPU近几年地迅速发展,GPU在多线程计算等方面逐渐超越CPU成为计算的主力军。而Matlab是常用的数学应用软件,现在讲解一下如何在Matlab中使用GPU加速计算% d4 X& Y1 g8 W6 y- I; F1 W
0 W0 S% u1 ~8 i4 ~. s
文章目录
& S. f0 A" v$ f# W1 l5 s9 X       0. 必要条件& L8 n0 X- k/ X) }- E9 R4 U
       1.给GPU传输数据. b7 N8 m8 c+ u% Q5 G  G* V
              1.1 CPU的数据复制到GPU
5 L- R4 t) k5 k  K2 i7 ], S8 r              1.2 直接在GPU上设置数据:
) }9 w7 z5 G6 t! D  t3 T       2.数据在GPU上运算
% `1 h) I( ?" f& `# x: v       3.GPU数据回传
$ }0 ~5 e1 ^" S       4.使用技巧
3 i1 E( `: ?( d" Y( x1 g* M              4.1 如果没有并行计算不建议使用GPU* c( R' ?: C" l  Z
              4.2 如果没有Nvidia显卡或者显卡驱动
, ?/ C. N* E7 N              4.3 双精度尽量转换为单精度
/ {* A$ ~* X" X" z/ d  `5 h& ]       附录
0 {% y" z/ ]/ m
7 G6 Q) x, s) ^# f' O' u5 }+ u  p  _: l: X$ p  A
, Y) w9 Q2 a8 ?2 x, R1 L1 Z9 o2 g
0. 必要条件! T; W/ a( M3 n' K& `, K( Z7 h/ p

+ B3 N1 b/ U& k  t* L+ V! j要想在Matlab中使用GPU加速有两个必须的条件
6 B) D6 f7 R5 _' y( p# i$ d  l4 h. A! q$ c3 d% a( j
  • 计算机上安装了NVIDIA显卡,目前AMD与Intel显示是暂不支持的;
  • 安装NVIDIA显卡驱动。
    $ A: ^) b, S6 r  _' D
3 u/ [- h$ g9 M  i
6 |% @- u5 e& ^% i; ?0 W
1.给GPU传输数据
+ B0 b; O1 _$ V, d0 W6 s7 I- K! i, s, y0 O  O
1.1 CPU的数据复制到GPU% R1 i1 E" k# o
/ t" K! d5 H8 K* A! y# F% S
在使用GPU计算的时候,只需要将CPU的数据复制到GPU中即可。
! r3 k8 N0 ]$ E6 f, k0 I- M" Q5 ], @8 n6 V( T  Z8 h
  • G = gpuArray(M);
    ( {' h8 l0 D1 c' v6 |: {6 V
( B7 }  T9 U0 v  G3 F; V/ o5 h
: B' W- ^6 j( [& z0 t
上边是对数据的名称做了修改,也可以直接进行重新赋值。
1 o0 J5 K9 n3 Q' L6 G: u2 D& y6 e* H) j2 `' T& w
  • M = gpuArray(M);, D. B6 L3 c" S& M4 ]

, T5 M7 L8 \5 v! O6 K" I
3 N3 {6 y# t( M1.2 直接在GPU上设置数据:
( g6 \/ h/ O8 y' O& @( [1 F/ r- ^" I4 B. f9 d
  • A = zeros(10, 'gpuArray');& R1 }& P! ~; l& e6 A) q7 I* i# }
  t& J/ D: m7 P6 O' T" e0 V2 G

# Q1 f8 Z% j' Z6 M( e- @6 ]可以对0矩阵以及1矩阵直接进行复制,但是在程序后边需要标注使用gpuArray。8 O$ E$ V" L  E/ Y4 Z$ N6 P  X: y
& u1 C8 N2 P. q2 G5 q  ~) u
  • r = gpuArray.rand(1, 100) % 一行,一百列
    - Z: h6 X9 Y! Z# `
( |/ P! C! |8 }0 j5 ]

% ^+ t4 L' p# G1 e2 e随机矩阵的产生。- h& e, ?0 K, ]5 Q" u
$ i# z1 c7 X2 D, K; {' A
2.数据在GPU上运算; b+ q1 M* m- e: Z. I: z
( V2 y9 R$ ~' R: v3 [
在GPU可以正常运行基本的运算,与正常矩阵计算方法相同! H! c- x: p. i1 r

8 F9 c5 i9 m" R( A) j& f4 P/ P
  • A=abs(A);
    2 k, S, c' s4 B
2 W" h$ j" k9 {3 k- N# X$ o8 A! ]

4 \4 b0 U; J; M+ {具体的可以运行的运算可以使用命令! `! u7 q( ~, h

% g; ~1 H8 s- |
  • methods(gpuArray)
      J2 J4 J0 i: O1 t

; B) Z. \) ]7 \  q
. l& h$ c. \( G/ J进行查看,Matlab可以在GPU运行的具体运算可以查看附录,附录中是Matlab给出的结果。% l1 e/ q8 X" `4 `8 ]& h+ R

; D& @& }3 I6 O) Q3.GPU数据回传
& |. w/ c0 s) Z" ]5 e9 s3 |6 i' g3 W" J7 J% m, C0 X: G/ d' z
  • B = gather (A);
    8 a: p: F* L* I+ V" D
$ I+ v, S! D3 O& N! Y# \

. u( z2 _; y$ y4 M直接使用上边的命令就能够将GPU中的数据回传给CPU。
% N- ?' v$ h4 q" I- ^' E# e! P/ @3 J
+ e' |, O3 x9 }4.使用技巧2 z) I9 @$ M8 p" _8 N+ \( T) Y2 c9 P
9 y0 u7 b+ ~, R& P5 E: ^$ `: u
4.1 如果没有并行计算不建议使用GPU: M- U# B, l8 R7 e4 k3 S) N$ b9 ^
4 G7 q- i4 |" y& F! O* [# l: q
  • index = 0;
  • index = gpuArray(index);
  • for i = 1 : 10000
  •     tic
  •     for j = 1 : 100000
  •         index = index + 1;
  •     end
  •     toc
  • end
  • disp(index)6 i2 T' ~; y1 s$ S- N) Y
* P2 K# H8 Z- B, O" m; r' s. O/ L
2 U2 _% G" ]! |: H' B. _' ~
通过上边程序第二行程序就可以在GPU上运行,注释掉就会在CPU上运行。在我的电脑上运行时间如下表所示。
# S) p5 _9 r! [/ u( m! z( m4 ^1 Y( V, ^# Q' s5 l6 q0 F
设备                 CPU                      GPU- ^5 M# a$ ?9 m# f  y* h' C
时间              0.00010 s            1.973017 s9 A. O' ^" n. J/ A, L

2 P% t, o$ k6 r6 n  W2 m由此可以看出,单个线程运行程序还是建议在CPU上运行,CPU的主频还是高一点,GPU主要是支持多个线程同时运行。
# Z0 ]8 L1 i- L6 ^3 k& _
# b; t* X+ N: e% ^6 I4.2 如果没有Nvidia显卡或者显卡驱动
3 _' q+ B8 s1 j* H5 c( H" |% l' G8 h- i" @
如果没有Nvidia显卡或者显卡驱动,会显示下边的提示。
/ U: ?3 n6 w7 ]; E# C! |' o) o5 Y1 e8 ?8 t0 X2 X2 t! I- ?6 y9 `( D
( _4 k  O) w' y  z- N* p" G- G

: _- D+ `2 f) _$ L: H  N" l4.3 双精度尽量转换为单精度
, M" \5 a$ l8 Y
' _/ s* Z' P( z- L. c" {在条件允许的情况下,尽量将计算过程中双精度转换为单精度。因为在GPU中单精度的计算速度明显优于双精度,在时间上会有很大的缩减。9 h  z, D5 I5 @$ B% T; |
附:单精度与上精度区别
/ n" u) V2 r# T+ J4 g8 V; p: }4 r  }
数据类型                    大小(字节)                     取值范围                  保留有效位数6 n7 D- a' c% X7 W; U% V9 P: X
单精度                   4个字节(32位)         3.4E-38~3.4E+38               7位  `- k5 b/ p6 Z) k% g3 G1 L- a7 ^2 p
双精度                   8个字节(64位)         1.7E-308~1.7E+308           16位) h2 O9 g$ [4 f$ S- V2 e) a0 W

3 ]9 ~" r+ n( p( I" ]: I+ R
/ Y) m3 k# q+ K; X) r% s附录
& c/ K6 J" j% j% A7 ~! [, _( S5 ~. L/ x3 v! ?
  • >> 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* W( o( T5 `% V+ w6 O1 e

- I6 e" s4 {& X8 E% F* y" M# |: `' v0 z- [7 K  t
5 q, P7 l* T$ v' [  o

该用户从未签到

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-23 22:50 , Processed in 0.171875 second(s), 26 queries , Gzip On.

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

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

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