aboutsummaryrefslogtreecommitdiff
path: root/nerv/layer/combiner.lua
blob: 22e89a90239c3955cb129a8f560a58dc6123bc4a (plain) (blame)
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
local CombinerLayer = nerv.class('nerv.CombinerLayer', 'nerv.Layer')

function CombinerLayer:__init(id, global_conf, layer_conf)
    self.id = id
    self.lambda = layer_conf.lambda
    self.dim_in = layer_conf.dim_in
    self.dim_out = layer_conf.dim_out
    self.gconf = global_conf
    if self.gconf.use_cpu then
        self.mat_type = self.gconf.mmat_type
    else
        self.mat_type = self.gconf.cumat_type
    end
    self:check_dim_len(#self.lambda, -1)
    if #self.dim_in < 1 then
        nerv.error("no input specified")
    end
    if #self.dim_out < 1 then
        nerv.error("no output specified")
    end
end

function CombinerLayer:init(batch_size)
    local dim = self.dim_in[1]
    for i = 2, #self.dim_in do
        if self.dim_in[i] ~= dim then
            nerv.error("mismatching dimensions of inputs")
        end
    end
    for i = 1, #self.dim_out do
        if self.dim_out[i] ~= dim then
            nerv.error("mismatching dimensions of inputs/outputs")
        end
    end
    self.sum = self.mat_type(batch_size, dim)
end

function CombinerLayer:batch_resize(batch_size)
    if self.sum:nrow() ~= batch_size then
        self.sum = self.mat_type(batch_size, self.dim_in[1])
    end
end

function CombinerLayer:update(bp_err, input, output)
end

function CombinerLayer:propagate(input, output)
    output[1]:fill(0)
    for i = 1, #self.dim_in do
        output[1]:add(output[1], input[i], 1.0, self.lambda[i])
    end
    for i = 2, #self.dim_out do
        output[i]:copy_from(output[1])
    end
end

function CombinerLayer:back_propagate(bp_err, next_bp_err, input, output)
    local sum = self.sum
    sum:copy_from(bp_err[1])
    for i = 2, #self.dim_out do
        sum:add(sum, bp_err[i], 1.0, 1.0)
    end
    for i = 1, #self.dim_in do
        next_bp_err[i]:add(next_bp_err[i], sum, 0.0, self.lambda[i])
    end
end

function CombinerLayer:get_params()
    return nerv.ParamRepo({})
end