summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--nerv/examples/lmptb/m-tests/dagl_test.lua164
-rw-r--r--nerv/examples/lmptb/rnn/layer_tdag.lua291
2 files changed, 455 insertions, 0 deletions
diff --git a/nerv/examples/lmptb/m-tests/dagl_test.lua b/nerv/examples/lmptb/m-tests/dagl_test.lua
new file mode 100644
index 0000000..02e9c49
--- /dev/null
+++ b/nerv/examples/lmptb/m-tests/dagl_test.lua
@@ -0,0 +1,164 @@
+require 'lmptb.lmvocab'
+require 'lmptb.lmfeeder'
+require 'lmptb.lmutil'
+require 'lmptb.layer.init'
+require 'rnn.layer_tdag'
+
+--[[global function rename]]--
+printf = nerv.printf
+--[[global function rename ends]]--
+
+--global_conf: table
+--first_time: bool
+--Returns: a ParamRepo
+function prepare_parameters(global_conf, first_time)
+ printf("%s preparing parameters...\n", global_conf.sche_log_pre)
+
+ if (first_time) then
+ ltp_ih = nerv.LinearTransParam("ltp_ih", global_conf)
+ ltp_ih.trans = global_conf.cumat_type(global_conf.vocab:size() + 1, global_conf.hidden_size) --index 0 is for zero, others correspond to vocab index(starting from 1)
+ ltp_ih.trans:generate(global_conf.param_random)
+ ltp_ih.trans[0]:fill(0)
+
+ ltp_hh = nerv.LinearTransParam("ltp_hh", global_conf)
+ ltp_hh.trans = global_conf.cumat_type(global_conf.hidden_size, global_conf.hidden_size)
+ ltp_hh.trans:generate(global_conf.param_random)
+
+ ltp_ho = nerv.LinearTransParam("ltp_ho", global_conf)
+ ltp_ho.trans = global_conf.cumat_type(global_conf.hidden_size, global_conf.vocab:size())
+ ltp_ho.trans:generate(global_conf.param_random)
+
+ bp_h = nerv.BiasParam("bp_h", global_conf)
+ bp_h.trans = global_conf.cumat_type(1, global_conf.hidden_size)
+ bp_h.trans:generate(global_conf.param_random)
+
+ bp_o = nerv.BiasParam("bp_o", global_conf)
+ bp_o.trans = global_conf.cumat_type(1, global_conf.vocab:size())
+ bp_o.trans:generate(global_conf.param_random)
+
+ local f = nerv.ChunkFile(global_conf.param_fn, 'w')
+ f:write_chunk(ltp_ih)
+ f:write_chunk(ltp_hh)
+ f:write_chunk(ltp_ho)
+ f:write_chunk(bp_h)
+ f:write_chunk(bp_o)
+ f:close()
+ end
+
+ local paramRepo = nerv.ParamRepo()
+ paramRepo:import({global_conf.param_fn}, nil, global_conf)
+
+ printf("%s preparing parameters end.\n", global_conf.sche_log_pre)
+
+ return paramRepo
+end
+
+--global_conf: table
+--Returns: nerv.LayerRepo
+function prepare_layers(global_conf, paramRepo)
+ printf("%s preparing layers...\n", global_conf.sche_log_pre)
+
+ local recurrentLconfig = {{["bp"] = "bp_h", ["ltp_hh"] = "ltp_hh"}, {["dim_in"] = {global_conf.hidden_size, global_conf.hidden_size}, ["dim_out"] = {global_conf.hidden_size}, ["break_id"] = global_conf.vocab:get_sen_entry().id, ["independent"] = global_conf.independent, ["clip"] = 10}}
+
+ local layers = {
+ ["nerv.IndRecurrentLayer"] = {
+ ["recurrentL1"] = recurrentLconfig,
+ },
+
+ ["nerv.SelectLinearLayer"] = {
+ ["selectL1"] = {{["ltp"] = "ltp_ih"}, {["dim_in"] = {1}, ["dim_out"] = {global_conf.hidden_size}}},
+ },
+
+ ["nerv.SigmoidLayer"] = {
+ ["sigmoidL1"] = {{}, {["dim_in"] = {global_conf.hidden_size}, ["dim_out"] = {global_conf.hidden_size}}}
+ },
+
+ ["nerv.AffineLayer"] = {
+ ["outputL"] = {{["ltp"] = "ltp_ho", ["bp"] = "bp_o"}, {["dim_in"] = {global_conf.hidden_size}, ["dim_out"] = {global_conf.vocab:size()}}},
+ },
+
+ ["nerv.SoftmaxCELayer"] = {
+ ["softmaxL"] = {{}, {["dim_in"] = {global_conf.vocab:size(), global_conf.vocab:size()}, ["dim_out"] = {1}}},
+ },
+ }
+
+ --[[ --we do not need those in the new rnn framework
+ printf("%s adding %d bptt layers...\n", global_conf.sche_log_pre, global_conf.bptt)
+ for i = 1, global_conf.bptt do
+ layers["nerv.IndRecurrentLayer"]["recurrentL" .. (i + 1)] = recurrentLconfig
+ layers["nerv.SigmoidLayer"]["sigmoidL" .. (i + 1)] = {{}, {["dim_in"] = {global_conf.hidden_size}, ["dim_out"] = {global_conf.hidden_size}}}
+ layers["nerv.SelectLinearLayer"]["selectL" .. (i + 1)] = {{["ltp"] = "ltp_ih"}, {["dim_in"] = {1}, ["dim_out"] = {global_conf.hidden_size}}}
+ end
+ --]]
+
+ local layerRepo = nerv.LayerRepo(layers, paramRepo, global_conf)
+ printf("%s preparing layers end.\n", global_conf.sche_log_pre)
+ return layerRepo
+end
+
+--global_conf: table
+--layerRepo: nerv.LayerRepo
+--Returns: a nerv.DAGLayer
+function prepare_dagLayer(global_conf, layerRepo)
+ printf("%s Initing daglayer ...\n", global_conf.sche_log_pre)
+
+ --input: input_w, input_w, ... input_w_now, last_activation
+ local dim_in_t = {}
+ dim_in_t[1] = 1 --input to select_linear layer
+ dim_in_t[2] = global_conf.vocab:size() --input to softmax label
+ local connections_t = {
+ ["<input>[1]"] = "selectL1[1],0",
+ ["selectL1[1]"] = "recurrentL1[1],0",
+ ["recurrentL1[1]"] = "sigmoidL1[1],0",
+ ["sigmoidL1[1]"] = "outputL[1],0",
+ ["sigmoidL1[1]"] = "recurrentL1[2],1",
+ ["outputL[1]"] = "softmaxL[1],0",
+ ["<input>[2]"] = "softmaxL[2],0",
+ ["softmaxL[1]"] = "<output>[1],0"
+ }
+
+ --[[
+ printf("%s printing DAG connections:\n", global_conf.sche_log_pre)
+ for key, value in pairs(connections_t) do
+ printf("\t%s->%s\n", key, value)
+ end
+ ]]--
+
+ local dagL = nerv.TDAGLayer("dagL", global_conf, {["dim_in"] = dim_in_t, ["dim_out"] = {1}, ["sub_layers"] = layerRepo,
+ ["connections"] = connections_t,
+ })
+ dagL:init(global_conf.batch_size)
+ printf("%s Initing DAGLayer end.\n", global_conf.sche_log_pre)
+ return dagL
+end
+
+train_fn = '/home/slhome/txh18/workspace/nerv/nerv/nerv/examples/lmptb/m-tests/some-text'
+test_fn = '/home/slhome/txh18/workspace/nerv/nerv/nerv/examples/lmptb/m-tests/some-text'
+
+global_conf = {
+ lrate = 1, wcost = 1e-6, momentum = 0,
+ cumat_type = nerv.CuMatrixFloat,
+ mmat_type = nerv.CuMatrixFloat,
+
+ hidden_size = 20,
+ batch_size = 5,
+ seq_size = 3,
+ max_iter = 18,
+ param_random = function() return (math.random() / 5 - 0.1) end,
+ independent = true,
+
+ train_fn = train_fn,
+ test_fn = test_fn,
+ sche_log_pre = "[SCHEDULER]:",
+ log_w_num = 10, --give a message when log_w_num words have been processed
+ timer = nerv.Timer()
+}
+global_conf.work_dir = '/home/slhome/txh18/workspace/nerv/play/dagL_test'
+global_conf.param_fn = global_conf.work_dir.."/params"
+
+local vocab = nerv.LMVocab()
+global_conf["vocab"] = vocab
+global_conf.vocab:build_file(global_conf.train_fn, false)
+local paramRepo = prepare_parameters(global_conf, true)
+local layerRepo = prepare_layers(global_conf, paramRepo)
+local dagL = prepare_dagLayer(global_conf, layerRepo)
diff --git a/nerv/examples/lmptb/rnn/layer_tdag.lua b/nerv/examples/lmptb/rnn/layer_tdag.lua
new file mode 100644
index 0000000..296e2e6
--- /dev/null
+++ b/nerv/examples/lmptb/rnn/layer_tdag.lua
@@ -0,0 +1,291 @@
+local DAGLayer = nerv.class("nerv.TDAGLayer", "nerv.Layer")
+
+local function parse_id(str)
+ local id, port, time, _
+ _, _, id, port, time = string.find(str, "([a-zA-Z0-9_]+)%[([0-9]+)%][,]*([0-9]*)")
+ if id == nil or port == nil then
+ _, _, id, port, time = string.find(str, "(.+)%[([0-9]+)%][,]*([0-9]*)")
+ if not (id == "<input>" or id == "<output>") then
+ nerv.error("wrong format of connection id")
+ end
+ end
+ print(str, id, port, time)
+ port = tonumber(port)
+ if (time == nil) then
+ time = 0
+ else
+ time = tonumber(time)
+ end
+ return id, port, time
+end
+
+local function discover(id, layers, layer_repo)
+ local ref = layers[id]
+ if id == "<input>" or id == "<output>" then
+ return nil
+ end
+ if ref == nil then
+ local layer = layer_repo:get_layer(id)
+ local dim_in, dim_out = layer:get_dim()
+ ref = {
+ layer = layer,
+ inputs = {},
+ outputs = {},
+ err_inputs = {},
+ err_outputs = {},
+ next_layers = {},
+ input_len = #dim_in,
+ output_len = #dim_out,
+ in_deg = 0,
+ visited = false
+ }
+ layers[id] = ref
+ end
+ return ref
+end
+
+function DAGLayer:__init(id, global_conf, layer_conf)
+ local layers = {}
+ local inputs = {}
+ local outputs = {}
+ local dim_in = layer_conf.dim_in
+ local dim_out = layer_conf.dim_out
+ local parsed_conn = {}
+ local _
+ local time_to
+
+ for from, to in pairs(layer_conf.connections) do
+
+ local id_from, port_from, _ = parse_id(from)
+ local id_to, port_to, time_to = parse_id(to)
+
+ local ref_from = discover(id_from, layers, layer_conf.sub_layers)
+ local ref_to = discover(id_to, layers, layer_conf.sub_layers)
+
+ local input_dim, output_dim, _
+
+ if ref_from and ref_from.outputs[port_from] ~= nil then
+ nerv.error("%s has already been attached", from)
+ end
+ if ref_to and ref_to.inputs[port_to] ~= nil then
+ nerv.error("%s has already been attached", to)
+ end
+ if id_from == "<input>" then
+ input_dim, _ = ref_to.layer:get_dim()
+ if dim_in[port_from] ~= input_dim[port_to] then
+ nerv.error("mismatching data dimension between %s and %s", from, to)
+ end
+ inputs[port_from] = {ref_to, port_to}
+ ref_to.inputs[port_to] = inputs -- just a place holder
+ elseif id_to == "<output>" then
+ _, output_dim = ref_from.layer:get_dim()
+ if output_dim[port_from] ~= dim_out[port_to] then
+ nerv.error("mismatching data dimension between %s and %s", from, to)
+ end
+ outputs[port_to] = {ref_from, port_from}
+ ref_from.outputs[port_from] = outputs -- just a place holder
+ else
+ _, output_dim = ref_from.layer:get_dim()
+ input_dim, _ = ref_to.layer:get_dim()
+ if output_dim[port_from] ~= input_dim[port_to] then
+ nerv.error("mismatching data dimension between %s and %s", from, to)
+ end
+
+ table.insert(parsed_conn,
+ {{ref_from, port_from}, {ref_to, port_to}})
+ table.insert(ref_from.next_layers, ref_to) -- add edge
+ ref_to.in_deg = ref_to.in_deg + 1 -- increase the in-degree of the target layer
+ end
+ end
+
+ self.layers = layers
+ self.inputs = inputs
+ self.outputs = outputs
+ self.id = id
+ self.dim_in = dim_in
+ self.dim_out = dim_out
+ self.parsed_conn = parsed_conn
+ self.queue = queue
+ self.gconf = global_conf
+end
+
+function DAGLayer:init(batch_size)
+ for i, conn in ipairs(self.parsed_conn) do
+ local _, output_dim
+ local ref_from, port_from, ref_to, port_to
+ ref_from, port_from = unpack(conn[1])
+ ref_to, port_to = unpack(conn[2])
+ _, output_dim = ref_from.layer:get_dim()
+ local dim = 1
+ if output_dim[port_from] > 0 then
+ dim = output_dim[port_from]
+ end
+ local mid = self.gconf.cumat_type(batch_size, dim)
+ local err_mid = mid:create()
+
+ ref_from.outputs[port_from] = mid
+ ref_to.inputs[port_to] = mid
+
+ ref_from.err_inputs[port_from] = err_mid
+ ref_to.err_outputs[port_to] = err_mid
+ end
+ for id, ref in pairs(self.layers) do
+ for i = 1, ref.input_len do
+ if ref.inputs[i] == nil then
+ nerv.error("dangling input port %d of layer %s", i, id)
+ end
+ end
+ for i = 1, ref.output_len do
+ if ref.outputs[i] == nil then
+ nerv.error("dangling output port %d of layer %s", i, id)
+ end
+ end
+ -- initialize sub layers
+ ref.layer:init(batch_size)
+ end
+ for i = 1, #self.dim_in do
+ if self.inputs[i] == nil then
+ nerv.error("dangling port %d of layer <input>", i)
+ end
+ end
+ for i = 1, #self.dim_out do
+ if self.outputs[i] == nil then
+ nerv.error("dangling port %d of layer <output>", i)
+ end
+ end
+end
+
+function DAGLayer:batch_resize(batch_size)
+ self.gconf.batch_size = batch_size
+
+ for i, conn in ipairs(self.parsed_conn) do
+ local _, output_dim
+ local ref_from, port_from, ref_to, port_to
+ ref_from, port_from = unpack(conn[1])
+ ref_to, port_to = unpack(conn[2])
+ _, output_dim = ref_from.layer:get_dim()
+
+ if ref_from.outputs[port_from]:nrow() ~= batch_size and output_dim[port_from] > 0 then
+ local mid = self.gconf.cumat_type(batch_size, output_dim[port_from])
+ local err_mid = mid:create()
+
+ ref_from.outputs[port_from] = mid
+ ref_to.inputs[port_to] = mid
+
+ ref_from.err_inputs[port_from] = err_mid
+ ref_to.err_outputs[port_to] = err_mid
+ end
+ end
+ for id, ref in pairs(self.layers) do
+ ref.layer:batch_resize(batch_size)
+ end
+ collectgarbage("collect")
+end
+
+function DAGLayer:set_inputs(input)
+ for i = 1, #self.dim_in do
+ if input[i] == nil then
+ nerv.error("some input is not provided");
+ end
+ local layer = self.inputs[i][1]
+ local port = self.inputs[i][2]
+ layer.inputs[port] = input[i]
+ end
+end
+
+function DAGLayer:set_outputs(output)
+ for i = 1, #self.dim_out do
+ if output[i] == nil then
+ nerv.error("some output is not provided");
+ end
+ local layer = self.outputs[i][1]
+ local port = self.outputs[i][2]
+ layer.outputs[port] = output[i]
+ end
+end
+
+function DAGLayer:set_err_inputs(bp_err)
+ for i = 1, #self.dim_out do
+ local layer = self.outputs[i][1]
+ local port = self.outputs[i][2]
+ layer.err_inputs[port] = bp_err[i]
+ end
+end
+
+function DAGLayer:set_err_outputs(next_bp_err)
+ for i = 1, #self.dim_in do
+ local layer = self.inputs[i][1]
+ local port = self.inputs[i][2]
+ layer.err_outputs[port] = next_bp_err[i]
+ end
+end
+
+function DAGLayer:update(bp_err, input, output)
+ self:set_err_inputs(bp_err)
+ self:set_inputs(input)
+ self:set_outputs(output)
+ -- print("update")
+ for id, ref in pairs(self.queue) do
+ -- print(ref.layer.id)
+ ref.layer:update(ref.err_inputs, ref.inputs, ref.outputs)
+ end
+end
+
+function DAGLayer:propagate(input, output)
+ self:set_inputs(input)
+ self:set_outputs(output)
+ local ret = false
+ for i = 1, #self.queue do
+ local ref = self.queue[i]
+ -- print(ref.layer.id)
+ ret = ref.layer:propagate(ref.inputs, ref.outputs)
+ end
+ return ret
+end
+
+function DAGLayer:back_propagate(bp_err, next_bp_err, input, output)
+ self:set_err_outputs(next_bp_err)
+ self:set_err_inputs(bp_err)
+ self:set_inputs(input)
+ self:set_outputs(output)
+ for i = #self.queue, 1, -1 do
+ local ref = self.queue[i]
+ -- print(ref.layer.id)
+ ref.layer:back_propagate(ref.err_inputs, ref.err_outputs, ref.inputs, ref.outputs)
+ end
+end
+
+function DAGLayer:get_params()
+ local param_repos = {}
+ for id, ref in pairs(self.queue) do
+ table.insert(param_repos, ref.layer:get_params())
+ end
+ return nerv.ParamRepo.merge(param_repos)
+end
+
+DAGLayer.PORT_TYPES = {
+ INPUT = {},
+ OUTPUT = {},
+ ERR_INPUT = {},
+ ERR_OUTPUT = {}
+}
+
+function DAGLayer:get_intermediate(id, port_type)
+ if id == "<input>" or id == "<output>" then
+ nerv.error("an actual real layer id is expected")
+ end
+ local layer = self.layers[id]
+ if layer == nil then
+ nerv.error("layer id %s not found", id)
+ end
+ if port_type == DAGLayer.PORT_TYPES.INPUT then
+ return layer.inputs
+ elseif port_type == DAGLayer.PORT_TYPES.OUTPUT then
+ return layer.outputs
+ elseif port_type == DAGLayer.PORT_TYPES.ERR_INPUT then
+ return layer.err_inputs
+ elseif port_type == DAGLayer.PORT_TYPES.ERR_OUTPUT then
+ return layer.err_outputs
+ end
+ nerv.error("unrecognized port type")
+end