aboutsummaryrefslogtreecommitdiff
path: root/nerv/nn/layer_repo.lua
blob: 647aac97b4db7e6c45b7aa503763927bac8c7e89 (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
local LayerRepo = nerv.class("nerv.LayerRepo")

function LayerRepo:__init(layer_spec, param_repo, global_conf)
    self.layers = {}
    self:add_layers(layer_spec, param_repo, global_conf)
end

function LayerRepo:add_layers(layer_spec, param_repo, global_conf)
    local layers = self.layers
    for ltype, llist in pairs(layer_spec) do
        local layer_type = nerv.get_type(ltype)
        if layer_type == nil then
            nerv.error('layer type `%s` not found', ltype)
        end
        for id, lconf in pairs(llist) do
            if type(lconf) ~= "table" then
                nerv.error("layer config table is need")
            end
            if lconf.pr == nil then
                lconf.pr = param_repo
            end
            if layers[id] ~= nil then
                nerv.error("a layer with id %s already exists", id)
            end
            nerv.info("create layer: %s", id)
            layers[id] = layer_type(id, global_conf, lconf)
        end
    end
end

function LayerRepo:rebind(param_repo)
    if self.__rebinding then
        return
    end
    self.__rebinding = true
    for _, layer in pairs(self.layers) do
        if not layer.__already_rebound then
            layer.__already_rebound = true
            layer.lconf.pr = param_repo
            layer:bind_params()
        end
    end
    for _, layer in pairs(self.layers) do
        layer.__already_rebound = false
    end
    self.__rebinding = false
end

function LayerRepo:get_layer(lid)
    local layer = self.layers[lid]
    if layer == nil then
        nerv.error("layer with id %s not found", lid)
    end
    return layer
end