-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutils.lua
More file actions
71 lines (62 loc) · 1.89 KB
/
Copy pathutils.lua
File metadata and controls
71 lines (62 loc) · 1.89 KB
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
local utils = {}
function utils.cloneNetwork(net, T)
-- return T copies of the initial network net
-- sharing the parameters between the copies
local clones = {}
-- retrieve parameters
local params, gradParams
if net.parameters then
params, gradParams = net:parameters()
if params == nil then
params = {}
end
end
local paramsNoGrad
if net.parametersNoGrad then
paramsNoGrad = net:parametersNoGrad()
end
-- store the structure of the network
-- in a virtual file
local mem = torch.MemoryFile("w"):binary()
mem:writeObject(net)
-- copy
for t = 1, T do
-- We needo to use a new reader for each clone.
-- We don't want to use the pointers to already read objects.
local reader = torch.MemoryFile(mem:storage(), "r"):binary()
local clone = reader:readObject()
reader:close()
-- the clone parameters must point to the same
-- address locations as the original net parameters
if net.parameters then
local cloneParams, cloneGradParams = clone:parameters()
local cloneParamsNoGrad
for i=1,#params do
cloneParams[i]:set(params[i])
cloneGradParams[i]:set(gradParams[i])
end
if paramsNoGrad then
cloneParamsNoGrad = clone:parametersNoGrad()
for i=1,#paramsNoGrad do
cloneParamsNoGrad[i]:set(paramsNoGrad[i])
end
end
end
clones[t] = clone
collectgarbage()
end
mem:close()
return clones
end
function utils.randomFromArray(a)
local rand = torch.Tensor(1):uniform()
local cumSum = 0
for i=1,a:nElement() do
cumSum = cumSum + a[i]
if cumSum > rand[1] then
return i
end
end
return a:nElement()
end
return utils