Repository navigation
Conversation
|
Should we try to combine this with mx.mod.Module? (We have written a lot of codes in Module.) Also, I find that the old |
f838f76 to
2a5b780
Compare
mli
left a comment
There was a problem hiding this comment.
i also have the same question as @sxjscience , what's the relationship between nn and mod, and how to educate users to use
| # code to automatically download dataset | ||
| curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__))) | ||
| sys.path.append(os.path.join(curr_path, "../../tests/python/common")) | ||
| import get_data |
There was a problem hiding this comment.
suggest to add a function in test_utils.py, for example
def get_mnist():
"""Download and load the MNIST dataset
Returns
-------
dict
A dict containing
"""
def read_data(label_url, image_url):
with gzip.open(mx.test_utils.download(label_url)) as flbl:
magic, num = struct.unpack(">II", flbl.read(8))
label = np.fromstring(flbl.read(), dtype=np.int8)
with gzip.open(mx.test_utils.download(image_url), 'rb') as fimg:
magic, num, rows, cols = struct.unpack(">IIII", fimg.read(16))
image = np.fromstring(fimg.read(), dtype=np.uint8).reshape(len(label), rows, cols)
image = image.reshape(image.shape[0], 1, 28, 28).astype(np.float32)/255
return (label, image)
# changed to mxnet.io for more stable hosting
# path='http://yann.lecun.com/exdb/mnist/'
path='http://data.mxnet.io/data/mnist/'
(train_lbl, train_img) = read_data(
path+'train-labels-idx1-ubyte.gz', path+'train-images-idx3-ubyte.gz')
(test_lbl, test_img) = read_data(
path+'t10k-labels-idx1-ubyte.gz', path+'t10k-images-idx3-ubyte.gz')
return {'train_data':train_img, 'train_label':train_lbl,
'test_data':test_img, 'test_label':test_lbl}then we can use NDArrayIter for them
There was a problem hiding this comment.
This is temporary. I'll do something like pytorch.dataset later
|
|
||
| Layers can also contain other Layers, allowing you to nest them in a tree | ||
| structure. You can assign sublayers as regular attributes:: | ||
| from mxnet import nn |
There was a problem hiding this comment.
there should be an empty line before from
There was a problem hiding this comment.
also suggest to add >>> before each line, then we can have doctest to run all these commands
| @@ -0,0 +1,93 @@ | |||
| # coding: utf-8 | |||
| # pylint: disable= | |||
There was a problem hiding this comment.
i think both coding and pylint are not necessary
|
|
||
|
|
||
| class SimpleLayer(Layer): | ||
| """SimpleLayer is a Layer that supports forwarding with both `Symbol` and `NDArray`. |
There was a problem hiding this comment.
What's the difference between SimpleLayer and Layer? Layer cannot forward with NDArray?
f4eb5bf to
bd9f800
Compare
|
@piiswrong: we are very interested in dynamic graph construction direction MXNet is going in. A question: how flexible (compared to pytorch) is this? For example, can complicated NLP examples be implemented (like https://devblogs.nvidia.com/parallelforall/recursive-neural-networks-pytorch/)? |
|
@sbodenstein It should match pytorch feature by feature. If you see anything missing it should be easy to add it |
|
@sxjscience The existing module API can actually do low level forward backward easily, as a demo shown here for writing your own explicit training loop. But comparing to PyTorch's full interface, it is still a bit basic. I do think we have a lot to learn from PyTorch / Chainer API design by either extending module or have a new API. |
| label = nn.utils.load_data(batch.label[0], ctx_list=ctx, batch_axis=0) | ||
| outputs = [] | ||
| with ag.train_section(): | ||
| for x, y in zip(data, label): |
There was a problem hiding this comment.
Why are we having an inner loop? Is it iterating through the batch one example at a time? Is it used to demonstrate that we can do this or is it suggesting the user should do this?
There was a problem hiding this comment.
This is doing data parallel on multiple gpus.
we can have a DataParallel util like pytorch but collecting the outputs to one gpu is not a good idea.
There was a problem hiding this comment.
I see. Is it possible to hide the data-par mechanism like the original mxnet way? I guess in the imperative style API, the users always explicitly write for loops to handle time index or other dimensions. So it seems to be reasonable to always assume the 1st dimension is batch.
There was a problem hiding this comment.
it also confuses me. i thought you are iterating for example by example. probably rename load_data into something like split_data_to_dev.
| def __init__(self, prefix=None, params=None): | ||
| super(Net, self).__init__(prefix=prefix, params=params) | ||
| self.dense1 = nn.Dense(20, in_units=10, prefix=self.prefix+'dense1_') | ||
| self.dense2 = nn.Dense(20, in_units=20, prefix=self.prefix+'dense2_') |
There was a problem hiding this comment.
pytorch use metaclass magic to automatically name the sub-layer according to the variable name it get's assigned. So
self.dense1 = nn.Dense(...)
will automatically have a (nested) name dense1. However, I'm not sure this is actually a feature we want to have. It sometimes could confuse people. If you do something like
self.layers = [nn.Dense(...) for i in range(5)]
the meta-class will no longer be able to figure it out automatically, and not even be able to collect all the parameters in a layer.
| parameter by passing the same dictionary to them. For example:: | ||
| params = nn.ParameterDict(prefix='dense_') | ||
| dense1 = nn.Dense(20, in_units=10, prefix='dense1_', params=params) | ||
| dense2 = nn.Dense(20, in_units=10, prefix='dense2_', params=params) |
There was a problem hiding this comment.
What does this example mean? The two separate prefix dense1_ and dense2_ are used to name the layer, but their parameter will be named dense_ XXX?
There was a problem hiding this comment.
yes, for sharing parameters
| self._children = [] | ||
|
|
||
| def __setattr__(self, name, value): | ||
| """Automatically register sublayers.""" |
There was a problem hiding this comment.
Maybe we are not going to make thing so complicated to support setting a list of layers or a dict of layers (sometimes people want to do that when there are a lot of inner layers or they are generated pragmatically). But maybe could be useful to detect this situation and print a warning that the layers might not be registered.
|
|
||
| def __setattr__(self, name, value): | ||
| """Automatically register sublayers.""" | ||
| super(Layer, self).__setattr__(name, value) |
There was a problem hiding this comment.
Maybe we can use the name as a prefix if the layer being registered does not already explicitly have a prefix?
There was a problem hiding this comment.
I've considered this. But it gets complicated and confusing when you start to nest layers.
should renaming be recursive?
There was a problem hiding this comment.
Hmm, I see. Yes, it should be recursive, and then becomes a bit complicated.
I checked the pytorch version. Their Module object do not have a name attached to it. The name is only used as a key when a module is nested in other modules and will be generated on the fly so that recursive key prefix is simple: https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/module.py#L440
For us, the module has its own name, and if we assign the same module as a submodule to two different places, it could be potentially conflicting names. So the situation is more complicated.
There was a problem hiding this comment.
Overall implicit registration on assign is pretty bad engineering. But it does make the interface easier to use.
There was a problem hiding this comment.
Chainer used to use explicit registration at __init__ time, and is moving to PyTorch's implicit registration on assign because it works much better with IDEs.
There was a problem hiding this comment.
Actually the with approach is very clever; it solves the list vs ModuleList problem too!
There was a problem hiding this comment.
we can also call it build or constructor instead of init so that its even more obvious
There was a problem hiding this comment.
yeah that's the idea. I have been banging my head against this for 2 days now...
pytorch let the devil out of the box and now we have to follow suit
There was a problem hiding this comment.
I like this scope thing. Except that I would prefer not to hide it, but to require user to write it explicitly (so that they know what is happening and do not get confused when they accidentally overwrite __init__ instead of init. So I'm suggesting maybe we could make it explicit by using a informative name for the scope such as
with self.collect_params():
self.fcs = [nn.Dense(...) for i in range(3)]
self.pred = nn.Dense(...)collect_params could be replaced with a better name, but my point is to ask user to do it explicitly instead of hiding it. What do you guys think?
There was a problem hiding this comment.
@jekbradbury as for __call__ and forward. I think both are fine. What I do not like about pytorch is that it seems __call__ does extra bookkeepings than forward and I do not what kind of consequence you will have by calling forward directly for user vs calling __call__. On the other hand, I think the Chainer way where __call__ and forward are the same thing, sounds better, and less confusing.
|
Seems we are going to manually define a bunch of NN layers in python, e.g., Pooling, BatchNorm, etc. Can they be generated automatically from c lib, just like the functions for symbol? Other frontend languages can follow the same way to do code generation. |
|
this is a super exciting development. I'm also wondering what the relationship to the existing APIs like the Module API will be in the long run? |
|
This is awesome! My nvidia blogpost has one example of the kind of model that needs this sort of framework, but a more practically useful one that'll demonstrate the full power of this approach in MXNet is https://github.com/facebookresearch/clevr-iep. I think it would be surprisingly easy to port as a demonstration (one benefit of PyTorch not building in any training loop abstractions etc. is that there's less to port when you move it to another framework). |
|
Several comments from previous conversations that I think might be good to post here for public discussions. Merging Metric and LossThe current proposal serialize a list of metrics inside a loss object. An alternative proposal is to unify metric and loss. A
A When constructing module, a list of So the effective loss is the sum of all Layer and SimpleLayerI think it might be good to rename Layer to BaseLayer, and SimpleLayer to Layer, as the user will mostly be interacting with The Whether to provide a built-in
|
| loss = nn.loss.softmax_cross_entropy_loss(z, y) | ||
| ag.compute_gradient([loss]) | ||
| outputs.append(z) | ||
| optim.step(batch.data[0].shape[0]) |
| from ...contrib import autograd | ||
|
|
||
| # pylint: disable= invalid-name | ||
| tensor_types = (symbol.Symbol, ndarray.NDArray) |
There was a problem hiding this comment.
you can change to
tensor_types = (symbol.Symbol, ndarray.NDArray) # pylint: disable=invalid-name
a high level NN interface that supports symbolic+imperative use. With a mixed Keras and pytorch flavor.
@jermainewang @pluskid @sxjscience @yajiedesign @tqchen @mli @madjam