initialization error when finetune a pretrained cnn with lstm-ctc
Environment info
Operating System: ubuntu 14.04
Compiler: gcc 4.8
Package used (Python/R/Scala/Julia): PYTHON
MXNet version: latest 0.9.1
MXNet commit hash (git rev-parse HEAD):6d05979cce53041f356204b17db2effb09371328
If you are using python package, please provide
Python version and distribution: anaconda 2.7.11
Error Message:
I want to use a pretrained cnn and bi-lstm-ctc to do ocr tasks, It works well if I do not use pretrained cnn. However if I use a pretraind cnn it will crash with initialization error, I do provide init_states for lstm in dataiter. this is the error :
Traceback (most recent call last):
File "pretrained_text_ocr.py", line 235, in <module>
allow_missing=True,
File "/home/onlyou/mxnet/python/mxnet/module/base_module.py", line 392, in fit
allow_missing=allow_missing, force_init=force_init)
File "/home/onlyou/mxnet/python/mxnet/module/module.py", line 261, in init_params
_impl(name, arr, arg_params)
File "/home/onlyou/mxnet/python/mxnet/module/module.py", line 256, in _impl
initializer(name, arr)
File "/home/onlyou/mxnet/python/mxnet/initializer.py", line 54, in __call__
self._init_default(name, arr)
File "/home/onlyou/mxnet/python/mxnet/initializer.py", line 92, in _init_default
raise ValueError('Unknown initialization pattern for %s' % name)
ValueError: Unknown initialization pattern for l1_init_h
this is the net :
def bi_lstm_unroll(seq_len, num_hidden, num_label,dropout=0):
last_states = []
last_states.append(LSTMState(c = mx.sym.Variable("l0_init_c"), h = mx.sym.Variable("l0_init_h")))
last_states.append(LSTMState(c = mx.sym.Variable("l1_init_c"), h = mx.sym.Variable("l1_init_h")))
forward_param = LSTMParam(i2h_weight=mx.sym.Variable("l0_i2h_weight"),
i2h_bias=mx.sym.Variable("l0_i2h_bias"),
h2h_weight=mx.sym.Variable("l0_h2h_weight"),
h2h_bias=mx.sym.Variable("l0_h2h_bias"))
backward_param = LSTMParam(i2h_weight=mx.sym.Variable("l1_i2h_weight"),
i2h_bias=mx.sym.Variable("l1_i2h_bias"),
h2h_weight=mx.sym.Variable("l1_h2h_weight"),
h2h_bias=mx.sym.Variable("l1_h2h_bias"))
assert(len(last_states) == 2)
# embeding layer
sym, arg_params, aux_params = mx.model.load_checkpoint('model/danzi3500_4conv', 35)
net=sym.get_internals()['pool2_output']
del arg_params['fullyconnected3_weight']
del arg_params['fullyconnected2_weight']
del arg_params['fullyconnected3_bias']
del arg_params['fullyconnected2_bias']
label = mx.sym.Variable('label')
column_features = mx.sym.SliceChannel(data=net, num_outputs=seq_len,axis=3, squeeze_axis=1)
hidden_all = []
forward_hidden = []
for seqidx in range(seq_len):
hidden =mx.sym.Flatten(data=column_features[seqidx])
if dropout > 0.:
hidden = mx.sym.Dropout(data=hidden, p=dropout)
next_state = lstm(num_hidden, indata=hidden,
prev_state=last_states[0],
param=forward_param,
seqidx=seqidx, layeridx=0)
hidden = next_state.h
last_states[0] = next_state
if dropout > 0.:
hidden = mx.sym.Dropout(data=hidden, p=dropout)
forward_hidden.append(hidden)
backward_hidden = []
for seqidx in range(seq_len):
k = seq_len - seqidx - 1
hidden =mx.sym.Flatten(data=column_features[k])
if dropout > 0.:
hidden = mx.sym.Dropout(data=hidden, p=dropout)
next_state = lstm(num_hidden, indata=hidden,
prev_state=last_states[1],
param=backward_param,
seqidx=k, layeridx=1)
hidden = next_state.h
last_states[1] = next_state
if dropout > 0.:
hidden = mx.sym.Dropout(data=hidden, p=dropout)
backward_hidden.insert(0, hidden)
hidden_all = []
for i in range(seq_len):
hidden_all.append(mx.sym.Concat(*[forward_hidden[i], backward_hidden[i]], dim=1))
hidden_concat = mx.sym.Concat(*hidden_all, dim=0)
pred = mx.sym.FullyConnected(data=hidden_concat, num_hidden=2369)
label = mx.sym.Reshape(data=label, shape=(-1,))
label = mx.sym.Cast(data = label, dtype = 'int32')
#does Warp-CTC support bucketing?
sm = mx.sym.WarpCTC(data=pred, label=label, label_length = num_label, input_length = seq_len)
return sm
Minimum reproducible example
this is my code: if name == 'main': num_hidden = 128 num_lstm_layer = 2 num_epoch = 100 learning_rate = 0.01 weight_decay=0 momentum = 0 num_label = 10 contexts = [mx.gpu(1)] def sym_gen(seq_len): return bi_lstm_unroll(seq_len, num_hidden=num_hidden, num_label = num_label,dropout=0.5) init_c = [('l%d_init_c'%l, (BATCH_SIZE, num_hidden)) for l in range(num_lstm_layer)] init_h = [('l%d_init_h'%l, (BATCH_SIZE, num_hidden)) for l in range(num_lstm_layer)] init_states = init_c + init_h path='text_train.lst' path_test='text_test.lst' data_root='NewCompany' buckets=[80] data_train=TextIter(path,data_root, BATCH_SIZE, init_states,num_label) data_train = mx.io.PrefetchingIter(data_train) data_val=TextIter(path_test, data_root, BATCH_SIZE,init_states,num_label) data_val = mx.io.PrefetchingIter(data_val) epoch_size=50110880.8/BATCH_SIZE lr_scheduler=mx.lr_scheduler.MultiFactorScheduler(step=[50epoch_size,80epoch_size], factor=0.1) if fixed_param_names: logger.info("Freezed parameters: [" + ','.join(fixed_param_names) + ']') sym = sym_gen(80) # init training module mod = mx.mod.Module(sym, label_names=('label',), logger=logger, context=contexts, fixed_param_names=fixed_param_names) optimizer_params={'learning_rate':learning_rate, 'momentum':momentum, 'wd':weight_decay, 'lr_scheduler':lr_scheduler, 'clip_gradient':None, 'rescale_grad': 1.0} mod.fit(data_train, eval_data=data_val, eval_metric=mx.metric.np(Accuracy), batch_end_callback=mx.callback.Speedometer(BATCH_SIZE, 50), optimizer='sgd', num_epoch=num_epoch, optimizer_params=optimizer_params, initializer=mx.init.Xavier(factor_type="in", magnitude=2.34), arg_params=arg_params, aux_params=aux_params, allow_missing=True, )
Steps to reproduce
1. 2. 3.
What have you tried to solve it?
- I can train this net just from scratch but meet init preblem when using pretrained cnn 2. 3.
How about making this change:
mod = mx.mod.Module(sym, label_names=('label', 'l1_init_h'),
@max0x thanks a lot! I change the line to
mod = mx.mod.Module(sym, label_names=('label','l1_init_h','l1_init_c','l0_init_c','l0_init_h')
It works, but this seems strange , maybe I'm too new to mxnet. The init states of lstm seems to be automatically initialized when training from scratch, but can't be initialized in this way when finetuning with pretrained cnn?
@xinghedyc could you close this issue if your original question has been answered? thanks
@sandeep-krishnamurthy Please close this issue for now.
@xinghedyc Please reopen this issue if you see it again or if this issue has been closed in error.