4 Copyright (c) 2016 Idiap Research Institute, http://www.idiap.ch/
5 Written by Francois Fleuret <francois.fleuret@idiap.ch>
7 This file is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License version 3 as
9 published by the Free Software Foundation.
11 It is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
14 License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this file. If not, see <http://www.gnu.org/licenses/>.
24 local DAG, parent = torch.class('nn.DAG', 'nn.Container')
28 -- Nodes are indexed by the module they contain
32 -- Apply f on t recursively; use the corresponding elements from args
33 -- (i.e. same keys) as second parameter to f when available; return
34 -- the results from f, organized in a similarly nested table.
35 function DAG:nestedApply(f, t, args)
36 if torch.type(t) == 'table' then
38 for k, s in pairs(t) do
39 result[k] = self:nestedApply(f, s, args and args[k])
47 function DAG:createNode(nnm)
48 if not self.node[nnm] then
49 self:add(nnm) -- Add it to the object as a Container
53 node.index = #self.modules
58 function DAG:putInOrder()
65 function(m) distance[m] = 1 end,
73 for nnma, node in pairs(self.node) do
74 for _, nnmb in pairs(node.succ) do
75 if distance[nnma] and (not distance[nnmb] or distance[nnmb] < distance[nnma] + 1) then
76 distance[nnmb] = distance[nnma] + 1
81 assert(nl < #self.modules, 'Cycle detected in the graph.')
85 for _, nnm in pairs(self.modules) do
86 assert(distance[nnm], 'Some modules are not connected to inputs')
90 for m, d in pairs(distance) do
91 table.insert(self.sorted, { distance = d, nnm = m })
94 table.sort(self.sorted, function(a, b) return a.distance < b.distance end)
96 for i, a in ipairs(self.sorted) do self.sorted[i] = a.nnm end
99 -- This accumulates x in a, where they are both nested tables of
100 -- tensors with same structures / keys. If first is true, set a = x
101 -- (in which case a can be nil) otherwise a = a + x. The behavior is
102 -- undefined if a and x do not have the exact same structure.
103 function DAG:nestedAccTensor(a, x, first)
104 if torch.type(x) == 'table' then
107 b[i] = self:nestedAccTensor(a[i], x[i], first)
113 a:resizeAs(x):copy(x)
124 function DAG:updateGradOutput(node)
125 local gradInputSucc = node.gradInputSucc
126 if #gradInputSucc == 1 then
127 node.gradOutput = gradInputSucc[1]
128 elseif #gradInputSucc > 1 then
129 for k = 1, #gradInputSucc do
130 node.gradOutput = self:nestedAccTensor(node.gradOutput, gradInputSucc[k], k == 1)
135 ----------------------------------------------------------------------
137 -- Connect a sequence of modules
138 function DAG:connect(...)
141 for _, nnm in pairs({...}) do
144 table.insert(self.node[nnm].pred, prev)
145 table.insert(self.node[prev].succ, nnm)
151 function DAG:setInput(i)
153 self.inputModules = i
156 assert(#self.node[nnm].succ > 0, 'Input modules must have outgoing edges.')
157 assert(#self.node[nnm].pred == 0, 'Input modules cannot have incoming edges.')
163 function DAG:setOutput(o)
165 self.outputModules = o
168 assert(#self.node[nnm].pred > 0, 'Output module must have incoming edges.')
169 assert(#self.node[nnm].succ == 0, 'Output module cannot have outgoing edges.')
178 for i, d in ipairs(self.sorted) do
179 print('#' .. i .. ' -> ' .. torch.type(d))
183 ----------------------------------------------------------------------
185 function DAG:saveDot(filename)
186 local file = (filename and io.open(filename, 'w')) or io.stdout
188 local function writeNestedCluster(prefix, list, indent)
189 local indent = indent or ''
190 if torch.type(list) == 'table' then
191 file:write(indent .. ' subgraph cluster_' .. prefix .. ' {\n');
192 for k, x in pairs(list) do
193 writeNestedCluster(prefix .. '_' .. k, x, ' ' .. indent)
195 file:write(indent .. ' }\n');
197 file:write(indent .. ' ' .. self.node[list].index .. ' [color=red]\n')
201 file:write('digraph {\n')
205 writeNestedCluster('input', self.inputModules)
206 writeNestedCluster('output', self.outputModules)
210 for nnmb, node in pairs(self.node) do
214 .. ' [shape=box,label=\"' .. torch.type(nnmb) .. '\"]'
218 for i, nnma in pairs(node.pred) do
219 local decoration = ''
220 if #node.pred > 1 then
221 -- decoration = ' [headlabel=\"' .. i .. '\"]'
222 decoration = ' [label=\"' .. i .. '\"]'
226 .. self.node[nnma].index
228 .. self.node[nnmb].index
241 ----------------------------------------------------------------------
243 function DAG:updateOutput(input)
248 local node = self.node[nnm]
250 self:rethrowErrors(nnm, node.index, 'updateOutput', i)
256 for _, nnm in ipairs(self.sorted) do
257 local node = self.node[nnm]
258 local pred = node.pred
263 elseif #pred > 1 then
266 i[k] = pred[k].output
270 self:rethrowErrors(nnm, node.index, 'updateOutput', i)
274 self.output = self:nestedApply(
275 function(m) return m.output end,
282 function DAG:updateGradInput(input, gradOutput)
283 assert(self.sorted, 'There has been a structure change before a DAG:updateGradInput')
287 local node = self.node[nnm]
289 self:rethrowErrors(nnm, node.index, 'updateGradInput', node.input, go)
291 self.outputModules, gradOutput
295 function(nnm, i) self.node[nnm].input = i end,
296 self.inputModules, input
299 for _, node in pairs(self.node) do
300 node.gradInputSucc = {}
303 for k = #self.sorted, 1, -1 do
304 local nnm = self.sorted[k]
305 local node = self.node[nnm]
306 local pred = node.pred
308 if #node.gradInputSucc > 0 then
309 self:updateGradOutput(node)
310 self:rethrowErrors(nnm, node.index, 'updateGradInput', node.input, node.gradOutput)
313 -- We fill the gradInputSucc of our predecessors
315 table.insert(self.node[pred[1]].gradInputSucc, nnm.gradInput)
316 elseif #pred > 1 then
317 assert(torch.type(nnm.gradInput) == 'table',
318 'Should have a table gradInput since it has multiple predecessors')
320 table.insert(self.node[pred[n]].gradInputSucc, nnm.gradInput[n])
325 self.gradInput = self:nestedApply(
326 function(m) return m.gradInput end,
330 return self.gradInput
333 function DAG:accGradParameters(input, gradOutput, scale)
334 assert(self.sorted, 'There has been a structure change before a DAG:accGradParameters')
337 function(nnm, go) self.node[nnm].gradOutput = go end,
338 self.outputModules, gradOutput
342 function(nnm, i) self.node[nnm].input = i end,
343 self.inputModules, input
346 for k = 1, #self.modules do
347 local nnm = self.modules[k]
348 local node = self.node[nnm]
349 self:rethrowErrors(nnm, k, 'accGradParameters', node.input, node.gradOutput, scale)
353 function DAG:clearState()
355 for _, node in pairs(self.node) do
357 node.gradInputSucc = nil
358 node.gradOutput = nil
360 return parent.clearState(self)