In [1]:
require 'cutorch'
print( cutorch.getDeviceProperties(cutorch.getDevice()) )
-- 我们默认使用Float,单精度计算
torch.setdefaulttensortype('torch.FloatTensor')
Out[1]:
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
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 [ ]: