-
Notifications
You must be signed in to change notification settings - Fork 242
/
ParallelCriterion2.lua
43 lines (38 loc) · 1.44 KB
/
ParallelCriterion2.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
local ParallelCriterion2, parent = torch.class('nn.ParallelCriterion2', 'nn.Criterion')
function ParallelCriterion2:__init(repeatTarget)
parent.__init(self)
self.criterions = {}
self.weights = {}
self.gradInput = {}
self.repeatTarget = repeatTarget
end
function ParallelCriterion2:add(criterion, weight)
assert(criterion, 'no criterion provided')
weight = weight or 1
table.insert(self.criterions, criterion)
table.insert(self.weights, weight)
return self
end
function ParallelCriterion2:updateOutput(input, target)
self.output = 0
local output = {}
for i,criterion in ipairs(self.criterions) do
local target = self.repeatTarget and target or target[i]
self.output = self.output + self.weights[i]*criterion:updateOutput(input[i],target)
table.insert(output, self.weights[i]*criterion:updateOutput(input[i],target))
end
return self.output, output
end
function ParallelCriterion2:updateGradInput(input, target)
self.gradInput = nn.utils.recursiveResizeAs(self.gradInput, input)
nn.utils.recursiveFill(self.gradInput, 0)
for i,criterion in ipairs(self.criterions) do
local target = self.repeatTarget and target or target[i]
nn.utils.recursiveAdd(self.gradInput[i], self.weights[i], criterion:updateGradInput(input[i], target))
end
return self.gradInput
end
function ParallelCriterion2:type(type, tensorCache)
self.gradInput = {}
return parent.type(self, type, tensorCache)
end