mxnet icon indicating copy to clipboard operation
mxnet copied to clipboard

override global initialization method in layer configuration

Open Lopezurrutia opened this issue 10 years ago • 13 comments

I am trying to convert to mxnet the cxxnet network configuration in: https://github.com/auroraxie/Kaggle-NDSB/blob/master/models/model1/bn.conf

layer[0->1] = conv kernel_size = 3 stride = 1 nchannel = 32 pad = 1 random_type = gaussian init_sigma = 0.03

In cxxnet it is possible to override the global initilization method in the layer configuration (as detailed in: https://github.com/dmlc/cxxnet/blob/master/doc/layer.md). Is this possible in mxnet? I could not find any documentation. Thanks

Lopezurrutia avatar Jan 25 '16 15:01 Lopezurrutia

Use mx.init.Mixed

piiswrong avatar Jan 25 '16 20:01 piiswrong

Thanks. I've reading (again and again) the doc at http://mxnet.readthedocs.org/en/latest/python/model.html#mxnet.initializer.Mixed but I can not figure out how to use it. A toy example would be very welcomed.

Lopezurrutia avatar Jan 25 '16 21:01 Lopezurrutia

I don't have an example at hand. If you can't understand the doc, try reading the code in mxnet/initializer.py:Mixed

piiswrong avatar Jan 26 '16 23:01 piiswrong

I just read the code in initializer.py. And it makes no sense to me that the base Initializer class would process 'bias', 'gamma', 'weights' etc one by one. It's a ridiculous design.

An initializer should be responsible for initializing one and any one variable. And it's users responsibility to determine which variable this initializer will init.

With the current design, the Uniform initializer should be called UniformWeight because it can't be used on bias or any other variables. And users will have to write another 'UniformBias' initializer if they need, which has almost duplicated code.

Apart from code reusability, maintainer will have to add a new line in Initializer whenever there is a new variable defined in some new layer, to provide a default initialization behavior.

Tensorflow, for example, does a better job where you can specify how to initialize the variable at variable definition time. In this way default initialization can then be built into layers.

BTW @Gelu74 there is a bug in mx.init.Mixed which affects python3. If you use python3, you might want to wait for #1361 to be merged.

ppwwyyxx avatar Jan 26 '16 23:01 ppwwyyxx

@ppwwyyxx The problem with building init into layers is that you'll have to write init code in C++ and it becomes harder to write and change. If init stays in the front end, your solution basically means the default initializer is a Mixed initializer that dispatch based on name. It's mostly the same deal.

piiswrong avatar Jan 27 '16 01:01 piiswrong

By 'bulit into layers' I didn't mean built into operators. I'm assuming there is a layer-like abstraction such as the ConvFactory in imagenet examples. And if initialization method of a variable can be given in variable definition time (like in TensorFlow), a layer abstraction will then be able to provide default initialization. But I guess this will introduce too many changes to the current system. Sorry that I might be unclear about the opinion. I think there are two issues with the current design that are worth a discussion:

  • The initializers in the code right now are parameter-specific: Uniform is actually UniformWeight initializer. The alternative is to have an initializer available to use with any parameters, and let users choose explicitly, for example, like:
mx.init.Mixed(['.*_weight', '.*'], [mx.init.Uniform(),SomeDefaultInitializer()])

The advantage is to have reusable code for the implementation of initializer, especially when parameters with new names are created.

  • The author of a layer abstraction (such as ConvFactory) cannot suggest its users a default initializer. Therefore if a new layer abstraction, or simply some new parameters in the graph with un-recognized names are created, either the source code of Initializer base class has to be modified to recognize the name and perform default initializer, or a user must explicitly give this default initilaizer through mx.init.Mixed before he starts training. I think neither of "maintaining a list of names in the source code" or "having users to write code to get default behavior", is a good idea.

Thanks

ppwwyyxx avatar Jan 27 '16 02:01 ppwwyyxx

I don't like the current name based approach either but it hasn't caused enough trouble to compel action. If you have concrete thoughts you are welcome to propose a PR and we can have more discussion.

I suggest starting with breaking down base Initializer class into separate "pure" initializers and refactor specialized initializers to be subclass of Mixed Initializer. Building init into layer abstraction is harder because layers are registered in C++. The corresponding python code is automatically generated. So it's hard to do layer specific things in the front end. It might be possible to use symbol attributes for this.

piiswrong avatar Jan 27 '16 03:01 piiswrong

OK, After reading the source I think I understand. I'll write a sort summary here for the records (in case there is someone as dumb as me..) and to get corrected if I am wrong before I close the issue.

Say you want to use a default initializer: default_initilializer = mx.init.Xavier(rnd_type="uniform", factor_type="in", magnitude=2.34)

for all your layers except for one, the layer defined as:

conv1 = mx.symbol.Convolution(
        data=input_data, kernel=(3, 3), stride=(1, 1), num_filter=32,pad=(1,1),name="overriden")

* note that this layer has as name "overriden" and this we will used to do the regular expression pattern match in mx.init.Mixed*

For this layer you want to use a initializer of the form:

override_initializer = mx.init.Normal(sigma=0.03)

Then the final initializer to train the model should be: mx.init.Mixed( patterns=[ 'overriden' , '.*' ] , initializers = [override_initializer , default_initilializer ] )

This will initialize all layers with the default_initializer, except those that have "overriden" in the name that will be initialized with the override_initializer. `

Lopezurrutia avatar Jan 29 '16 19:01 Lopezurrutia

init = mx.initializer.Mixed(['bias', '.*'], [mx.init.Zero(), mx.init.Xavier(magnitude=2.24)])
net.collect_params().initialize(init, ctx=ctx)

It seems that Mixed type is different from those normal ones. The code above will return error 'initializer must be of string type' But if init = mx.init.Xavier(magnitude=2.24), it will be Okay~

Jing-Luo avatar Nov 08 '17 09:11 Jing-Luo

Good afternoon everyone, i'm trying to use mx.iter.Load('parameters...', mx.init.Normal(),True) to load some weights from file and to initialize othr weights normally, but i get error : AssertionError: initializer must be of string type. I have log: Traceback (most recent call last): File "/home/alex/Desktop/MySegment/executor.py", line 283, in preds = [model(X) for X in dlist] File "/home/alex/anaconda3/envs/py27/lib/python2.7/site-packages/mxnet/gluon/block.py", line 304, in call return self.forward(*args) File "/home/alex/anaconda3/envs/py27/lib/python2.7/site-packages/mxnet/gluon/block.py", line 607, in forward self._finish_deferred_init(True, x, *args) File "/home/alex/anaconda3/envs/py27/lib/python2.7/site-packages/mxnet/gluon/block.py", line 407, in _finish_deferred_init i._finish_deferred_init() File "/home/alex/anaconda3/envs/py27/lib/python2.7/site-packages/mxnet/gluon/parameter.py", line 239, in _finish_deferred_init initializer.create(default_init)( File "/home/alex/anaconda3/envs/py27/lib/python2.7/site-packages/mxnet/registry.py", line 131, in create assert isinstance(name, string_types), "%s must be of string type"%nickname AssertionError: initializer must be of string type

Process finished with exit code 1.

In gluon block.py module it raises Deferred Initialization Error, why does it defer initialization? I used Normal initializer and it initialized all variables, but Load initializer doesn't work. How can I solve the problem?

RedShift51 avatar Feb 01 '18 14:02 RedShift51

@Jing-Luo Hi, I also met the problem of Mixed initializer with Gluon Block. Have you found any solution that allows to use different initializers for different layers/parameters?

@piiswrong Hi, will Gluon Block support Mixed initializer in the future?

II-Matto avatar Apr 03 '18 11:04 II-Matto

I am trying to load a np array into a Dense layer as weight like this:

weights = np.zeros((512,512))
np.fill_diagonal(weights,1)
last_layer = gluon.nn.Dense(
    512, 
    use_bias=False, 
    weight_initializer=mx.initializer.Load({'last_layer_weight':nd.array(weights, ctx)}),
    prefix='last_layer_',
    in_units=512
)
last_layer.initialize()

I get:


---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-70-2c552b0c6c4f> in <module>()
      8     in_units=512
      9 )
---> 10 last_layer.initialize()

~/anaconda3/lib/python3.6/site-packages/mxnet/gluon/block.py in initialize(self, init, ctx, verbose, force_reinit)
    380             Whether to force re-initialization if parameter is already initialized.
    381         """
--> 382         self.collect_params().initialize(init, ctx, verbose, force_reinit)
    383 
    384     def hybridize(self, active=True, **kwargs):

~/anaconda3/lib/python3.6/site-packages/mxnet/gluon/parameter.py in initialize(self, init, ctx, verbose, force_reinit)
    685             init.set_verbosity(verbose=verbose)
    686         for _, v in self.items():
--> 687             v.initialize(None, ctx, init, force_reinit=force_reinit)
    688 
    689     def zero_grad(self):

~/anaconda3/lib/python3.6/site-packages/mxnet/gluon/parameter.py in initialize(self, init, ctx, default_init, force_reinit)
    338 
    339         self._deferred_init = (init, ctx, default_init, None)
--> 340         self._finish_deferred_init()
    341 
    342     def reset_ctx(self, ctx):

~/anaconda3/lib/python3.6/site-packages/mxnet/gluon/parameter.py in _finish_deferred_init(self)
    240                                      ctx=context.cpu())
    241                 initializer.create(default_init)(
--> 242                     initializer.InitDesc(self.name, {'__init__': init}), data)
    243 
    244             self._init_impl(data, ctx)

~/anaconda3/lib/python3.6/site-packages/mxnet/initializer.py in __call__(self, desc, arr)
    136         if init:
    137             # when calling Variable initializer
--> 138             create(init)._init_weight(desc, arr)
    139             self._verbose_print(desc, init, arr)
    140         else:

~/anaconda3/lib/python3.6/site-packages/mxnet/registry.py in create(*args, **kwargs)
    147             return create(**name)
    148 
--> 149         assert isinstance(name, string_types), "%s must be of string type"%nickname
    150 
    151         if name.startswith('['):

AssertionError: initializer must be of string type

update: To accomplish the following you can use:

last_layer = gluon.nn.Dense(
    512, 
    in_units=512, 
    use_bias=False, 
    weight_initializer=mx.init.Constant(nd.array(np.identity(512)))
)
last_layer.collect_params().initialize(ctx=ctx)
last_layer.params['dense0_weight'].data()

ThomasDelteil avatar Apr 22 '18 04:04 ThomasDelteil

@RedShift51 @ThomasDelteil I also meet AssertionError: initializer must be of string type when I try to override Block.initialize() method.

As for my situation, I found this problem is caused by a parameter called default_init in Parameter class initialize method while not appeared in ParameterDict class. Here is the code The bool value I want to set force_reinit is set to default_init that caused this error.

The solution is very simple, passing keyword arguments, such as: param..initialize(init=init, ctx=ctx, force_reinit=False)

Not sure is this helpful for you. I comment here just for a reference.

WalterMa avatar Jun 05 '18 11:06 WalterMa