5 local DAG, parent = torch.class('nn.DAG', 'nn.Container')
13 function DAG:addEdge(a, b)
15 local pred, succ = self.pred, self.succ
16 if not pred[a] and not succ[a] then
19 if not pred[b] and not succ[b] then
22 pred[b] = pred[b] or {}
23 pred[b][#pred[b] + 1] = a
24 succ[a] = succ[a] or {}
25 succ[a][#succ[a] + 1] = b
28 -- Apply f on t recursively; use the corresponding a1 and a2 elements
29 -- (i.e. same keys) as second and third parameters to f when
30 -- available; return the results from f, organized in a similarly
32 function DAG:applyOnModules(f, t, a1, a2)
33 if torch.type(t) == 'table' then
35 for k, s in pairs(t) do
36 result[k] = self:applyOnModules(f, s, a1 and a1[k], a2 and a2[k])
44 function DAG:setInput(i)
49 if not self.succ[m] or #self.succ[m] == 0 then
50 error('Input modules must have outgoing edges.')
52 if self.pred[m] and #self.pred[m] > 0 then
53 error('Input modules cannog have incoming edges.')
60 function DAG:setOutput(o)
62 self.outputModules = o
65 if not self.pred[m] or #self.pred[m] == 0 then
66 error('Output module must have incoming edges.')
68 if self.succ[m] and #self.succ[m] > 0 then
69 error('Output module cannot have outgoing edges.')
83 self:applyOnModules(function(m) distance[m] = 1 end, self.inputModules)
89 for i, isucc in pairs(self.succ) do
90 for _, j in pairs(isucc) do
91 if distance[i] and (not distance[j] or distance[j] < distance[i] + 1) then
92 distance[j] = distance[i] + 1
100 for i, d in pairs(distance) do
101 table.insert(self.sorted, { d, i })
104 table.sort(self.sorted, function(a, b) return a[1] < b[1] end)
105 for i, a in ipairs(self.sorted) do self.sorted[i] = a[2] end
111 for i, d in ipairs(self.sorted) do
112 print('#' .. i .. ' -> ' .. torch.type(d))
116 function DAG:updateOutput(input)
119 self:applyOnModules(function(m, i) m:updateOutput(i) end, self.inputModules, input)
121 for _, d in ipairs(self.sorted) do
123 if #self.pred[d] == 1 then
124 d:updateOutput(self.pred[d][1].output)
125 elseif #self.pred[d] > 1 then
127 for k = 1, #self.pred[d] do
128 c[k] = self.pred[d][k].output
135 self.output = self:applyOnModules(function(m) return m.output end, self.outputModules)
140 function DAG:updateGradInput(input, gradOutput)
144 function(m, i, go) m:updateGradInput(i, go) end,
145 self.outputModules, input, gradOutput
148 for k = self.sorted, 1, -1 do
151 if #self.succ[d] == 1 then
152 d:updateGradInput(self.succ[d][1].gradInput)
153 elseif #self.succ[d] > 1 then
155 for k = 1, #self.succ[d] do
157 sum:add(self.succ[d][k].gradInput)
159 sum = self.succ[d][k].gradInput:clone()
162 d:updateGradInput(sum)
167 self.gradInput = self:applyOnModules(function(m) return m.gradInput end, self.inputModules)
169 return self.gradInput