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 function DAG:setInput(i)
30 if torch.type(i) == 'table' then
32 for _, m in ipairs(i) do
33 if not self.pred[m] and not self.succ[m] then
42 function DAG:setOutput(o)
44 if torch.type(o) == 'table' then
45 self.outputModules = o
46 for _, m in ipairs(o) do
47 if not self.pred[m] and not self.succ[m] then
63 for _, a in pairs(self.inputModules) do
71 for i, isucc in pairs(self.succ) do
72 for _, j in pairs(isucc) do
73 if distance[i] and (not distance[j] or distance[j] < distance[i] + 1) then
74 distance[j] = distance[i] + 1
82 for i, d in pairs(distance) do
83 table.insert(self.sorted, { d, i })
86 table.sort(self.sorted, function(a, b) return a[1] < b[1] end)
87 for i, a in ipairs(self.sorted) do self.sorted[i] = a[2] end
93 for i, d in ipairs(self.sorted) do
94 print('#' .. i .. ' -> ' .. torch.type(d))
98 function DAG:updateOutput(input)
101 if #self.inputModules == 1 then
102 self.inputModules[1]:updateOutput(input)
104 for i, d in ipairs(self.inputModules) do
105 d:updateOutput(input[i])
109 for _, d in ipairs(self.sorted) do
111 if #self.pred[d] == 1 then
112 d:updateOutput(self.pred[d][1].output)
113 elseif #self.pred[d] > 1 then
115 for k = 1, #self.pred[d] do
116 c[k] = self.pred[d][k].output
123 if #self.outputModules == 1 then
124 self.output = self.outputModules[1].output
127 for i, d in ipairs(self.outputModules) do
128 self.output[i] = d.output
135 function DAG:updateGradInput(input, gradOutput)