-
Notifications
You must be signed in to change notification settings - Fork 157
/
init.lua
382 lines (333 loc) · 11.8 KB
/
init.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
require 'cutorch'
require 'nn'
cudnn = require 'cudnn.env'
require('cudnn.ffi')
local C = cudnn.C
local ffi = require 'ffi'
local thc = ffi.C
if ffi.os == "Windows" then thc = ffi.load("THC") end
--------------------------------------------------------------------
-- defaults, each should be overrideable via env var:
--------------------------------------------------------------------
cudnn.benchmark = false
cudnn.fastest = false
-- use new cudnn FindEx APIs
-- Warning: this option is experimental and assumes at least 2 warmup iterations!
cudnn.useFindEx = false
-- amount of memory to use on 1st iteration for FindEx
cudnn.initialWorkspaceBytes = 1024
--
cudnn.reservedGPUBytes = 1024*1024
cudnn.maxWorkspaceGPUMemPercent = 95
local maxStreamsPerDevice = 1024
--------------------------------------------------------------------
-- end defaults
--------------------------------------------------------------------
local numDevices = cutorch.getDeviceCount()
-- this tensor keeps track of whether a handle has been initialized or not
local handleStatus = torch.ByteTensor(numDevices,
maxStreamsPerDevice):zero()
-- here we create an array of cudnn handle structs
cudnn.handle = ffi.new('struct cudnnContext*[?]', numDevices*maxStreamsPerDevice)
local function destroy(handle)
local currentDevice = cutorch.getDevice()
for i=1,numDevices do
cutorch.setDevice(i)
-- streams go from 0 to maxStreamsPerDevice - 1
for j=0,maxStreamsPerDevice - 1 do
if handleStatus[i][j + 1] == 1 then -- if handle was created
cudnn.errcheck('cudnnDestroy', handle[(((i-1)*maxStreamsPerDevice) + j)]);
end
end
end
cutorch.setDevice(currentDevice)
end
ffi.gc(cudnn.handle, destroy)
cudnn.typemap = {
['torch.CudaHalfTensor'] = 'CUDNN_DATA_HALF',
['torch.CudaTensor'] = 'CUDNN_DATA_FLOAT',
['torch.CudaDoubleTensor'] = 'CUDNN_DATA_DOUBLE',
}
local sizeofmap = {
['torch.CudaHalfTensor'] = cutorch.hasHalf and ffi.sizeof('half') or 2,
['torch.CudaTensor'] = ffi.sizeof('float'),
['torch.CudaDoubleTensor'] = ffi.sizeof('double'),
}
function cudnn.sizeof(t)
return sizeofmap[torch.type(t)]
end
local onemap = {
['torch.CudaHalfTensor'] = torch.FloatTensor({1}),
['torch.CudaTensor'] = torch.FloatTensor({1}),
['torch.CudaDoubleTensor'] = torch.DoubleTensor({1}),
}
local zeromap = {
['torch.CudaHalfTensor'] = torch.FloatTensor({0}),
['torch.CudaTensor'] = torch.FloatTensor({0}),
['torch.CudaDoubleTensor'] = torch.DoubleTensor({0}),
}
function cudnn.scalar(t, val)
if val == 1 then
return onemap[torch.type(t)]:data()
elseif val == 0 then
return zeromap[torch.type(t)]:data()
else
error('unknown scalar')
end
end
local function fasterHalfMathTypeForCurrentDevice()
-- get info from cutorc
if cutorch.hasFastHalfInstructions() then
return 'CUDNN_DATA_HALF'
else
return 'CUDNN_DATA_FLOAT'
end
end
local configMaths = {}
local function configureMath(overrides)
local currentDevice = cutorch.getDevice()
for i=1,cutorch.getDeviceCount() do
cutorch.setDevice(i)
configMaths[i] = {
['torch.CudaHalfTensor'] = fasterHalfMathTypeForCurrentDevice(),
['torch.CudaTensor'] = 'CUDNN_DATA_FLOAT',
['torch.CudaDoubleTensor'] = 'CUDNN_DATA_DOUBLE',
}
-- apply overrides
if overrides then
for k,v in pairs(overrides) do configMaths[i][k] = v end
end
end
cutorch.setDevice(currentDevice)
end
cudnn.configureMath = configureMath
-- TODO: rename to something like "configuredMathType" on next refactor
-- also, should move torch.type() inside
cudnn.configmap = function(tensortype)
return configMaths[cutorch.getDevice()][tensortype]
end
configureMath()
function cudnn.getHandle()
local device = cutorch.getDevice()
local stream = cutorch.getStream() -- starts from 0
assert(stream < maxStreamsPerDevice, 'cudnn bindings only support max of : '
.. maxStreamsPerDevice .. ' streams per device')
-- lazy initialization of handles
if handleStatus[device][stream + 1] == 0 then
local status = C['cudnnCreate'](cudnn.handle
+ (((device-1) * maxStreamsPerDevice)
+ stream))
if status ~= ffi.C.CUDNN_STATUS_SUCCESS then
local str = ffi.string(C.cudnnGetErrorString(status))
error('Error in CuDNN: ' .. str)
end
handleStatus[device][stream + 1] = 1 -- mark handle as initialized
end
return cudnn.handle[(((device-1)*maxStreamsPerDevice) + stream)]
end
function cudnn.call(f, ...)
C.cudnnSetStream(cudnn.getHandle(),
thc.THCState_getCurrentStream(cutorch.getState()))
return C[f](...)
end
local errcheck = function(f, ...)
local status = cudnn.call(f, ...)
if status ~= ffi.C.CUDNN_STATUS_SUCCESS then
local str = ffi.string(C.cudnnGetErrorString(status))
error('Error in CuDNN: ' .. str .. ' ('..f..')')
return false
end
return true
end
cudnn.errcheck = errcheck
function cudnn.toDescriptor(t)
local typename = torch.typename(t)
assert(cudnn.typemap[typename])
local descriptor = ffi.new('struct cudnnTensorStruct*[1]')
-- create descriptor
errcheck('cudnnCreateTensorDescriptor', descriptor)
-- set gc hook
local function destroy(d)
errcheck('cudnnDestroyTensorDescriptor', d[0]);
end
ffi.gc(descriptor, destroy)
-- view 2D and 3D as 4D
if t:dim() == 2 then
t = t:view(t:size(1), t:size(2), 1, 1)
elseif t:dim() == 3 then
t = t:view(t:size(1), t:size(2), t:size(3), 1)
end
-- set descriptor
local size = torch.LongTensor(t:size()):int()
local stride = torch.LongTensor(t:stride()):int()
errcheck('cudnnSetTensorNdDescriptor', descriptor[0], cudnn.typemap[typename],
t:dim(), size:data(), stride:data())
return descriptor
end
function cudnn.createDescriptors(count, descs_type, create_func, destroy_func)
local ds = ffi.new(descs_type, count)
for i = 0, count - 1 do
errcheck(create_func, ds + i)
end
local function destroyDescriptors(ds)
for i = 0, count - 1 do
errcheck(destroy_func, ds[i])
end
end
ffi.gc(ds, destroyDescriptors)
return ds
end
function cudnn.setConvolutionDescriptor(data, desc)
if not data.arrayLength then data.arrayLength = #data.padA end
if not data.upscaleA then data.upscaleA = torch.IntStorage(data.arrayLength):fill(1) end
if not data.mode then data.mode = 'CUDNN_CROSS_CORRELATION' end
local myDesc = desc or cudnn.createDescriptors(
1, 'struct cudnnConvolutionStruct*[?]',
'cudnnCreateConvolutionDescriptor', 'cudnnDestroyConvolutionDescriptor')
-- make sure we have references to these tensors so gc doesn't clean them up
local padATensor = torch.IntTensor(data.padA)
local filterStrideATensor = torch.IntTensor(data.filterStrideA)
local upscaleATensor = torch.IntTensor(data.upscaleA)
errcheck('cudnnSetConvolutionNdDescriptor', myDesc[0],
data.arrayLength,
padATensor:data(),
filterStrideATensor:data(),
upscaleATensor:data(),
data.mode,
data.dataType)
return myDesc
end
function cudnn.setFilterDescriptor(data, filterDesc)
local myDesc = filterDesc or cudnn.createDescriptors(
1, 'struct cudnnFilterStruct*[?]',
'cudnnCreateFilterDescriptor', 'cudnnDestroyFilterDescriptor')
local dims = data.nbDims or #data.filterDimA
-- make sure we have references to these tensors so gc doesn't clean them up
local filterDimATensor = torch.IntTensor(data.filterDimA)
errcheck('cudnnSetFilterNdDescriptor', myDesc[0],
data.dataType, data.format or 'CUDNN_TENSOR_NCHW',
dims, filterDimATensor:data());
return myDesc
end
local sharedBuffer = {}
local nextBufferSize = {}
-- may reassign currentSize
local function allocateStorage(buf, ifGreater)
if buf.nextSize < 0 then
buf.nextSize = buf.currentSize
end
local elSize = 8
-- get number of elements in the buf, rounded up
local newelem = math.floor((buf.nextSize+elSize-1)/elSize)
if buf.storage then
if (newelem == buf.storage:size()) or (ifGreater and newelem < buf.storage:size()) then
else
-- resize to just to make sure we return memory
buf.storage:resize(0)
buf.storage:resize(newelem)
end
else
-- this is to be replaced with new cutorch tempbuf stuff
-- may reassign currentSize again
buf.storage = torch.CudaDoubleStorage(newelem)
end
buf.currentSize = buf.storage:size()*elSize
buf.data = buf.storage:data()
buf.nextSize = -1
end
local function sharedBufForStream(device, stream)
device = device or cutorch.getDevice()
stream = stream or cutorch.getStream() -- starts from 0
if not sharedBuffer[device] then sharedBuffer[device] = {} end
local buf = sharedBuffer[device][stream]
if not buf then
buf = {
currentSize = cudnn.initialWorkspaceBytes,
nextSize = -1
}
allocateStorage(buf)
sharedBuffer[device][stream] = buf
end
return buf
end
function cudnn.getSharedWorkspace(device, stream)
device = device or cutorch.getDevice()
stream = stream or cutorch.getStream()
local buf = sharedBufForStream(device, stream)
return buf.data, buf.currentSize
end
-- Creates a clone of luaStr that can be used to prevent side
-- effects when passing char* to C functions.
function cudnn.externalizeString(luaStr)
local cStr = ffi.new("char[?]", #luaStr+1)
ffi.copy(cStr, luaStr)
return cStr
end
function cudnn.adjustSharedWorkspaceSize(bytesDelta, device, stream)
local buf = sharedBufForStream(device, stream)
buf.nextSize = buf.currentSize + bytesDelta
allocateStorage(buf)
end
function cudnn.setNextWorkspaceSize(bytes, device, stream)
local buf = sharedBufForStream(device, stream)
buf.nextSize = bytes
return buf
end
function cudnn.setSharedWorkspaceSize(bytes, ifGreater, device, stream)
bytes = bytes or cudnn.initialWorkspaceBytes
local buf = cudnn.setNextWorkspaceSize(bytes, device, stream)
allocateStorage(buf, ifGreater)
end
cudnn.find = require('cudnn.find')
require('cudnn.SpatialConvolution')
require('cudnn.VolumetricConvolution')
require('cudnn.SpatialFullConvolution')
require('cudnn.VolumetricFullConvolution')
require('cudnn.Pooling')
require('cudnn.SpatialMaxPooling')
require('cudnn.SpatialAveragePooling')
require('cudnn.Pooling3D')
require('cudnn.VolumetricMaxPooling')
require('cudnn.VolumetricAveragePooling')
require('cudnn.Pointwise')
require('cudnn.ReLU')
require('cudnn.ClippedReLU')
require('cudnn.Tanh')
require('cudnn.Sigmoid')
require('cudnn.SpatialSoftMax')
require('cudnn.SpatialLogSoftMax')
require('cudnn.VolumetricSoftMax')
require('cudnn.VolumetricLogSoftMax')
require('cudnn.SoftMax')
require('cudnn.LogSoftMax')
require('cudnn.SpatialCrossMapLRN')
require('cudnn.BatchNormalization')
require('cudnn.SpatialBatchNormalization')
require('cudnn.VolumetricBatchNormalization')
require('cudnn.SpatialCrossEntropyCriterion')
require('cudnn.VolumetricCrossEntropyCriterion')
require('cudnn.TemporalConvolution')
require('cudnn.RNN')
require('cudnn.RNNTanh')
require('cudnn.RNNReLU')
require('cudnn.BLSTM')
require('cudnn.LSTM')
require('cudnn.BGRU')
require('cudnn.GRU')
require('cudnn.functional')
require('cudnn.convert')
function cudnn.reset()
-- this resets everything
if cudnn.verbose then
print("cudnn::reset for device #", cutorch.getDevice())
end
cutorch.synchronize()
-- make sure shared buffers that may have been cached, have 0 size
for i=1,numDevices do
sharedBuffer[i] = {}
end
collectgarbage()
-- this resets internal algorithm finder state machine and cache
cudnn.find.reset()
end
return cudnn