Added the detection of cycles + cosmetics.
[dagnn.git] / dagnn.lua
1
2 --[[
3
4    Copyright (c) 2016 Idiap Research Institute, http://www.idiap.ch/
5    Written by Francois Fleuret <francois.fleuret@idiap.ch>
6
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.
10
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.
15
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/>.
18
19 ]]--
20
21 require 'torch'
22 require 'nn'
23
24 local DAG, parent = torch.class('nn.DAG', 'nn.Container')
25
26 function DAG:__init()
27    parent.__init(self)
28    -- Nodes are indexed by the module they contain
29    self.node = {}
30 end
31
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
37       local result = {}
38       for k, s in pairs(t) do
39          result[k] = self:nestedApply(f, s, args and args[k])
40       end
41       return result
42    else
43       return f(t, args)
44    end
45 end
46
47 function DAG:createNode(nnm)
48    if not self.node[nnm] then
49       self:add(nnm) -- Add it to the object as a Container
50       local node = {}
51       node.succ = {}
52       node.pred = {}
53       node.index = #self.modules
54       self.node[nnm] = node
55    end
56 end
57
58 function DAG:putInOrder()
59    if self.sorted then
60       return
61    end
62
63    local distance = {}
64    self:nestedApply(
65       function(m) distance[m] = 1 end,
66       self.inputModules
67    )
68
69    local nc
70    local nl = 0
71    repeat
72       nc = 0
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
77                nc = nc + 1
78             end
79          end
80       end
81       assert(nl < #self.modules, 'Cycle detected in the graph.')
82       nl = nl + 1
83    until nc == 0
84
85    for _, nnm in pairs(self.modules) do
86       assert(distance[nnm], 'Some modules are not connected to inputs')
87    end
88
89    self.sorted = {}
90    for m, d in pairs(distance) do
91       table.insert(self.sorted, { distance = d, nnm = m })
92    end
93
94    table.sort(self.sorted, function(a, b) return a.distance < b.distance end)
95
96    for i, a in ipairs(self.sorted) do self.sorted[i] = a.nnm end
97 end
98
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
105       local b = {}
106       for i in pairs(x) do
107          b[i] = self:nestedAccTensor(a[i], x[i], first)
108       end
109       a = b
110    else
111       if first then
112          if a then
113             a:resizeAs(x):copy(x)
114          else
115             a = x:clone()
116          end
117       else
118          a:add(x)
119       end
120    end
121    return a
122 end
123
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)
131       end
132    end
133 end
134
135 ----------------------------------------------------------------------
136
137 -- Connect a sequence of modules
138 function DAG:connect(...)
139    self.sorted = nil
140    local prev
141    for _, nnm in pairs({...}) do
142       self:createNode(nnm)
143       if prev then
144          table.insert(self.node[nnm].pred, prev)
145          table.insert(self.node[prev].succ, nnm)
146       end
147       prev = nnm
148    end
149 end
150
151 function DAG:setInput(i)
152    self.sorted = nil
153    self.inputModules = i
154    self:nestedApply(
155       function(nnm)
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.')
158       end,
159       self.inputModules
160    )
161 end
162
163 function DAG:setOutput(o)
164    self.sorted = nil
165    self.outputModules = o
166    self:nestedApply(
167       function(nnm)
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.')
170       end,
171       self.outputModules
172    )
173 end
174
175 function DAG:print()
176    self:putInOrder()
177
178    for i, d in ipairs(self.sorted) do
179       print('#' .. i .. ' -> ' .. torch.type(d))
180    end
181 end
182
183 ----------------------------------------------------------------------
184
185 function DAG:saveDot(filename)
186    local file = (filename and io.open(filename, 'w')) or io.stdout
187
188    file:write('digraph {\n')
189
190    file:write('\n')
191
192    for nnmb, node in pairs(self.node) do
193       file:write(
194          '  '
195             .. node.index
196             .. ' [shape=box,label=\"' .. torch.type(nnmb) .. '\"]'
197             .. '\n'
198       )
199
200       for i, nnma in pairs(node.pred) do
201          local decoration = ''
202          if #node.pred > 1 then
203             -- decoration = ' [headlabel=\"' .. i .. '\"]'
204             decoration = ' [label=\"' .. i .. '\"]'
205          end
206          file:write(
207             '  '
208                .. self.node[nnma].index
209                .. ' -> '
210                .. self.node[nnmb].index
211                .. decoration
212                .. '\n'
213          )
214       end
215
216       file:write('\n')
217    end
218
219    file:write('}\n')
220
221 end
222
223 ----------------------------------------------------------------------
224
225 function DAG:updateOutput(input)
226    self:putInOrder()
227
228    self:nestedApply(
229       function(nnm, i)
230          local node = self.node[nnm]
231          node.input = i
232          self:rethrowErrors(nnm, node.index, 'updateOutput', i)
233       end,
234       self.inputModules,
235       input
236    )
237
238    for _, nnm in ipairs(self.sorted) do
239       local node = self.node[nnm]
240       local pred = node.pred
241       if #pred > 0 then
242          local i
243          if #pred == 1 then
244             i = pred[1].output
245          elseif #pred > 1 then
246             i = {}
247             for k = 1, #pred do
248                i[k] = pred[k].output
249             end
250          end
251          node.input = i
252          self:rethrowErrors(nnm, node.index, 'updateOutput', i)
253       end
254    end
255
256    self.output = self:nestedApply(
257       function(m) return m.output end,
258       self.outputModules
259    )
260
261    return self.output
262 end
263
264 function DAG:updateGradInput(input, gradOutput)
265    assert(self.sorted, 'There has been a structure change before a DAG:updateGradInput')
266
267    self:nestedApply(
268       function(nnm, go)
269          local node = self.node[nnm]
270          node.gradOutput = go
271          self:rethrowErrors(nnm, node.index, 'updateGradInput', node.input, go)
272       end,
273       self.outputModules, gradOutput
274    )
275
276    self:nestedApply(
277       function(nnm, i) self.node[nnm].input = i end,
278       self.inputModules, input
279    )
280
281    for _, node in pairs(self.node) do
282       node.gradInputSucc = {}
283    end
284
285    for k = #self.sorted, 1, -1 do
286       local nnm = self.sorted[k]
287       local node = self.node[nnm]
288       local pred = node.pred
289
290       if #node.gradInputSucc > 0 then
291          self:updateGradOutput(node)
292          self:rethrowErrors(nnm, node.index, 'updateGradInput', node.input, node.gradOutput)
293       end
294
295       -- We fill the gradInputSucc of our predecessors
296       if #pred == 1 then
297          table.insert(self.node[pred[1]].gradInputSucc, nnm.gradInput)
298       elseif #pred > 1 then
299          assert(torch.type(nnm.gradInput) == 'table',
300                 'Should have a table gradInput since it has multiple predecessors')
301          for n = 1, #pred do
302             table.insert(self.node[pred[n]].gradInputSucc, nnm.gradInput[n])
303          end
304       end
305    end
306
307    self.gradInput = self:nestedApply(
308       function(m) return m.gradInput end,
309       self.inputModules
310    )
311
312    return self.gradInput
313 end
314
315 function DAG:accGradParameters(input, gradOutput, scale)
316    assert(self.sorted, 'There has been a structure change before a DAG:accGradParameters')
317
318    self:nestedApply(
319       function(nnm, go) self.node[nnm].gradOutput = go end,
320       self.outputModules, gradOutput
321    )
322
323    self:nestedApply(
324       function(nnm, i) self.node[nnm].input = i end,
325       self.inputModules, input
326    )
327
328    for k = 1, #self.modules do
329       local nnm = self.modules[k]
330       local node = self.node[nnm]
331       self:rethrowErrors(nnm, k, 'accGradParameters', node.input, node.gradOutput, scale)
332    end
333 end
334
335 function DAG:clearState()
336    self.sorted = nil
337    for _, node in pairs(self.node) do
338       node.input = nil
339       node.gradInputSucc = nil
340       node.gradOutput = nil
341    end
342    return parent.clearState(self)
343 end