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

Matlab应用之GPU加速

[复制链接]

该用户从未签到

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

EDA365欢迎您登录!

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

x
* ]5 T& M5 Q0 }! s# m6 |
由于GPU近几年地迅速发展,GPU在多线程计算等方面逐渐超越CPU成为计算的主力军。而Matlab是常用的数学应用软件,现在讲解一下如何在Matlab中使用GPU加速计算! @8 f/ _, h# o6 e

3 N2 f6 K8 }% U5 u. z. v文章目录# ~. L$ a( @. M) }' h: f" _
       0. 必要条件
) M7 b$ [1 {# {* M* ?3 _1 ?& r       1.给GPU传输数据% P) I/ ?, x0 r* o% u
              1.1 CPU的数据复制到GPU
4 @$ e! ]1 {' C# c; n- V! Z! S/ R              1.2 直接在GPU上设置数据:
& r, ?0 ?& O/ A% F/ ^0 @       2.数据在GPU上运算
5 B, u; k$ C) Q% G' I       3.GPU数据回传
& i; H* y- |. V       4.使用技巧) [' m1 j0 l) F; E# m8 c
              4.1 如果没有并行计算不建议使用GPU4 L; ]  j  K8 E. x4 [, F/ C/ K
              4.2 如果没有Nvidia显卡或者显卡驱动- [+ @2 H  @. e" x- P. A( l0 A6 U
              4.3 双精度尽量转换为单精度9 J2 }0 L+ Q/ {8 i7 F( N; ^+ ^. W) M
       附录$ G5 B" n$ ^& C, A
# ]( W) [1 }4 y8 S% K) }4 X

% i- [, H& K. M8 `6 d
/ N: N7 N- q1 V/ }4 i" P( w0. 必要条件
0 O7 B4 C, }: G7 O1 `6 G- K* n. R( g* o" j- H( x# [  S9 V# t' t2 F
要想在Matlab中使用GPU加速有两个必须的条件
, f! X1 }( V+ [7 F, z( ?$ t- U! G4 c/ T/ H  o
  • 计算机上安装了NVIDIA显卡,目前AMD与Intel显示是暂不支持的;
  • 安装NVIDIA显卡驱动。
    6 a  R8 t9 B$ a

( R3 ?" @$ c* L0 ~- c3 _; ?2 |  c8 c; ~7 W3 n$ q
1.给GPU传输数据
7 x( a- C+ `9 A7 u. F; I# d  Y
1.1 CPU的数据复制到GPU
% p7 c# r" n7 P. }# l  W, k, M+ j
& V& w  @0 H/ m  w" |+ w) D  x9 e% }在使用GPU计算的时候,只需要将CPU的数据复制到GPU中即可。
$ ?0 p# m% B) q8 c0 J! m1 D2 k% x4 H7 v9 b
  • G = gpuArray(M);
    2 h" e5 @2 ^" F9 W5 x6 B6 x, E5 r
6 k2 g: r/ N/ a

( R& O. @+ h& J9 W上边是对数据的名称做了修改,也可以直接进行重新赋值。+ t8 x1 w2 }$ C) k  h4 W3 Z" N$ B

2 q; B& G/ k( ?) B0 m6 N# b% I
  • M = gpuArray(M);0 c, e$ L. A7 I( G

0 o3 v/ i+ `8 R
) `' R* E2 b  `  x1 H/ Z4 Z6 J1.2 直接在GPU上设置数据:$ a% a; s: l$ R4 ?

0 {0 ], D0 [) t" s9 Z6 c. b& K1 P7 g
  • A = zeros(10, 'gpuArray');: A/ n' A! x/ W+ f! G) a/ N6 r6 y4 D

( P# ~$ a2 s8 M" a; _/ j1 n( v
; L& g! U0 h0 l' ?* j9 p可以对0矩阵以及1矩阵直接进行复制,但是在程序后边需要标注使用gpuArray。! q1 g* Z5 J. H6 g  s4 W
* ]/ J2 @1 P( w
  • r = gpuArray.rand(1, 100) % 一行,一百列+ B+ X, F7 l1 ?1 x% L4 L- J) ]
4 I: u8 {3 q& E5 p/ ]$ ~
# e5 W# y2 M, n8 o; T  A
随机矩阵的产生。( |5 Q1 r3 c: c; g8 X; |; u

; v. b: J% T, h2 b/ e2.数据在GPU上运算
- ~2 y. u& e( O& X0 \3 v
; ^; G7 J, `; P在GPU可以正常运行基本的运算,与正常矩阵计算方法相同
9 c4 ~' y: H" c1 z- e0 T. ^) s% H- d8 Y! O6 N# t
  • A=abs(A);: \) y( F+ q" d" D1 O
/ ^* U! ^( g6 O9 E, E( P
, j$ k5 T+ H1 P
具体的可以运行的运算可以使用命令" I: l  o$ w! M/ m$ g3 u' {3 Z
5 d8 C0 |" m; T& t
  • methods(gpuArray)
    , ~$ i5 A8 n% [3 X1 A/ T6 K# B
- Q3 S2 t# E/ ~3 ]

0 a! ^$ U1 h& a) U4 J进行查看,Matlab可以在GPU运行的具体运算可以查看附录,附录中是Matlab给出的结果。
  S/ D1 {4 [+ N" f. v9 d, [& @+ x
+ g* \+ _  X" Y, `( E3.GPU数据回传& r( s$ z) S( ]+ \0 A2 M
) w4 L+ ^- Y7 g. u3 ?% c
  • B = gather (A);$ W8 C4 d( j7 |7 V1 H! r8 k1 K. s

1 F0 b1 B0 C4 P' X. X  s; e4 }8 o# Q
直接使用上边的命令就能够将GPU中的数据回传给CPU。; w; k$ I' g) R6 A/ z

! W& V" A: Y) L8 n3 X4.使用技巧; S6 O6 ^+ f7 B8 B
; @8 w5 b: ~7 s/ i( H
4.1 如果没有并行计算不建议使用GPU
0 F) u$ X1 M3 G, y* w0 i
2 v/ k" h9 Q2 J! y: \5 e
  • index = 0;
  • index = gpuArray(index);
  • for i = 1 : 10000
  •     tic
  •     for j = 1 : 100000
  •         index = index + 1;
  •     end
  •     toc
  • end
  • disp(index)
      T, o9 o" `' ~# p$ w
+ Z  l! r) I, c( t
2 K8 H8 V- }7 f2 ]' e9 j
通过上边程序第二行程序就可以在GPU上运行,注释掉就会在CPU上运行。在我的电脑上运行时间如下表所示。
5 X- l0 m; H: u7 X8 S' t/ |9 Q6 z! g
设备                 CPU                      GPU
# _5 O" R6 K# R. A时间              0.00010 s            1.973017 s8 Y' C/ z4 s) W) N3 \$ a. R7 w  q. f- T6 M
  \1 e2 [1 i: E
由此可以看出,单个线程运行程序还是建议在CPU上运行,CPU的主频还是高一点,GPU主要是支持多个线程同时运行。+ |4 ^8 ]8 q* q8 p* T" n( ^9 ]6 h
2 e9 }5 V. I7 N& n
4.2 如果没有Nvidia显卡或者显卡驱动
5 _3 q+ p* ^$ S4 n6 D8 O9 d+ [- P$ V6 p& I) D8 e# H: x
如果没有Nvidia显卡或者显卡驱动,会显示下边的提示。
! g4 u4 i: Q+ |+ X
0 P6 g3 z  v5 Q9 i- |2 d
$ R- }  ]/ k9 O7 Y- a- U2 o* O' X+ D0 ^5 J: S
4.3 双精度尽量转换为单精度4 U$ e: v- g$ q9 V3 T

; I& }! Q7 ~: s! ?6 v在条件允许的情况下,尽量将计算过程中双精度转换为单精度。因为在GPU中单精度的计算速度明显优于双精度,在时间上会有很大的缩减。
! h2 z; W+ n+ a) j  @1 W' c附:单精度与上精度区别6 {. E) x$ b% y3 l# S+ K( i
4 f0 U* P. M* p8 }6 h- R! W
数据类型                    大小(字节)                     取值范围                  保留有效位数
' {) I3 [8 e+ y) B: C5 Y, O& d( [; X单精度                   4个字节(32位)         3.4E-38~3.4E+38               7位2 n# x* J: d( V0 u) d" @
双精度                   8个字节(64位)         1.7E-308~1.7E+308           16位! O9 \% a# `; J. ?2 @$ J
+ L/ J  p3 y+ }' Y+ P
7 d0 c, y, O5 Z: i
附录
6 _* K; W- r- Z3 Z; h- I6 W' ^) P; D, [# w5 N. o' ?/ d
  • >> 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
    2 @7 O, L% E6 e0 g2 J: W5 ~
# q  A8 ^4 w3 K8 N1 f; m

/ o+ B3 O) M  v- D0 w/ Z
2 ~5 M- ~# J6 z. o# G

该用户从未签到

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-6-16 22:30 , Processed in 0.093750 second(s), 26 queries , Gzip On.

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

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

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