Replaced torch.abs with math.abs.
[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(function(m) distance[m] = 1 end, self.inputModules)
65
66    local nc
67    repeat
68       nc = 0
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
73                nc = nc + 1
74             end
75          end
76       end
77    until nc == 0
78
79    self.sorted = {}
80    for m, d in pairs(distance) do
81       table.insert(self.sorted, { distance = d, nnm = m })
82    end
83
84    table.sort(self.sorted, function(a, b) return a.distance < b.distance end)
85
86    for i, a in ipairs(self.sorted) do self.sorted[i] = a.nnm end
87 end
88
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
94       local b = {}
95       for i in pairs(x) do
96          b[i] = self:nestedAccTensor(a[i], x[i], first)
97       end
98       a = b
99    else
100       if first then
101          if a then
102             a:resizeAs(x):copy(x)
103          else
104             a = x:clone()
105          end
106       else
107          a:add(x)
108       end
109    end
110    return a
111 end
112
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)
120       end
121    end
122 end
123
124 ----------------------------------------------------------------------
125
126 -- Connect a sequence of modules
127 function DAG:connect(...)
128    self.sorted = nil
129    local prev
130    for _, nnm in pairs({...}) do
131       self:createNode(nnm)
132       if prev then
133          table.insert(self.node[nnm].pred, prev)
134          table.insert(self.node[prev].succ, nnm)
135       end
136       prev = nnm
137    end
138 end
139
140 function DAG:setInput(i)
141    self.sorted = nil
142    self.inputModules = i
143    self:nestedApply(
144       function(nnm)
145          if #self.node[nnm].succ == 0 then
146             error('Input modules must have outgoing  edges.')
147          end
148          if #self.node[nnm].pred > 0 then
149             error('Input modules cannot have incoming edges.')
150          end
151       end,
152       self.inputModules
153    )
154 end
155
156 function DAG:setOutput(o)
157    self.sorted = nil
158    self.outputModules = o
159    self:nestedApply(
160       function(nnm)
161          if #self.node[nnm].pred == 0 then
162             error('Output module must have incoming edges.')
163          end
164          if #self.node[nnm].succ > 0 then
165             error('Output module cannot have outgoing edges.')
166          end
167       end,
168       self.outputModules
169    )
170 end
171
172 function DAG:print()
173    self:putInOrder()
174
175    for i, d in ipairs(self.sorted) do
176       print('#' .. i .. ' -> ' .. torch.type(d))
177    end
178 end
179
180 ----------------------------------------------------------------------
181
182 function DAG:saveDot(filename)
183    local file = (filename and io.open(filename, 'w')) or io.stdout
184
185    file:write('digraph {\n')
186
187    file:write('\n')
188
189    for nnmb, node in pairs(self.node) do
190       file:write(
191          '  '
192             .. node.index
193             .. ' [shape=box,label=\"' .. torch.type(nnmb) .. '\"]'
194             .. '\n'
195       )
196
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 .. '\"]'
202          end
203          file:write(
204             '  '
205                .. self.node[nnma].index
206                .. ' -> '
207                .. self.node[nnmb].index
208                .. decoration
209                .. '\n'
210          )
211       end
212
213       file:write('\n')
214    end
215
216    file:write('}\n')
217
218 end
219
220 ----------------------------------------------------------------------
221
222 function DAG:updateOutput(input)
223    self:putInOrder()
224
225    self:nestedApply(
226       function(nnm, i)
227          local node = self.node[nnm]
228          node.input = i
229          self:rethrowErrors(nnm, node.index, 'updateOutput', i)
230       end,
231       self.inputModules,
232       input
233    )
234
235    for _, nnm in ipairs(self.sorted) do
236       local node = self.node[nnm]
237       if #node.pred > 0 then
238          local i
239          if #node.pred == 1 then
240             i = node.pred[1].output
241          elseif #node.pred > 1 then
242             i = {}
243             for k = 1, #node.pred do
244                i[k] = node.pred[k].output
245             end
246          end
247          node.input = i
248          self:rethrowErrors(nnm, node.index, 'updateOutput', i)
249       end
250    end
251
252    self.output = self:nestedApply(
253       function(m) return m.output end,
254       self.outputModules
255    )
256
257    return self.output
258 end
259
260 function DAG:updateGradInput(input, gradOutput)
261    assert(self.sorted, 'There has been a DAG structure change before a DAG:updateGradInput')
262
263    self:nestedApply(
264       function(nnm, go)
265          local node = self.node[nnm]
266          node.gradOutput = go
267          self:rethrowErrors(nnm, node.index, 'updateGradInput', node.input, go)
268       end,
269       self.outputModules, gradOutput
270    )
271
272    self:nestedApply(
273       function(nnm, i) self.node[nnm].input = i end,
274       self.inputModules, input
275    )
276
277    for _, node in pairs(self.node) do
278       node.gradInputSucc = {}
279    end
280
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
285
286       if #node.gradInputSucc > 0 then
287          self:updateGradOutput(node)
288          self:rethrowErrors(nnm, node.index, 'updateGradInput', node.input, node.gradOutput)
289       end
290
291       -- We fill the gradInputSucc of our predecessors
292       if #pred == 1 then
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')
297          end
298          for n = 1, #pred do
299             table.insert(self.node[node.pred[n]].gradInputSucc, nnm.gradInput[n])
300          end
301       end
302    end
303
304    self.gradInput = self:nestedApply(function(m) return m.gradInput end, self.inputModules)
305
306    return self.gradInput
307 end
308
309 function DAG:accGradParameters(input, gradOutput, scale)
310    assert(self.sorted, 'There has been a DAG structure change before a DAG:accGradParameters')
311
312    self:nestedApply(
313       function(nnm, go) self.node[nnm].gradOutput = go end,
314       self.outputModules, gradOutput
315    )
316
317    self:nestedApply(
318       function(nnm, i) self.node[nnm].input = i end,
319       self.inputModules, input
320    )
321
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)
326    end
327 end
328
329 function DAG:clearState()
330    self.sorted = nil
331    for _, node in pairs(self.node) do
332       node.gradInputSucc = nil
333       node.input = nil
334       node.gradOutput = nil
335    end
336    return parent.clearState(self)
337 end