5 local DAG, parent = torch.class('nn.DAG', 'nn.Container')
13 function DAG:addEdge(a, b)
14 local pred, succ = self.pred, self.succ
15 if not pred[a] and not succ[a] then
18 if not pred[b] and not succ[b] then
21 pred[b] = pred[b] or {}
22 pred[b][#pred[b] + 1] = a
23 succ[a] = succ[a] or {}
24 succ[a][#succ[a] + 1] = b
27 function DAG:setInput(i)
28 if torch.type(i) == 'table' then
30 for _, m in ipairs(i) do
31 if not self.pred[m] and not self.succ[m] then
40 function DAG:setOutput(o)
41 if torch.type(o) == 'table' then
42 self.outputModules = o
43 for _, m in ipairs(o) do
44 if not self.pred[m] and not self.succ[m] then
56 for _, a in pairs(self.inputModules) do
64 for i, isucc in pairs(self.succ) do
65 for _, j in pairs(isucc) do
66 if distance[i] and (not distance[j] or distance[j] < distance[i] + 1) then
67 distance[j] = distance[i] + 1
75 for i, d in pairs(distance) do
76 table.insert(self.sorted, { d, i })
79 table.sort(self.sorted, function(a, b) return a[1] < b[1] end)
80 for i, a in ipairs(self.sorted) do self.sorted[i] = a[2] end
84 for i, d in ipairs(self.sorted) do
85 print('#' .. i .. ' -> ' .. torch.type(d))
89 function DAG:updateOutput(input)
90 if #self.inputModules == 1 then
91 self.inputModules[1]:updateOutput(input)
93 for i, d in ipairs(self.inputModules) do
94 d:updateOutput(input[i])
98 for _, d in ipairs(self.sorted) do
100 if #self.pred[d] == 1 then
101 d:updateOutput(self.pred[d][1].output)
102 elseif #self.pred[d] > 1 then
104 for k = 1, #self.pred[d] do
105 c[k] = self.pred[d][k].output
112 if #self.outputModules == 1 then
113 self.output = self.outputModules[1].output
116 for i, d in ipairs(self.outputModules) do
117 self.output[i] = d.output