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) or (self.pred[m] and #self.pred[m] > 0) then
50 error('Invalid input edges.')
57 function DAG:setOutput(o)
59 self.outputModules = o
62 if (not self.pred[m] or #self.pred[m] == 0) or (self.succ[m] and #self.succ[m] > 0) then
63 error('Invalid output edges.')
77 self:applyOnModules(function(m) distance[m] = 1 end, self.inputModules)
83 for i, isucc in pairs(self.succ) do
84 for _, j in pairs(isucc) do
85 if distance[i] and (not distance[j] or distance[j] < distance[i] + 1) then
86 distance[j] = distance[i] + 1
94 for i, d in pairs(distance) do
95 table.insert(self.sorted, { d, i })
98 table.sort(self.sorted, function(a, b) return a[1] < b[1] end)
99 for i, a in ipairs(self.sorted) do self.sorted[i] = a[2] end
105 for i, d in ipairs(self.sorted) do
106 print('#' .. i .. ' -> ' .. torch.type(d))
110 function DAG:updateOutput(input)
113 self:applyOnModules(function(m, i) m:updateOutput(i) end, self.inputModules, input)
115 for _, d in ipairs(self.sorted) do
117 if #self.pred[d] == 1 then
118 d:updateOutput(self.pred[d][1].output)
119 elseif #self.pred[d] > 1 then
121 for k = 1, #self.pred[d] do
122 c[k] = self.pred[d][k].output
129 self.output = self:applyOnModules(function(m) return m.output end, self.outputModules)
134 function DAG:updateGradInput(input, gradOutput)
137 self:applyOnModules(function(m, i, go) m:updateGradInput(i, go) end, self.outputModules, input, gradOutput)
139 for k = self.sorted, 1, -1 do
142 if #self.succ[d] == 1 then
143 d:updateGradInput(self.succ[d][1].gradInput)
144 elseif #self.succ[d] > 1 then
146 for k = 1, #self.succ[d] do
148 sum:add(self.succ[d][k].gradInput)
150 sum = self.succ[d][k].gradInput:clone()
153 d:updateGradInput(sum)
158 self.gradInput = self:applyOnModules(function(m) return m.gradInput end, self.inputModules)
160 return self.gradInput