Torch下的GPU支持

1. 支持GPU的张量库


In [1]:
require 'cutorch'
print(  cutorch.getDeviceProperties(cutorch.getDevice()) )

-- 我们默认使用Float,单精度计算
torch.setdefaulttensortype('torch.FloatTensor')


Out[1]:
{
  computeMode : 0
  memPitch : 2147483647
  canMapHostMemory : 1
  warpSize : 32
  pciDeviceID : 0
  pciBusID : 1
  totalConstMem : 65536
  pciDomainID : 0
  integrated : 0
  deviceOverlap : 1
  maxThreadsPerBlock : 1024
  clockRate : 1032500
  maxTexture1D : 65536
  minor : 0
  name : GeForce GTX 760
  freeGlobalMem : 2075398144
  maxTexture1DLinear : 134217728
  kernelExecTimeoutEnabled : 0
  sharedMemPerBlock : 49152
  major : 3
  totalGlobalMem : 2147287040
  regsPerBlock : 65536
  textureAlignment : 512
  multiProcessorCount : 6
}

Torch支持tensor在CPU/GPU各种的切换,cutorch支持在GPU环境下执行Tensor的各种操作。


In [2]:
-- 在GPU内进行计算
t1 = torch.CudaTensor(100):fill(0.5)
t2 = torch.CudaTensor(100):fill(1)
t1:add(t2)

-- GPU和CPU内存切换
t1_cpu = t1:float()
t1:zero()
t1[{}] = t1_cpu  -- copies the data back to the GPU, with no new alloc
t1_new = t1_cpu:cuda()  -- allocates a new tensor

2. 支持GPU执行环境的神经网络库

Torch包含一个GPU执行的神经网络库,这个库和Tensor库的GPU支持一样,接口与GPU版本一样。 同样神经网络模型支持CPU与GPU之间的无缝切换。


In [3]:
require 'cunn'

ninput = 32
noutput = 5
-- we define an MLP
mlp = nn.Sequential()
mlp:add(nn.Linear(ninput, 1000))
mlp:add(nn.Tanh())
mlp:add(nn.Linear(1000, 1000))
mlp:add(nn.Tanh())
mlp:add(nn.Linear(1000, 1000))
mlp:add(nn.Tanh())
mlp:add(nn.Linear(1000, noutput))
 
-- and move it to the GPU:
mlp:cuda()


input = torch.randn(ninput)
 
-- retype and feed to network:
result = mlp:forward( input:cuda() )
 
-- the result is a CudaTensor, if your loss is CPU-based, then you will
-- need to bring it back:
result_cpu = result:float()

In [ ]: