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:setLabel(nnm, label)
152 self.node[nnm].label = label
155 function DAG:setInput(i)
157 self.inputModules = i
160 assert(#self.node[nnm].succ > 0, 'Input modules must have outgoing edges.')
161 assert(#self.node[nnm].pred == 0, 'Input modules cannot have incoming edges.')
167 function DAG:setOutput(o)
169 self.outputModules = o
172 assert(#self.node[nnm].pred > 0, 'Output module must have incoming edges.')
173 assert(#self.node[nnm].succ == 0, 'Output module cannot have outgoing edges.')
182 for i, d in ipairs(self.sorted) do
183 local decoration = ''
184 if self.node[d].label then
185 decoration = ' [' .. self.node[d].label .. ']'
187 print('#' .. i .. ' -> ' .. torch.type(d) .. decoration)
191 ----------------------------------------------------------------------
193 function DAG:saveDot(filename)
194 local file = (filename and io.open(filename, 'w')) or io.stdout
196 local function writeNestedCluster(prefix, list, indent)
197 local indent = indent or ''
198 if torch.type(list) == 'table' then
199 file:write(indent .. ' subgraph cluster_' .. prefix .. ' {\n');
200 for k, x in pairs(list) do
201 writeNestedCluster(prefix .. '_' .. k, x, ' ' .. indent)
203 file:write(indent .. ' }\n');
205 file:write(indent .. ' ' .. self.node[list].index .. ' [color=red]\n')
209 file:write('digraph {\n')
213 writeNestedCluster('input', self.inputModules)
214 writeNestedCluster('output', self.outputModules)
218 for nnmb, node in pairs(self.node) do
222 .. ' [shape=box,label=\"' .. (self.node[nnmb].label or torch.type(nnmb)) .. '\"]'
226 for i, nnma in pairs(node.pred) do
227 local decoration = ''
228 if #node.pred > 1 then
229 -- decoration = ' [headlabel=\"' .. i .. '\"]'
230 decoration = ' [label=\"' .. i .. '\"]'
234 .. self.node[nnma].index
236 .. self.node[nnmb].index
249 ----------------------------------------------------------------------
251 function DAG:updateOutput(input)
256 local node = self.node[nnm]
258 self:rethrowErrors(nnm, node.index, 'updateOutput', i)
264 for _, nnm in ipairs(self.sorted) do
265 local node = self.node[nnm]
266 local pred = node.pred
271 elseif #pred > 1 then
274 i[k] = pred[k].output
278 self:rethrowErrors(nnm, node.index, 'updateOutput', i)
282 self.output = self:nestedApply(
283 function(m) return m.output end,
290 function DAG:updateGradInput(input, gradOutput)
291 assert(self.sorted, 'There has been a structure change before a DAG:updateGradInput')
295 local node = self.node[nnm]
297 self:rethrowErrors(nnm, node.index, 'updateGradInput', node.input, go)
299 self.outputModules, gradOutput
303 function(nnm, i) self.node[nnm].input = i end,
304 self.inputModules, input
307 for _, node in pairs(self.node) do
308 node.gradInputSucc = {}
311 for k = #self.sorted, 1, -1 do
312 local nnm = self.sorted[k]
313 local node = self.node[nnm]
314 local pred = node.pred
316 if #node.gradInputSucc > 0 then
317 self:updateGradOutput(node)
318 self:rethrowErrors(nnm, node.index, 'updateGradInput', node.input, node.gradOutput)
321 -- We fill the gradInputSucc of our predecessors
323 table.insert(self.node[pred[1]].gradInputSucc, nnm.gradInput)
324 elseif #pred > 1 then
325 assert(torch.type(nnm.gradInput) == 'table',
326 'Should have a table gradInput since it has multiple predecessors')
328 table.insert(self.node[pred[n]].gradInputSucc, nnm.gradInput[n])
333 self.gradInput = self:nestedApply(
334 function(m) return m.gradInput end,
338 return self.gradInput
341 function DAG:accGradParameters(input, gradOutput, scale)
342 assert(self.sorted, 'There has been a structure change before a DAG:accGradParameters')
345 function(nnm, go) self.node[nnm].gradOutput = go end,
346 self.outputModules, gradOutput
350 function(nnm, i) self.node[nnm].input = i end,
351 self.inputModules, input
354 for k = 1, #self.modules do
355 local nnm = self.modules[k]
356 local node = self.node[nnm]
357 self:rethrowErrors(nnm, k, 'accGradParameters', node.input, node.gradOutput, scale)
361 function DAG:clearState()
363 for _, node in pairs(self.node) do
365 node.gradInputSucc = nil
366 node.gradOutput = nil
368 return parent.clearState(self)