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()
64 self:nestedApply(function(m) distance[m] = 1 end, self.inputModules)
69 for nnma, node in pairs(self.node) do
70 for _, nnmb in pairs(node.succ) do
71 if distance[nnma] and (not distance[nnmb] or distance[nnmb] < distance[nnma] + 1) then
72 distance[nnmb] = distance[nnma] + 1
80 for m, d in pairs(distance) do
81 table.insert(self.sorted, { distance = d, nnm = m })
84 table.sort(self.sorted, function(a, b) return a.distance < b.distance end)
86 for i, a in ipairs(self.sorted) do self.sorted[i] = a.nnm end
89 -- This accumulates x in a where they are both nested tables of
90 -- tensors. If first is true, set a = x. Behavior is undefined if a
91 -- and x do not have the exact same structure.
92 function DAG:nestedAccTensor(a, x, first)
93 if torch.type(x) == 'table' then
96 b[i] = self:nestedAccTensor(a[i], x[i], first)
102 a:resizeAs(x):copy(x)
113 function DAG:updateGradOutput(node)
114 local gradInputSucc = node.gradInputSucc
115 if #gradInputSucc == 1 then
116 node.gradOutput = gradInputSucc[1]
117 elseif #gradInputSucc > 1 then
118 for k = 1, #gradInputSucc do
119 node.gradOutput = self:nestedAccTensor(node.gradOutput, gradInputSucc[k], k == 1)
124 ----------------------------------------------------------------------
126 -- Connect a sequence of modules
127 function DAG:connect(...)
130 for _, nnm in pairs({...}) do
133 table.insert(self.node[nnm].pred, prev)
134 table.insert(self.node[prev].succ, nnm)
140 function DAG:setInput(i)
142 self.inputModules = i
145 if #self.node[nnm].succ == 0 then
146 error('Input modules must have outgoing edges.')
148 if #self.node[nnm].pred > 0 then
149 error('Input modules cannot have incoming edges.')
156 function DAG:setOutput(o)
158 self.outputModules = o
161 if #self.node[nnm].pred == 0 then
162 error('Output module must have incoming edges.')
164 if #self.node[nnm].succ > 0 then
165 error('Output module cannot have outgoing edges.')
175 for i, d in ipairs(self.sorted) do
176 print('#' .. i .. ' -> ' .. torch.type(d))
180 ----------------------------------------------------------------------
182 function DAG:saveDot(filename)
183 local file = (filename and io.open(filename, 'w')) or io.stdout
185 file:write('digraph {\n')
189 for nnmb, node in pairs(self.node) do
193 .. ' [shape=box,label=\"' .. torch.type(nnmb) .. '\"]'
197 for i, nnma in pairs(node.pred) do
198 local decoration = ''
199 if #node.pred > 1 then
200 -- decoration = ' [headlabel=\"' .. i .. '\"]'
201 decoration = ' [label=\"' .. i .. '\"]'
205 .. self.node[nnma].index
207 .. self.node[nnmb].index
220 ----------------------------------------------------------------------
222 function DAG:updateOutput(input)
227 local node = self.node[nnm]
229 self:rethrowErrors(nnm, node.index, 'updateOutput', i)
235 for _, nnm in ipairs(self.sorted) do
236 local node = self.node[nnm]
237 if #node.pred > 0 then
239 if #node.pred == 1 then
240 i = node.pred[1].output
241 elseif #node.pred > 1 then
243 for k = 1, #node.pred do
244 i[k] = node.pred[k].output
248 self:rethrowErrors(nnm, node.index, 'updateOutput', i)
252 self.output = self:nestedApply(
253 function(m) return m.output end,
260 function DAG:updateGradInput(input, gradOutput)
261 assert(self.sorted, 'There has been a DAG structure change before a DAG:updateGradInput')
265 local node = self.node[nnm]
267 self:rethrowErrors(nnm, node.index, 'updateGradInput', node.input, go)
269 self.outputModules, gradOutput
273 function(nnm, i) self.node[nnm].input = i end,
274 self.inputModules, input
277 for _, node in pairs(self.node) do
278 node.gradInputSucc = {}
281 for k = #self.sorted, 1, -1 do
282 local nnm = self.sorted[k]
283 local node = self.node[nnm]
284 local pred = node.pred
286 if #node.gradInputSucc > 0 then
287 self:updateGradOutput(node)
288 self:rethrowErrors(nnm, node.index, 'updateGradInput', node.input, node.gradOutput)
291 -- We fill the gradInputSucc of our predecessors
293 table.insert(self.node[pred[1]].gradInputSucc, nnm.gradInput)
294 elseif #pred > 1 then
295 if not torch.type(nnm.gradInput) == 'table' then
296 error('Should have a table gradInput since it has multiple predecessors')
299 table.insert(self.node[node.pred[n]].gradInputSucc, nnm.gradInput[n])
304 self.gradInput = self:nestedApply(function(m) return m.gradInput end, self.inputModules)
306 return self.gradInput
309 function DAG:accGradParameters(input, gradOutput, scale)
310 assert(self.sorted, 'There has been a DAG structure change before a DAG:accGradParameters')
313 function(nnm, go) self.node[nnm].gradOutput = go end,
314 self.outputModules, gradOutput
318 function(nnm, i) self.node[nnm].input = i end,
319 self.inputModules, input
322 for k = 1, #self.modules do
323 local nnm = self.modules[k]
324 local node = self.node[nnm]
325 self:rethrowErrors(nnm, k, 'accGradParameters', node.input, node.gradOutput, scale)
329 function DAG:clearState()
331 for _, node in pairs(self.node) do
332 node.gradInputSucc = nil
334 node.gradOutput = nil
336 return parent.clearState(self)