You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mxnet.apache.org by zh...@apache.org on 2020/09/05 18:13:45 UTC
[incubator-mxnet] branch master updated: [API] clean up gluon
contrib (#19046)
This is an automated email from the ASF dual-hosted git repository.
zhasheng pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-mxnet.git
The following commit(s) were added to refs/heads/master by this push:
new af2b4bc [API] clean up gluon contrib (#19046)
af2b4bc is described below
commit af2b4bcecfbf52df3a833974651eb75301d8f860
Author: Sheng Zha <sz...@users.noreply.github.com>
AuthorDate: Sat Sep 5 11:11:38 2020 -0700
[API] clean up gluon contrib (#19046)
* clean up gluon contrib
* add numpy tests for conv
---
.../python_docs/python/api/gluon/contrib/index.rst | 94 +--
docs/python_docs/python/api/gluon/data/index.rst | 3 +-
docs/python_docs/python/api/gluon/nn/index.rst | 28 +-
docs/python_docs/python/api/gluon/rnn/index.rst | 22 +-
python/mxnet/contrib/__init__.py | 1 -
python/mxnet/contrib/amp/lists/symbol_bf16.py | 2 +-
python/mxnet/contrib/amp/lists/symbol_fp16.py | 2 +-
python/mxnet/contrib/autograd.py | 228 ------
python/mxnet/gluon/contrib/__init__.py | 6 -
python/mxnet/gluon/contrib/cnn/__init__.py | 25 -
python/mxnet/gluon/contrib/cnn/conv_layers.py | 399 -----------
python/mxnet/gluon/contrib/data/__init__.py | 3 -
python/mxnet/gluon/contrib/data/sampler.py | 62 --
python/mxnet/gluon/contrib/data/text.py | 176 -----
python/mxnet/gluon/contrib/nn/__init__.py | 26 -
python/mxnet/gluon/contrib/nn/basic_layers.py | 372 ----------
python/mxnet/gluon/contrib/rnn/__init__.py | 28 -
python/mxnet/gluon/contrib/rnn/rnn_cell.py | 431 -----------
python/mxnet/gluon/data/sampler.py | 43 +-
python/mxnet/gluon/model_zoo/vision/densenet.py | 5 +-
python/mxnet/gluon/model_zoo/vision/inception.py | 15 +-
python/mxnet/gluon/model_zoo/vision/squeezenet.py | 3 +-
python/mxnet/gluon/nn/basic_layers.py | 180 ++++-
python/mxnet/gluon/nn/conv_layers.py | 591 ++++++++++++++-
python/mxnet/gluon/rnn/__init__.py | 2 +-
.../mxnet/gluon/{contrib => }/rnn/conv_rnn_cell.py | 6 +-
python/mxnet/gluon/rnn/rnn_cell.py | 408 ++++++++++-
python/mxnet/numpy/random.py | 4 +-
python/mxnet/random.py | 28 +-
.../{contrib => }/deformable_convolution-inl.h | 16 +-
.../{contrib => }/deformable_convolution.cc | 2 +-
.../{contrib => }/deformable_convolution.cu | 0
.../modulated_deformable_convolution-inl.h | 16 +-
.../modulated_deformable_convolution.cc | 2 +-
.../modulated_deformable_convolution.cu | 0
tests/python/gpu/test_gluon_contrib_gpu.py | 87 ---
tests/python/gpu/test_gluon_gpu.py | 12 +-
tests/python/gpu/test_operator_gpu.py | 10 +-
tests/python/unittest/test_contrib_autograd.py | 193 -----
tests/python/unittest/test_contrib_operator.py | 36 -
tests/python/unittest/test_contrib_text.py | 794 ---------------------
tests/python/unittest/test_gluon.py | 189 ++++-
tests/python/unittest/test_gluon_contrib.py | 426 -----------
tests/python/unittest/test_gluon_data.py | 6 +
tests/python/unittest/test_gluon_rnn.py | 238 +++++-
tests/python/unittest/test_numpy_gluon.py | 117 ++-
tests/python/unittest/test_numpy_op.py | 39 +
tests/python/unittest/test_operator.py | 20 +-
tests/python/unittest/test_random.py | 2 +-
49 files changed, 1911 insertions(+), 3487 deletions(-)
diff --git a/docs/python_docs/python/api/gluon/contrib/index.rst b/docs/python_docs/python/api/gluon/contrib/index.rst
index b65c1f9..90c782d 100644
--- a/docs/python_docs/python/api/gluon/contrib/index.rst
+++ b/docs/python_docs/python/api/gluon/contrib/index.rst
@@ -38,79 +38,19 @@ so that feature contributors can receive feedback.
In the rest of this document, we list routines provided by the `gluon.contrib` package.
-Neural Network
---------------
-
-
-.. currentmodule:: mxnet.gluon.contrib.nn
-
-.. autosummary::
- :nosignatures:
-
- Concurrent
- HybridConcurrent
- Identity
- SyncBatchNorm
- PixelShuffle1D
- PixelShuffle2D
- PixelShuffle3D
-
-
-Convolutional Neural Network
-----------------------------
-
-.. currentmodule:: mxnet.gluon.contrib.cnn
-
-.. autosummary::
- :nosignatures:
-
- DeformableConvolution
-
-
-Recurrent Neural Network
-------------------------
-
-
-.. currentmodule:: mxnet.gluon.contrib.rnn
+Vision Data
+-----------
.. autosummary::
:nosignatures:
- VariationalDropoutCell
- Conv1DRNNCell
- Conv2DRNNCell
- Conv3DRNNCell
- Conv1DLSTMCell
- Conv2DLSTMCell
- Conv3DLSTMCell
- Conv1DGRUCell
- Conv2DGRUCell
- Conv3DGRUCell
- LSTMPCell
-
-
-Data
-----
-
-
-.. currentmodule:: mxnet.gluon.contrib.data.sampler
-
-.. autosummary::
- :nosignatures:
-
- IntervalSampler
-
-
-Text Dataset
-------------
-
-.. currentmodule:: mxnet.gluon.contrib.data.text
-
-.. autosummary::
- :nosignatures:
-
- WikiText2
- WikiText103
+ data.vision.create_image_augment
+ data.vision.ImageDataLoader
+ data.vision.ImageBboxDataLoader
+ data.vision.ImageBboxRandomFlipLeftRight
+ data.vision.ImageBboxCrop
+ data.vision.ImageBboxRandomCropWithConstraints
+ data.vision.ImageBboxResize
Estimator
@@ -143,25 +83,9 @@ Event Handler
API Reference
-------------
-
.. automodule:: mxnet.gluon.contrib
:members:
-.. automodule:: mxnet.gluon.contrib.nn
- :members:
-
-.. automodule:: mxnet.gluon.contrib.cnn
- :members:
-
-.. automodule:: mxnet.gluon.contrib.rnn
- :members:
-
-.. automodule:: mxnet.gluon.contrib.data.sampler
- :members:
-
-.. automodule:: mxnet.gluon.contrib.data.text
- :members:
-
.. automodule:: mxnet.gluon.contrib.estimator
:members:
:imported-members:
diff --git a/docs/python_docs/python/api/gluon/data/index.rst b/docs/python_docs/python/api/gluon/data/index.rst
index f9e8a21..7b31e17 100644
--- a/docs/python_docs/python/api/gluon/data/index.rst
+++ b/docs/python_docs/python/api/gluon/data/index.rst
@@ -39,6 +39,7 @@ Sampling
SequentialSampler
RandomSampler
BatchSampler
+ IntervalSampler
DataLoader
----------
@@ -60,4 +61,4 @@ API Reference
:maxdepth: 2
:glob:
- */index
\ No newline at end of file
+ */index
diff --git a/docs/python_docs/python/api/gluon/nn/index.rst b/docs/python_docs/python/api/gluon/nn/index.rst
index 110a998..1c7051e 100644
--- a/docs/python_docs/python/api/gluon/nn/index.rst
+++ b/docs/python_docs/python/api/gluon/nn/index.rst
@@ -29,7 +29,6 @@ two modules:
:nosignatures:
mxnet.gluon.nn
- mxnet.gluon.contrib.nn
We group all layers in these two modules according to their categories.
@@ -38,10 +37,9 @@ We group all layers in these two modules according to their categories.
-Sequential containers
+Sequential Containers
---------------------
-
.. autosummary::
:nosignatures:
@@ -49,6 +47,16 @@ Sequential containers
nn.HybridSequential
+Concatenation Containers
+------------------------
+
+.. autosummary::
+ :nosignatures:
+
+ nn.Concatenate
+ nn.HybridConcatenate
+
+
Basic Layers
------------
@@ -61,6 +69,7 @@ Basic Layers
nn.Flatten
nn.Lambda
nn.HybridLambda
+ nn.Identity
Convolutional Layers
--------------------
@@ -74,6 +83,18 @@ Convolutional Layers
nn.Conv1DTranspose
nn.Conv2DTranspose
nn.Conv3DTranspose
+ nn.DeformableConvolution
+ nn.ModulatedDeformableConvolution
+
+Pixel Shuffle Layers
+--------------------
+
+.. autosummary::
+ :nosignatures:
+
+ nn.PixelShuffle1D
+ nn.PixelShuffle2D
+ nn.PixelShuffle3D
Pooling Layers
--------------
@@ -104,6 +125,7 @@ Normalization Layers
nn.BatchNorm
nn.InstanceNorm
nn.LayerNorm
+ nn.SyncBatchNorm
Embedding Layers
----------------
diff --git a/docs/python_docs/python/api/gluon/rnn/index.rst b/docs/python_docs/python/api/gluon/rnn/index.rst
index e02cdc6..637a0a3 100644
--- a/docs/python_docs/python/api/gluon/rnn/index.rst
+++ b/docs/python_docs/python/api/gluon/rnn/index.rst
@@ -30,7 +30,7 @@ Build-in recurrent neural network layers are provided in the following two modul
.. currentmodule:: mxnet.gluon
Recurrent Cells
-----------------
+---------------
.. autosummary::
:nosignatures:
@@ -38,12 +38,30 @@ Recurrent Cells
rnn.LSTMCell
rnn.GRUCell
rnn.RecurrentCell
+ rnn.LSTMPCell
rnn.SequentialRNNCell
rnn.BidirectionalCell
rnn.DropoutCell
+ rnn.VariationalDropoutCell
rnn.ZoneoutCell
rnn.ResidualCell
+Convolutional Recurrent Cells
+-----------------------------
+
+.. autosummary::
+ :nosignatures:
+
+ rnn.Conv1DLSTMCell
+ rnn.Conv2DLSTMCell
+ rnn.Conv3DLSTMCell
+ rnn.Conv1DGRUCell
+ rnn.Conv2DGRUCell
+ rnn.Conv3DGRUCell
+ rnn.Conv1DRNNCell
+ rnn.Conv2DRNNCell
+ rnn.Conv3DRNNCell
+
Recurrent Layers
----------------
@@ -59,4 +77,4 @@ API Reference
.. automodule:: mxnet.gluon.rnn
:members:
:imported-members:
- :autosummary:
\ No newline at end of file
+ :autosummary:
diff --git a/python/mxnet/contrib/__init__.py b/python/mxnet/contrib/__init__.py
index ca4b9d4..ab4303f 100644
--- a/python/mxnet/contrib/__init__.py
+++ b/python/mxnet/contrib/__init__.py
@@ -24,7 +24,6 @@ from . import ndarray
from . import symbol as sym
from . import ndarray as nd
-from . import autograd
from . import tensorboard
from . import text
diff --git a/python/mxnet/contrib/amp/lists/symbol_bf16.py b/python/mxnet/contrib/amp/lists/symbol_bf16.py
index 7ae799c..306635a 100644
--- a/python/mxnet/contrib/amp/lists/symbol_bf16.py
+++ b/python/mxnet/contrib/amp/lists/symbol_bf16.py
@@ -492,7 +492,7 @@ FP32_FUNCS = [
'_contrib_CTCLoss',
'_contrib_ctc_loss',
'ctc_loss',
- '_contrib_DeformableConvolution',
+ '_npx_deformable_convolution',
'_contrib_DeformablePSROIPooling',
]
diff --git a/python/mxnet/contrib/amp/lists/symbol_fp16.py b/python/mxnet/contrib/amp/lists/symbol_fp16.py
index 5858eb9..275d088 100644
--- a/python/mxnet/contrib/amp/lists/symbol_fp16.py
+++ b/python/mxnet/contrib/amp/lists/symbol_fp16.py
@@ -485,7 +485,7 @@ FP32_FUNCS = [
'_contrib_CTCLoss',
'_contrib_ctc_loss',
'ctc_loss',
- '_contrib_DeformableConvolution',
+ '_npx_deformable_convolution',
'_contrib_DeformablePSROIPooling',
]
diff --git a/python/mxnet/contrib/autograd.py b/python/mxnet/contrib/autograd.py
deleted file mode 100644
index 9c6456c..0000000
--- a/python/mxnet/contrib/autograd.py
+++ /dev/null
@@ -1,228 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-# coding: utf-8
-"""Autograd for NDArray."""
-
-from array import array
-import ctypes
-import functools
-from ..base import _LIB, check_call, string_types
-from ..base import mx_uint, NDArrayHandle, c_array, c_array_buf, c_handle_array
-# pylint: disable= unused-import
-from ..ndarray import NDArray, zeros_like, _GRAD_REQ_MAP
-
-
-def set_is_training(is_train):
- """Set status to training/not training. When training, graph will be constructed
- for gradient computation. Operators will also run with ctx.is_train=True. For example,
- Dropout will drop inputs randomly when is_train=True while simply passing through
- if is_train=False.
-
- Parameters
- ----------
- is_train: bool
-
- Returns
- -------
- previous state before this set.
- """
- prev = ctypes.c_int()
- check_call(_LIB.MXAutogradSetIsTraining(
- ctypes.c_int(is_train), ctypes.byref(prev)))
- check_call(_LIB.MXAutogradSetIsRecording(
- ctypes.c_int(is_train), ctypes.byref(prev)))
- return bool(prev.value)
-
-
-class TrainingStateScope(object):
- """Scope for managing training state.
-
- Example::
- with TrainingStateScope(True):
- y = model(x)
- compute_gradient([y])
- """
- def __init__(self, enter_state):
- self._enter_state = enter_state
- self._prev = None
-
- def __enter__(self):
- self._prev = set_is_training(self._enter_state)
-
- def __exit__(self, ptype, value, trace):
- if self._prev != self._enter_state:
- set_is_training(self._prev)
-
-
-def train_section():
- """Returns a training scope context to be used in 'with' statement
- and captures training code.
-
- Example::
- with autograd.train_section():
- y = model(x)
- compute_gradient([y])
- metric.update(...)
- optim.step(...)
- """
- return TrainingStateScope(True)
-
-
-def test_section():
- """Returns a testing scope context to be used in 'with' statement
- and captures testing code.
-
- Example::
- with autograd.train_section():
- y = model(x)
- compute_gradient([y])
- with autograd.test_section():
- # testing, IO, gradient updates...
- """
- return TrainingStateScope(False)
-
-
-def mark_variables(variables, gradients, grad_reqs='write'):
- """Mark NDArrays as variables to compute gradient for autograd.
-
- Parameters
- ----------
- variables: list of NDArray
- gradients: list of NDArray
- grad_reqs: list of string
- """
- if isinstance(grad_reqs, string_types):
- grad_reqs = [_GRAD_REQ_MAP[grad_reqs]]*len(variables)
- else:
- grad_reqs = [_GRAD_REQ_MAP[i] for i in grad_reqs]
-
- check_call(_LIB.MXAutogradMarkVariables(
- len(variables),
- c_handle_array(variables),
- c_array_buf(mx_uint, array('I', grad_reqs)),
- c_handle_array(gradients)))
-
-
-def backward(outputs, out_grads=None, retain_graph=False):
- """Compute the gradients of outputs w.r.t variables.
-
- Parameters
- ----------
- outputs: list of NDArray
- out_grads: list of NDArray or None
- """
- assert isinstance(outputs, (list, tuple)), \
- "outputs must be a list or tuple of NDArrays"
-
- if out_grads is None:
- check_call(_LIB.MXAutogradBackward(
- len(outputs),
- c_handle_array(outputs),
- ctypes.c_void_p(0),
- ctypes.c_int(retain_graph)))
- return
-
- ograd_handles = []
- for arr in out_grads:
- if arr is not None:
- ograd_handles.append(arr.handle)
- else:
- ograd_handles.append(NDArrayHandle(0))
- assert len(ograd_handles) == len(outputs), \
- "outputs and out_grads must have the same length"
-
- check_call(_LIB.MXAutogradBackward(
- len(outputs),
- c_handle_array(outputs),
- c_array(NDArrayHandle, ograd_handles),
- ctypes.c_int(retain_graph)))
-
-
-def compute_gradient(outputs):
- """Deprecated. Please use backward"""
- backward(outputs)
-
-
-def grad_and_loss(func, argnum=None):
- """Return function that computes both gradient of arguments and loss value.
-
- Parameters
- ----------
- func: a python function
- The forward (loss) function.
- argnum: an int or a list of int
- The index of argument to calculate gradient for.
-
- Returns
- -------
- grad_and_loss_func: a python function
- A function that would compute both the gradient of arguments and loss value.
- """
- @functools.wraps(func)
- def wrapped(*args):
- """Wrapped function."""
- variables = args
- if argnum is not None:
- argnum_ = argnum if isinstance(argnum, list) else [argnum]
- variables = [args[i] for i in argnum_]
- for x in variables:
- assert isinstance(x, NDArray), "type of autograd input should NDArray."
- grads = [zeros_like(x) for x in variables]
- mark_variables(variables, grads)
- with train_section():
- outputs = func(*args)
- compute_gradient([outputs] if isinstance(outputs, NDArray) else outputs)
- return grads, outputs
- return wrapped
-
-def grad(func, argnum=None):
- """Return function that computes gradient of arguments.
-
- Parameters
- ----------
- func: a python function
- The forward (loss) function.
- argnum: an int or a list of int
- The index of argument to calculate gradient for.
-
- Returns
- -------
- grad_func: a python function
- A function that would compute the gradient of arguments.
-
- Examples
- --------
- >>> # autograd supports dynamic graph which is changed
- >>> # every instance
- >>> def func(x):
- >>> r = random.randint(0, 1)
- >>> if r % 2:
- >>> return x**2
- >>> else:
- >>> return x/3
- >>> # use `grad(func)` to get the gradient function
- >>> for x in range(10):
- >>> grad_func = grad(func)
- >>> inputs = nd.array([[1, 2, 3], [4, 5, 6]])
- >>> grad_vals = grad_func(inputs)
- """
- grad_with_loss_func = grad_and_loss(func, argnum)
- @functools.wraps(grad_with_loss_func)
- def wrapped(*args):
- return grad_with_loss_func(*args)[0]
- return wrapped
diff --git a/python/mxnet/gluon/contrib/__init__.py b/python/mxnet/gluon/contrib/__init__.py
index 7590eb7..9b9f0ce 100644
--- a/python/mxnet/gluon/contrib/__init__.py
+++ b/python/mxnet/gluon/contrib/__init__.py
@@ -18,12 +18,6 @@
# coding: utf-8
"""Contrib neural network module."""
-from . import nn
-
-from . import rnn
-
-from . import cnn
-
from . import data
from . import estimator
diff --git a/python/mxnet/gluon/contrib/cnn/__init__.py b/python/mxnet/gluon/contrib/cnn/__init__.py
deleted file mode 100644
index 501b9ea..0000000
--- a/python/mxnet/gluon/contrib/cnn/__init__.py
+++ /dev/null
@@ -1,25 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-# coding: utf-8
-# pylint: disable=wildcard-import
-"""Contrib convolutional neural network module."""
-
-from . import conv_layers
-from .conv_layers import *
-
-__all__ = conv_layers.__all__
diff --git a/python/mxnet/gluon/contrib/cnn/conv_layers.py b/python/mxnet/gluon/contrib/cnn/conv_layers.py
deleted file mode 100644
index ef74c23..0000000
--- a/python/mxnet/gluon/contrib/cnn/conv_layers.py
+++ /dev/null
@@ -1,399 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-# coding: utf-8
-# pylint: disable= arguments-differ
-"""Custom convolutional neural network layers in model_zoo."""
-
-__all__ = ['DeformableConvolution', 'ModulatedDeformableConvolution']
-
-from .... import symbol
-from ...block import HybridBlock
-from ...parameter import Parameter
-from ....base import numeric_types
-from ...nn import Activation
-
-class DeformableConvolution(HybridBlock):
- """2-D Deformable Convolution v_1 (Dai, 2017).
- Normal Convolution uses sampling points in a regular grid, while the sampling
- points of Deformablem Convolution can be offset. The offset is learned with a
- separate convolution layer during the training. Both the convolution layer for
- generating the output features and the offsets are included in this gluon layer.
-
- Parameters
- ----------
- channels : int,
- The dimensionality of the output space
- i.e. the number of output channels in the convolution.
- kernel_size : int or tuple/list of 2 ints, (Default value = (1,1))
- Specifies the dimensions of the convolution window.
- strides : int or tuple/list of 2 ints, (Default value = (1,1))
- Specifies the strides of the convolution.
- padding : int or tuple/list of 2 ints, (Default value = (0,0))
- If padding is non-zero, then the input is implicitly zero-padded
- on both sides for padding number of points.
- dilation : int or tuple/list of 2 ints, (Default value = (1,1))
- Specifies the dilation rate to use for dilated convolution.
- groups : int, (Default value = 1)
- Controls the connections between inputs and outputs.
- At groups=1, all inputs are convolved to all outputs.
- At groups=2, the operation becomes equivalent to having two convolution
- layers side by side, each seeing half the input channels, and producing
- half the output channels, and both subsequently concatenated.
- num_deformable_group : int, (Default value = 1)
- Number of deformable group partitions.
- layout : str, (Default value = NCHW)
- Dimension ordering of data and weight. Can be 'NCW', 'NWC', 'NCHW',
- 'NHWC', 'NCDHW', 'NDHWC', etc. 'N', 'C', 'H', 'W', 'D' stands for
- batch, channel, height, width and depth dimensions respectively.
- Convolution is performed over 'D', 'H', and 'W' dimensions.
- use_bias : bool, (Default value = True)
- Whether the layer for generating the output features uses a bias vector.
- in_channels : int, (Default value = 0)
- The number of input channels to this layer. If not specified,
- initialization will be deferred to the first time `forward` is called
- and input channels will be inferred from the shape of input data.
- activation : str, (Default value = None)
- Activation function to use. See :func:`~mxnet.ndarray.Activation`.
- If you don't specify anything, no activation is applied
- (ie. "linear" activation: `a(x) = x`).
- weight_initializer : str or `Initializer`, (Default value = None)
- Initializer for the `weight` weights matrix for the convolution layer
- for generating the output features.
- bias_initializer : str or `Initializer`, (Default value = zeros)
- Initializer for the bias vector for the convolution layer
- for generating the output features.
- offset_weight_initializer : str or `Initializer`, (Default value = zeros)
- Initializer for the `weight` weights matrix for the convolution layer
- for generating the offset.
- offset_bias_initializer : str or `Initializer`, (Default value = zeros),
- Initializer for the bias vector for the convolution layer
- for generating the offset.
- offset_use_bias: bool, (Default value = True)
- Whether the layer for generating the offset uses a bias vector.
-
- Inputs:
- - **data**: 4D input tensor with shape
- `(batch_size, in_channels, height, width)` when `layout` is `NCHW`.
- For other layouts shape is permuted accordingly.
-
- Outputs:
- - **out**: 4D output tensor with shape
- `(batch_size, channels, out_height, out_width)` when `layout` is `NCHW`.
- out_height and out_width are calculated as::
-
- out_height = floor((height+2*padding[0]-dilation[0]*(kernel_size[0]-1)-1)/stride[0])+1
- out_width = floor((width+2*padding[1]-dilation[1]*(kernel_size[1]-1)-1)/stride[1])+1
- """
-
- def __init__(self, channels, kernel_size=(1, 1), strides=(1, 1), padding=(0, 0), dilation=(1, 1), groups=1,
- num_deformable_group=1, layout='NCHW', use_bias=True, in_channels=0, activation=None,
- weight_initializer=None, bias_initializer='zeros',
- offset_weight_initializer='zeros', offset_bias_initializer='zeros', offset_use_bias=True,
- op_name='DeformableConvolution', adj=None):
- super(DeformableConvolution, self).__init__()
- self._channels = channels
- self._in_channels = in_channels
-
- assert layout in ('NCHW', 'NHWC'), "Only supports 'NCHW' and 'NHWC' layout for now"
- if isinstance(kernel_size, numeric_types):
- kernel_size = (kernel_size,) * 2
- if isinstance(strides, numeric_types):
- strides = (strides,) * len(kernel_size)
- if isinstance(padding, numeric_types):
- padding = (padding,) * len(kernel_size)
- if isinstance(dilation, numeric_types):
- dilation = (dilation,) * len(kernel_size)
- self._op_name = op_name
-
- offset_channels = 2 * kernel_size[0] * kernel_size[1] * num_deformable_group
- self._kwargs_offset = {
- 'kernel': kernel_size, 'stride': strides, 'dilate': dilation,
- 'pad': padding, 'num_filter': offset_channels, 'num_group': groups,
- 'no_bias': not offset_use_bias, 'layout': layout}
-
- self._kwargs_deformable_conv = {
- 'kernel': kernel_size, 'stride': strides, 'dilate': dilation,
- 'pad': padding, 'num_filter': channels, 'num_group': groups,
- 'num_deformable_group': num_deformable_group,
- 'no_bias': not use_bias, 'layout': layout}
-
- if adj:
- self._kwargs_offset['adj'] = adj
- self._kwargs_deformable_conv['adj'] = adj
-
- dshape = [0] * (len(kernel_size) + 2)
- dshape[layout.find('N')] = 1
- dshape[layout.find('C')] = in_channels
-
- op = getattr(symbol, 'Convolution')
- offset = op(symbol.var('data', shape=dshape), **self._kwargs_offset)
-
- offsetshapes = offset.infer_shape_partial()[0]
-
- self.offset_weight = Parameter('offset_weight', shape=offsetshapes[1],
- init=offset_weight_initializer,
- allow_deferred_init=True)
-
- if offset_use_bias:
- self.offset_bias = Parameter('offset_bias', shape=offsetshapes[2],
- init=offset_bias_initializer,
- allow_deferred_init=True)
- else:
- self.offset_bias = None
-
- deformable_conv_weight_shape = [0] * (len(kernel_size) + 2)
- deformable_conv_weight_shape[0] = channels
- deformable_conv_weight_shape[2] = kernel_size[0]
- deformable_conv_weight_shape[3] = kernel_size[1]
-
- self.deformable_conv_weight = Parameter('deformable_conv_weight',
- shape=deformable_conv_weight_shape,
- init=weight_initializer,
- allow_deferred_init=True)
-
- if use_bias:
- self.deformable_conv_bias = Parameter('deformable_conv_bias', shape=(channels,),
- init=bias_initializer,
- allow_deferred_init=True)
- else:
- self.deformable_conv_bias = None
-
- if activation:
- self.act = Activation(activation)
- else:
- self.act = None
-
- def hybrid_forward(self, F, x, offset_weight, deformable_conv_weight, offset_bias=None, deformable_conv_bias=None):
- if offset_bias is None:
- offset = F.Convolution(x, offset_weight, cudnn_off=True, **self._kwargs_offset)
- else:
- offset = F.Convolution(x, offset_weight, offset_bias, cudnn_off=True, **self._kwargs_offset)
-
- if deformable_conv_bias is None:
- act = F.contrib.DeformableConvolution(data=x, offset=offset, weight=deformable_conv_weight,
- name='fwd', **self._kwargs_deformable_conv)
- else:
- act = F.contrib.DeformableConvolution(data=x, offset=offset, weight=deformable_conv_weight,
- bias=deformable_conv_bias, name='fwd',
- **self._kwargs_deformable_conv)
-
- if self.act:
- act = self.act(act)
- return act
-
- def _alias(self):
- return 'deformable_conv'
-
- def __repr__(self):
- s = '{name}({mapping}, kernel_size={kernel}, stride={stride}'
- len_kernel_size = len(self._kwargs_deformable_conv['kernel'])
- if self._kwargs_deformable_conv['pad'] != (0,) * len_kernel_size:
- s += ', padding={pad}'
- if self._kwargs_deformable_conv['dilate'] != (1,) * len_kernel_size:
- s += ', dilation={dilate}'
- if hasattr(self, 'out_pad') and self.out_pad != (0,) * len_kernel_size:
- s += ', output_padding={out_pad}'.format(out_pad=self.out_pad)
- if self._kwargs_deformable_conv['num_group'] != 1:
- s += ', groups={num_group}'
- if self.deformable_conv_bias is None:
- s += ', bias=False'
- if self.act:
- s += ', {}'.format(self.act)
- s += ')'
- shape = self.deformable_conv_weight.shape
- return s.format(name=self.__class__.__name__,
- mapping='{0} -> {1}'.format(shape[1] if shape[1] else None, shape[0]),
- **self._kwargs_deformable_conv)
-
-
-class ModulatedDeformableConvolution(HybridBlock):
- """2-D Deformable Convolution v2 (Dai, 2018).
-
- The modulated deformable convolution operation is described in https://arxiv.org/abs/1811.11168
-
- Parameters
- ----------
- channels : int,
- The dimensionality of the output space
- i.e. the number of output channels in the convolution.
- kernel_size : int or tuple/list of 2 ints, (Default value = (1,1))
- Specifies the dimensions of the convolution window.
- strides : int or tuple/list of 2 ints, (Default value = (1,1))
- Specifies the strides of the convolution.
- padding : int or tuple/list of 2 ints, (Default value = (0,0))
- If padding is non-zero, then the input is implicitly zero-padded
- on both sides for padding number of points.
- dilation : int or tuple/list of 2 ints, (Default value = (1,1))
- Specifies the dilation rate to use for dilated convolution.
- groups : int, (Default value = 1)
- Controls the connections between inputs and outputs.
- At groups=1, all inputs are convolved to all outputs.
- At groups=2, the operation becomes equivalent to having two convolution
- layers side by side, each seeing half the input channels, and producing
- half the output channels, and both subsequently concatenated.
- num_deformable_group : int, (Default value = 1)
- Number of deformable group partitions.
- layout : str, (Default value = NCHW)
- Dimension ordering of data and weight. Can be 'NCW', 'NWC', 'NCHW',
- 'NHWC', 'NCDHW', 'NDHWC', etc. 'N', 'C', 'H', 'W', 'D' stands for
- batch, channel, height, width and depth dimensions respectively.
- Convolution is performed over 'D', 'H', and 'W' dimensions.
- use_bias : bool, (Default value = True)
- Whether the layer for generating the output features uses a bias vector.
- in_channels : int, (Default value = 0)
- The number of input channels to this layer. If not specified,
- initialization will be deferred to the first time `forward` is called
- and input channels will be inferred from the shape of input data.
- activation : str, (Default value = None)
- Activation function to use. See :func:`~mxnet.ndarray.Activation`.
- If you don't specify anything, no activation is applied
- (ie. "linear" activation: `a(x) = x`).
- weight_initializer : str or `Initializer`, (Default value = None)
- Initializer for the `weight` weights matrix for the convolution layer
- for generating the output features.
- bias_initializer : str or `Initializer`, (Default value = zeros)
- Initializer for the bias vector for the convolution layer
- for generating the output features.
- offset_weight_initializer : str or `Initializer`, (Default value = zeros)
- Initializer for the `weight` weights matrix for the convolution layer
- for generating the offset.
- offset_bias_initializer : str or `Initializer`, (Default value = zeros),
- Initializer for the bias vector for the convolution layer
- for generating the offset.
- offset_use_bias: bool, (Default value = True)
- Whether the layer for generating the offset uses a bias vector.
-
- Inputs:
- - **data**: 4D input tensor with shape
- `(batch_size, in_channels, height, width)` when `layout` is `NCHW`.
- For other layouts shape is permuted accordingly.
-
- Outputs:
- - **out**: 4D output tensor with shape
- `(batch_size, channels, out_height, out_width)` when `layout` is `NCHW`.
- out_height and out_width are calculated as::
-
- out_height = floor((height+2*padding[0]-dilation[0]*(kernel_size[0]-1)-1)/stride[0])+1
- out_width = floor((width+2*padding[1]-dilation[1]*(kernel_size[1]-1)-1)/stride[1])+1
- """
-
- def __init__(self, channels, kernel_size=(1, 1), strides=(1, 1), padding=(0, 0), dilation=(1, 1), groups=1,
- num_deformable_group=1, layout='NCHW', use_bias=True, in_channels=0, activation=None,
- weight_initializer=None, bias_initializer='zeros',
- offset_weight_initializer='zeros', offset_bias_initializer='zeros', offset_use_bias=True,
- op_name='ModulatedDeformableConvolution', adj=None):
- super(ModulatedDeformableConvolution, self).__init__()
- self._channels = channels
- self._in_channels = in_channels
-
- assert layout in ('NCHW', 'NHWC'), "Only supports 'NCHW' and 'NHWC' layout for now"
- if isinstance(kernel_size, numeric_types):
- kernel_size = (kernel_size,) * 2
- if isinstance(strides, numeric_types):
- strides = (strides,) * len(kernel_size)
- if isinstance(padding, numeric_types):
- padding = (padding,) * len(kernel_size)
- if isinstance(dilation, numeric_types):
- dilation = (dilation,) * len(kernel_size)
- self._op_name = op_name
-
- offset_channels = num_deformable_group * 3 * kernel_size[0] * kernel_size[1]
- self.offset_split_index = num_deformable_group * 2 * kernel_size[0] * kernel_size[1]
- self._kwargs_offset = {
- 'kernel': kernel_size, 'stride': strides, 'dilate': dilation,
- 'pad': padding, 'num_filter': offset_channels, 'num_group': groups,
- 'no_bias': not offset_use_bias, 'layout': layout}
-
- self._kwargs_deformable_conv = {
- 'kernel': kernel_size, 'stride': strides, 'dilate': dilation,
- 'pad': padding, 'num_filter': channels, 'num_group': groups,
- 'num_deformable_group': num_deformable_group,
- 'no_bias': not use_bias, 'layout': layout}
-
- if adj:
- self._kwargs_offset['adj'] = adj
- self._kwargs_deformable_conv['adj'] = adj
-
- deformable_conv_weight_shape = [0] * (len(kernel_size) + 2)
- deformable_conv_weight_shape[0] = channels
- deformable_conv_weight_shape[2] = kernel_size[0]
- deformable_conv_weight_shape[3] = kernel_size[1]
-
- self.deformable_conv_weight = Parameter('deformable_conv_weight',
- shape=deformable_conv_weight_shape,
- init=weight_initializer,
- allow_deferred_init=True)
-
- if use_bias:
- self.deformable_conv_bias = Parameter('deformable_conv_bias', shape=(channels,),
- init=bias_initializer,
- allow_deferred_init=True)
- else:
- self.deformable_conv_bias = None
-
- dshape = [0] * (len(kernel_size) + 2)
- dshape[layout.find('N')] = 1
- dshape[layout.find('C')] = in_channels
-
- op = getattr(symbol, 'Convolution')
- offset = op(symbol.var('data', shape=dshape), **self._kwargs_offset)
-
- offsetshapes = offset.infer_shape_partial()[0]
-
- self.offset_weight = Parameter('offset_weight', shape=offsetshapes[1],
- init=offset_weight_initializer,
- allow_deferred_init=True)
-
- if offset_use_bias:
- self.offset_bias = Parameter('offset_bias', shape=offsetshapes[2],
- init=offset_bias_initializer,
- allow_deferred_init=True)
- else:
- self.offset_bias = None
-
- if activation:
- self.act = Activation(activation)
- else:
- self.act = None
-
- def hybrid_forward(self, F, x, offset_weight, deformable_conv_weight, offset_bias=None, deformable_conv_bias=None):
- if offset_bias is None:
- offset = F.Convolution(x, offset_weight, cudnn_off=True, **self._kwargs_offset)
- else:
- offset = F.Convolution(x, offset_weight, offset_bias, cudnn_off=True, **self._kwargs_offset)
-
- offset_t = F.slice_axis(offset, axis=1, begin=0, end=self.offset_split_index)
- mask = F.slice_axis(offset, axis=1, begin=self.offset_split_index, end=None)
- mask = F.sigmoid(mask) * 2
-
- if deformable_conv_bias is None:
- act = F.contrib.ModulatedDeformableConvolution(data=x, offset=offset_t, mask=mask,
- weight=deformable_conv_weight,
- name='fwd', **self._kwargs_deformable_conv)
- else:
- act = F.contrib.ModulatedDeformableConvolution(data=x, offset=offset_t, mask=mask,
- weight=deformable_conv_weight,
- bias=deformable_conv_bias, name='fwd',
- **self._kwargs_deformable_conv)
-
- if self.act:
- act = self.act(act)
- return act
-
- def _alias(self):
- return 'modulated_deformable_conv'
diff --git a/python/mxnet/gluon/contrib/data/__init__.py b/python/mxnet/gluon/contrib/data/__init__.py
index 964d44c..74f6e78 100644
--- a/python/mxnet/gluon/contrib/data/__init__.py
+++ b/python/mxnet/gluon/contrib/data/__init__.py
@@ -19,7 +19,4 @@
# pylint: disable=wildcard-import
"""Contrib datasets."""
-from . import text
from . import vision
-
-from .sampler import *
diff --git a/python/mxnet/gluon/contrib/data/sampler.py b/python/mxnet/gluon/contrib/data/sampler.py
deleted file mode 100644
index e4909c0..0000000
--- a/python/mxnet/gluon/contrib/data/sampler.py
+++ /dev/null
@@ -1,62 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-# coding: utf-8
-# pylint: disable=
-"""Dataset sampler."""
-__all__ = ['IntervalSampler']
-
-from ...data import sampler
-
-class IntervalSampler(sampler.Sampler):
- """Samples elements from [0, length) at fixed intervals.
-
- Parameters
- ----------
- length : int
- Length of the sequence.
- interval : int
- The number of items to skip between two samples.
- rollover : bool, default True
- Whether to start again from the first skipped item after reaching the end.
- If true, this sampler would start again from the first skipped item until all items
- are visited.
- Otherwise, iteration stops when end is reached and skipped items are ignored.
-
- Examples
- --------
- >>> sampler = contrib.data.IntervalSampler(13, interval=3)
- >>> list(sampler)
- [0, 3, 6, 9, 12, 1, 4, 7, 10, 2, 5, 8, 11]
- >>> sampler = contrib.data.IntervalSampler(13, interval=3, rollover=False)
- >>> list(sampler)
- [0, 3, 6, 9, 12]
- """
- def __init__(self, length, interval, rollover=True):
- assert interval <= length, \
- "Interval {} must be smaller than or equal to length {}".format(interval, length)
- self._length = length
- self._interval = interval
- self._rollover = rollover
-
- def __iter__(self):
- for i in range(self._interval if self._rollover else 1):
- for j in range(i, self._length, self._interval):
- yield j
-
- def __len__(self):
- return self._length
diff --git a/python/mxnet/gluon/contrib/data/text.py b/python/mxnet/gluon/contrib/data/text.py
deleted file mode 100644
index 916b418..0000000
--- a/python/mxnet/gluon/contrib/data/text.py
+++ /dev/null
@@ -1,176 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-# coding: utf-8
-# pylint: disable=
-"""Text datasets."""
-__all__ = ['WikiText2', 'WikiText103']
-
-import os
-import zipfile
-import shutil
-import numpy as np
-
-from . import _constants as C
-from ...data import dataset
-from ...utils import download, check_sha1, _get_repo_file_url
-from ....contrib import text
-from .... import ndarray as nd, base
-
-class _LanguageModelDataset(dataset._DownloadedDataset): # pylint: disable=abstract-method
- def __init__(self, root, namespace, vocabulary):
- self._vocab = vocabulary
- self._counter = None
- self._namespace = namespace
- super(_LanguageModelDataset, self).__init__(root, None)
-
- @property
- def vocabulary(self):
- return self._vocab
-
- @property
- def frequencies(self):
- return self._counter
-
- def _build_vocab(self, content):
- if not self._counter:
- self._counter = text.utils.count_tokens_from_str(content)
- if not self._vocab:
- self._vocab = text.vocab.Vocabulary(counter=self.frequencies,
- reserved_tokens=[C.EOS_TOKEN])
-
-
-class _WikiText(_LanguageModelDataset):
-
- def _read_batch(self, filename):
- with open(filename, 'r', encoding='utf8') as fin:
- content = fin.read()
- self._build_vocab(content)
-
- raw_data = [line for line in [x.strip().split() for x in content.splitlines()]
- if line]
- for line in raw_data:
- line.append(C.EOS_TOKEN)
- raw_data = self.vocabulary.to_indices([x for line in raw_data for x in line if x])
- data = raw_data[0:-1]
- label = raw_data[1:]
- return np.array(data, dtype=np.int32), np.array(label, dtype=np.int32)
-
- def _get_data(self):
- archive_file_name, archive_hash = self._archive_file
- data_file_name, data_hash = self._data_file[self._segment]
- path = os.path.join(self._root, data_file_name)
- if not os.path.exists(path) or not check_sha1(path, data_hash):
- namespace = 'gluon/dataset/'+self._namespace
- downloaded_file_path = download(_get_repo_file_url(namespace, archive_file_name),
- path=self._root,
- sha1_hash=archive_hash)
-
- with zipfile.ZipFile(downloaded_file_path, 'r') as zf:
- for member in zf.namelist():
- filename = os.path.basename(member)
- if filename:
- dest = os.path.join(self._root, filename)
- with zf.open(member) as source, \
- open(dest, "wb") as target:
- shutil.copyfileobj(source, target)
-
- data, label = self._read_batch(path)
-
- self._data = nd.array(data, dtype=data.dtype).reshape((-1, self._seq_len))
- self._label = nd.array(label, dtype=label.dtype).reshape((-1, self._seq_len))
-
- def __getitem__(self, idx):
- return self._data[idx], self._label[idx]
-
- def __len__(self):
- return len(self._label)
-
-
-class WikiText2(_WikiText):
- """WikiText-2 word-level dataset for language modeling, from Salesforce research.
-
- From
- https://blog.einstein.ai/the-wikitext-long-term-dependency-language-modeling-dataset/
-
- License: Creative Commons Attribution-ShareAlike
-
- Each sample is a vector of length equal to the specified sequence length.
- At the end of each sentence, an end-of-sentence token '<eos>' is added.
-
- Parameters
- ----------
- root : str, default $MXNET_HOME/datasets/wikitext-2
- Path to temp folder for storing data.
- segment : str, default 'train'
- Dataset segment. Options are 'train', 'validation', 'test'.
- vocab : :class:`~mxnet.contrib.text.vocab.Vocabulary`, default None
- The vocabulary to use for indexing the text dataset.
- If None, a default vocabulary is created.
- seq_len : int, default 35
- The sequence length of each sample, regardless of the sentence boundary.
-
- """
- def __init__(self, root=os.path.join(base.data_dir(), 'datasets', 'wikitext-2'),
- segment='train', vocab=None, seq_len=35):
- self._archive_file = ('wikitext-2-v1.zip', '3c914d17d80b1459be871a5039ac23e752a53cbe')
- self._data_file = {'train': ('wiki.train.tokens',
- '863f29c46ef9d167fff4940ec821195882fe29d1'),
- 'validation': ('wiki.valid.tokens',
- '0418625c8b4da6e4b5c7a0b9e78d4ae8f7ee5422'),
- 'test': ('wiki.test.tokens',
- 'c7b8ce0aa086fb34dab808c5c49224211eb2b172')}
- self._segment = segment
- self._seq_len = seq_len
- super(WikiText2, self).__init__(root, 'wikitext-2', vocab)
-
-
-class WikiText103(_WikiText):
- """WikiText-103 word-level dataset for language modeling, from Salesforce research.
-
- From
- https://blog.einstein.ai/the-wikitext-long-term-dependency-language-modeling-dataset/
-
- License: Creative Commons Attribution-ShareAlike
-
- Each sample is a vector of length equal to the specified sequence length.
- At the end of each sentence, an end-of-sentence token '<eos>' is added.
-
- Parameters
- ----------
- root : str, default $MXNET_HOME/datasets/wikitext-103
- Path to temp folder for storing data.
- segment : str, default 'train'
- Dataset segment. Options are 'train', 'validation', 'test'.
- vocab : :class:`~mxnet.contrib.text.vocab.Vocabulary`, default None
- The vocabulary to use for indexing the text dataset.
- If None, a default vocabulary is created.
- seq_len : int, default 35
- The sequence length of each sample, regardless of the sentence boundary.
- """
- def __init__(self, root=os.path.join(base.data_dir(), 'datasets', 'wikitext-103'),
- segment='train', vocab=None, seq_len=35):
- self._archive_file = ('wikitext-103-v1.zip', '0aec09a7537b58d4bb65362fee27650eeaba625a')
- self._data_file = {'train': ('wiki.train.tokens',
- 'b7497e2dfe77e72cfef5e3dbc61b7b53712ac211'),
- 'validation': ('wiki.valid.tokens',
- 'c326ac59dc587676d58c422eb8a03e119582f92b'),
- 'test': ('wiki.test.tokens',
- '8a5befc548865cec54ed4273cf87dbbad60d1e47')}
- self._segment = segment
- self._seq_len = seq_len
- super(WikiText103, self).__init__(root, 'wikitext-103', vocab)
diff --git a/python/mxnet/gluon/contrib/nn/__init__.py b/python/mxnet/gluon/contrib/nn/__init__.py
deleted file mode 100644
index 5eb46f6..0000000
--- a/python/mxnet/gluon/contrib/nn/__init__.py
+++ /dev/null
@@ -1,26 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-# coding: utf-8
-# pylint: disable=wildcard-import
-"""Contributed neural network modules."""
-
-from . import basic_layers
-
-from .basic_layers import *
-
-__all__ = basic_layers.__all__
diff --git a/python/mxnet/gluon/contrib/nn/basic_layers.py b/python/mxnet/gluon/contrib/nn/basic_layers.py
deleted file mode 100644
index e32c371..0000000
--- a/python/mxnet/gluon/contrib/nn/basic_layers.py
+++ /dev/null
@@ -1,372 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-# coding: utf-8
-# pylint: disable= arguments-differ
-"""Custom neural network layers in model_zoo."""
-
-__all__ = ['Concurrent', 'HybridConcurrent', 'Identity',
- 'SyncBatchNorm', 'PixelShuffle1D', 'PixelShuffle2D',
- 'PixelShuffle3D']
-
-import warnings
-import uuid
-from .... import ndarray as nd, context
-from ...block import HybridBlock
-from ...nn import Sequential, HybridSequential, BatchNorm
-
-class Concurrent(Sequential):
- """Lays `Block` s concurrently.
-
- This block feeds its input to all children blocks, and
- produce the output by concatenating all the children blocks' outputs
- on the specified axis.
-
- Example::
-
- net = Concurrent()
- net.add(nn.Dense(10, activation='relu'))
- net.add(nn.Dense(20))
- net.add(Identity())
-
- Parameters
- ----------
- axis : int, default -1
- The axis on which to concatenate the outputs.
- """
- def __init__(self, axis=-1):
- super(Concurrent, self).__init__()
- self.axis = axis
-
- def forward(self, x):
- out = []
- for block in self._children.values():
- out.append(block()(x))
- out = nd.concat(*out, dim=self.axis)
- return out
-
-
-class HybridConcurrent(HybridSequential):
- """Lays `HybridBlock` s concurrently.
-
- This block feeds its input to all children blocks, and
- produce the output by concatenating all the children blocks' outputs
- on the specified axis.
-
- Example::
-
- net = HybridConcurrent()
- net.add(nn.Dense(10, activation='relu'))
- net.add(nn.Dense(20))
- net.add(Identity())
-
- Parameters
- ----------
- axis : int, default -1
- The axis on which to concatenate the outputs.
- """
- def __init__(self, axis=-1):
- super(HybridConcurrent, self).__init__()
- self.axis = axis
-
- def hybrid_forward(self, F, x):
- out = []
- for block in self._children.values():
- out.append(block()(x))
- out = F.concat(*out, dim=self.axis)
- return out
-
-
-class Identity(HybridBlock):
- """Block that passes through the input directly.
-
- This block can be used in conjunction with HybridConcurrent
- block for residual connection.
-
- Example::
-
- net = HybridConcurrent()
- net.add(nn.Dense(10, activation='relu'))
- net.add(nn.Dense(20))
- net.add(Identity())
- """
- def __init__(self):
- super(Identity, self).__init__()
-
- def hybrid_forward(self, F, x):
- return x
-
-class SyncBatchNorm(BatchNorm):
- """Cross-GPU Synchronized Batch normalization (SyncBN)
-
- Standard BN [1]_ implementation only normalize the data within each device.
- SyncBN normalizes the input within the whole mini-batch.
- We follow the implementation described in the paper [2]_.
-
- Note: Current implementation of SyncBN does not support FP16 training.
- For FP16 inference, use standard nn.BatchNorm instead of SyncBN.
-
- Parameters
- ----------
- in_channels : int, default 0
- Number of channels (feature maps) in input data. If not specified,
- initialization will be deferred to the first time `forward` is called
- and `in_channels` will be inferred from the shape of input data.
- num_devices : int, default number of visible GPUs
- momentum: float, default 0.9
- Momentum for the moving average.
- epsilon: float, default 1e-5
- Small float added to variance to avoid dividing by zero.
- center: bool, default True
- If True, add offset of `beta` to normalized tensor.
- If False, `beta` is ignored.
- scale: bool, default True
- If True, multiply by `gamma`. If False, `gamma` is not used.
- When the next layer is linear (also e.g. `nn.relu`),
- this can be disabled since the scaling
- will be done by the next layer.
- use_global_stats: bool, default False
- If True, use global moving statistics instead of local batch-norm. This will force
- change batch-norm into a scale shift operator.
- If False, use local batch-norm.
- beta_initializer: str or `Initializer`, default 'zeros'
- Initializer for the beta weight.
- gamma_initializer: str or `Initializer`, default 'ones'
- Initializer for the gamma weight.
- running_mean_initializer: str or `Initializer`, default 'zeros'
- Initializer for the running mean.
- running_variance_initializer: str or `Initializer`, default 'ones'
- Initializer for the running variance.
-
-
- Inputs:
- - **data**: input tensor with arbitrary shape.
- Outputs:
- - **out**: output tensor with the same shape as `data`.
-
- Reference:
- .. [1] Ioffe, Sergey, and Christian Szegedy. "Batch normalization: Accelerating \
- deep network training by reducing internal covariate shift." *ICML 2015*
- .. [2] Hang Zhang, Kristin Dana, Jianping Shi, Zhongyue Zhang, Xiaogang Wang, \
- Ambrish Tyagi, and Amit Agrawal. "Context Encoding for Semantic Segmentation." *CVPR 2018*
- """
- def __init__(self, in_channels=0, num_devices=None, momentum=0.9, epsilon=1e-5,
- center=True, scale=True, use_global_stats=False, beta_initializer='zeros',
- gamma_initializer='ones', running_mean_initializer='zeros',
- running_variance_initializer='ones', **kwargs):
- super(SyncBatchNorm, self).__init__(
- axis=1, momentum=momentum, epsilon=epsilon,
- center=center, scale=scale,
- use_global_stats=use_global_stats,
- beta_initializer=beta_initializer,
- gamma_initializer=gamma_initializer,
- running_mean_initializer=running_mean_initializer,
- running_variance_initializer=running_variance_initializer,
- in_channels=in_channels, **kwargs)
- num_devices = self._get_num_devices() if num_devices is None else num_devices
- self._kwargs = {'eps': epsilon, 'momentum': momentum,
- 'fix_gamma': not scale, 'use_global_stats': use_global_stats,
- 'ndev': num_devices, 'key': uuid.uuid4()}
-
- def _get_num_devices(self):
- warnings.warn("Caution using SyncBatchNorm: "
- "if not using all the GPUs, please mannually set num_devices",
- UserWarning)
- num_devices = context.num_gpus()
- num_devices = num_devices if num_devices > 0 else 1
- return num_devices
-
- def hybrid_forward(self, F, x, gamma, beta, running_mean, running_var):
- return F.contrib.SyncBatchNorm(x, gamma, beta, running_mean, running_var,
- name='fwd', **self._kwargs)
-
-class PixelShuffle1D(HybridBlock):
-
- r"""Pixel-shuffle layer for upsampling in 1 dimension.
-
- Pixel-shuffling is the operation of taking groups of values along
- the *channel* dimension and regrouping them into blocks of pixels
- along the ``W`` dimension, thereby effectively multiplying that dimension
- by a constant factor in size.
-
- For example, a feature map of shape :math:`(fC, W)` is reshaped
- into :math:`(C, fW)` by forming little value groups of size :math:`f`
- and arranging them in a grid of size :math:`W`.
-
- Parameters
- ----------
- factor : int or 1-tuple of int
- Upsampling factor, applied to the ``W`` dimension.
-
- Inputs:
- - **data**: Tensor of shape ``(N, f*C, W)``.
- Outputs:
- - **out**: Tensor of shape ``(N, C, W*f)``.
-
- Examples
- --------
- >>> pxshuf = PixelShuffle1D(2)
- >>> x = mx.nd.zeros((1, 8, 3))
- >>> pxshuf(x).shape
- (1, 4, 6)
- """
-
- def __init__(self, factor):
- super(PixelShuffle1D, self).__init__()
- self._factor = int(factor)
-
- def hybrid_forward(self, F, x):
- """Perform pixel-shuffling on the input."""
- f = self._factor
- # (N, C*f, W)
- x = F.reshape(x, (0, -4, -1, f, 0)) # (N, C, f, W)
- x = F.transpose(x, (0, 1, 3, 2)) # (N, C, W, f)
- x = F.reshape(x, (0, 0, -3)) # (N, C, W*f)
- return x
-
- def __repr__(self):
- return "{}({})".format(self.__class__.__name__, self._factor)
-
-
-class PixelShuffle2D(HybridBlock):
-
- r"""Pixel-shuffle layer for upsampling in 2 dimensions.
-
- Pixel-shuffling is the operation of taking groups of values along
- the *channel* dimension and regrouping them into blocks of pixels
- along the ``H`` and ``W`` dimensions, thereby effectively multiplying
- those dimensions by a constant factor in size.
-
- For example, a feature map of shape :math:`(f^2 C, H, W)` is reshaped
- into :math:`(C, fH, fW)` by forming little :math:`f \times f` blocks
- of pixels and arranging them in an :math:`H \times W` grid.
-
- Pixel-shuffling together with regular convolution is an alternative,
- learnable way of upsampling an image by arbitrary factors. It is reported
- to help overcome checkerboard artifacts that are common in upsampling with
- transposed convolutions (also called deconvolutions). See the paper
- `Real-Time Single Image and Video Super-Resolution Using an Efficient
- Sub-Pixel Convolutional Neural Network <https://arxiv.org/abs/1609.05158>`_
- for further details.
-
- Parameters
- ----------
- factor : int or 2-tuple of int
- Upsampling factors, applied to the ``H`` and ``W`` dimensions,
- in that order.
-
- Inputs:
- - **data**: Tensor of shape ``(N, f1*f2*C, H, W)``.
- Outputs:
- - **out**: Tensor of shape ``(N, C, H*f1, W*f2)``.
-
- Examples
- --------
- >>> pxshuf = PixelShuffle2D((2, 3))
- >>> x = mx.nd.zeros((1, 12, 3, 5))
- >>> pxshuf(x).shape
- (1, 2, 6, 15)
- """
-
- def __init__(self, factor):
- super(PixelShuffle2D, self).__init__()
- try:
- self._factors = (int(factor),) * 2
- except TypeError:
- self._factors = tuple(int(fac) for fac in factor)
- assert len(self._factors) == 2, "wrong length {}".format(len(self._factors))
-
- def hybrid_forward(self, F, x):
- """Perform pixel-shuffling on the input."""
- f1, f2 = self._factors
- # (N, f1*f2*C, H, W)
- x = F.reshape(x, (0, -4, -1, f1 * f2, 0, 0)) # (N, C, f1*f2, H, W)
- x = F.reshape(x, (0, 0, -4, f1, f2, 0, 0)) # (N, C, f1, f2, H, W)
- x = F.transpose(x, (0, 1, 4, 2, 5, 3)) # (N, C, H, f1, W, f2)
- x = F.reshape(x, (0, 0, -3, -3)) # (N, C, H*f1, W*f2)
- return x
-
- def __repr__(self):
- return "{}({})".format(self.__class__.__name__, self._factors)
-
-
-class PixelShuffle3D(HybridBlock):
-
- r"""Pixel-shuffle layer for upsampling in 3 dimensions.
-
- Pixel-shuffling (or voxel-shuffling in 3D) is the operation of taking
- groups of values along the *channel* dimension and regrouping them into
- blocks of voxels along the ``D``, ``H`` and ``W`` dimensions, thereby
- effectively multiplying those dimensions by a constant factor in size.
-
- For example, a feature map of shape :math:`(f^3 C, D, H, W)` is reshaped
- into :math:`(C, fD, fH, fW)` by forming little :math:`f \times f \times f`
- blocks of voxels and arranging them in a :math:`D \times H \times W` grid.
-
- Pixel-shuffling together with regular convolution is an alternative,
- learnable way of upsampling an image by arbitrary factors. It is reported
- to help overcome checkerboard artifacts that are common in upsampling with
- transposed convolutions (also called deconvolutions). See the paper
- `Real-Time Single Image and Video Super-Resolution Using an Efficient
- Sub-Pixel Convolutional Neural Network <https://arxiv.org/abs/1609.05158>`_
- for further details.
-
- Parameters
- ----------
- factor : int or 3-tuple of int
- Upsampling factors, applied to the ``D``, ``H`` and ``W``
- dimensions, in that order.
-
- Inputs:
- - **data**: Tensor of shape ``(N, f1*f2*f3*C, D, H, W)``.
- Outputs:
- - **out**: Tensor of shape ``(N, C, D*f1, H*f2, W*f3)``.
-
- Examples
- --------
- >>> pxshuf = PixelShuffle3D((2, 3, 4))
- >>> x = mx.nd.zeros((1, 48, 3, 5, 7))
- >>> pxshuf(x).shape
- (1, 2, 6, 15, 28)
- """
-
- def __init__(self, factor):
- super(PixelShuffle3D, self).__init__()
- try:
- self._factors = (int(factor),) * 3
- except TypeError:
- self._factors = tuple(int(fac) for fac in factor)
- assert len(self._factors) == 3, "wrong length {}".format(len(self._factors))
-
- def hybrid_forward(self, F, x):
- """Perform pixel-shuffling on the input."""
- # `transpose` doesn't support 8D, need other implementation
- f1, f2, f3 = self._factors
- # (N, C*f1*f2*f3, D, H, W)
- x = F.reshape(x, (0, -4, -1, f1 * f2 * f3, 0, 0, 0)) # (N, C, f1*f2*f3, D, H, W)
- x = F.swapaxes(x, 2, 3) # (N, C, D, f1*f2*f3, H, W)
- x = F.reshape(x, (0, 0, 0, -4, f1, f2*f3, 0, 0)) # (N, C, D, f1, f2*f3, H, W)
- x = F.reshape(x, (0, 0, -3, 0, 0, 0)) # (N, C, D*f1, f2*f3, H, W)
- x = F.swapaxes(x, 3, 4) # (N, C, D*f1, H, f2*f3, W)
- x = F.reshape(x, (0, 0, 0, 0, -4, f2, f3, 0)) # (N, C, D*f1, H, f2, f3, W)
- x = F.reshape(x, (0, 0, 0, -3, 0, 0)) # (N, C, D*f1, H*f2, f3, W)
- x = F.swapaxes(x, 4, 5) # (N, C, D*f1, H*f2, W, f3)
- x = F.reshape(x, (0, 0, 0, 0, -3)) # (N, C, D*f1, H*f2, W*f3)
- return x
-
- def __repr__(self):
- return "{}({})".format(self.__class__.__name__, self._factors)
diff --git a/python/mxnet/gluon/contrib/rnn/__init__.py b/python/mxnet/gluon/contrib/rnn/__init__.py
deleted file mode 100644
index eaa38be..0000000
--- a/python/mxnet/gluon/contrib/rnn/__init__.py
+++ /dev/null
@@ -1,28 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-# coding: utf-8
-# pylint: disable=wildcard-import
-"""Contrib recurrent neural network module."""
-
-from . import conv_rnn_cell, rnn_cell
-
-from .conv_rnn_cell import *
-
-from .rnn_cell import *
-
-__all__ = conv_rnn_cell.__all__ + rnn_cell.__all__
diff --git a/python/mxnet/gluon/contrib/rnn/rnn_cell.py b/python/mxnet/gluon/contrib/rnn/rnn_cell.py
deleted file mode 100644
index 155b6bd..0000000
--- a/python/mxnet/gluon/contrib/rnn/rnn_cell.py
+++ /dev/null
@@ -1,431 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-# coding: utf-8
-"""Definition of various recurrent neural network cells."""
-__all__ = ['VariationalDropoutCell', 'LSTMPCell']
-
-from ...rnn import BidirectionalCell, SequentialRNNCell, ModifierCell, HybridRecurrentCell
-from ...rnn.rnn_cell import _format_sequence, _get_begin_state, _mask_sequence_variable_length
-from ... import tensor_types
-from ...parameter import Parameter
-from ....base import _as_list
-
-class VariationalDropoutCell(ModifierCell):
- """
- Applies Variational Dropout on base cell.
- https://arxiv.org/pdf/1512.05287.pdf
-
- Variational dropout uses the same dropout mask across time-steps. It can be applied to RNN
- inputs, outputs, and states. The masks for them are not shared.
-
- The dropout mask is initialized when stepping forward for the first time and will remain
- the same until .reset() is called. Thus, if using the cell and stepping manually without calling
- .unroll(), the .reset() should be called after each sequence.
-
- Parameters
- ----------
- base_cell : RecurrentCell
- The cell on which to perform variational dropout.
- drop_inputs : float, default 0.
- The dropout rate for inputs. Won't apply dropout if it equals 0.
- drop_states : float, default 0.
- The dropout rate for state inputs on the first state channel.
- Won't apply dropout if it equals 0.
- drop_outputs : float, default 0.
- The dropout rate for outputs. Won't apply dropout if it equals 0.
- """
- def __init__(self, base_cell, drop_inputs=0., drop_states=0., drop_outputs=0.):
- assert not drop_states or not isinstance(base_cell, BidirectionalCell), \
- "BidirectionalCell doesn't support variational state dropout. " \
- "Please add VariationalDropoutCell to the cells underneath instead."
- assert not drop_states \
- or not isinstance(base_cell, SequentialRNNCell) or not base_cell._bidirectional, \
- "Bidirectional SequentialRNNCell doesn't support variational state dropout. " \
- "Please add VariationalDropoutCell to the cells underneath instead."
- super(VariationalDropoutCell, self).__init__(base_cell)
- self.drop_inputs = drop_inputs
- self.drop_states = drop_states
- self.drop_outputs = drop_outputs
- self.drop_inputs_mask = None
- self.drop_states_mask = None
- self.drop_outputs_mask = None
-
- def _alias(self):
- return 'vardrop'
-
- def reset(self):
- super(VariationalDropoutCell, self).reset()
- self.drop_inputs_mask = None
- self.drop_states_mask = None
- self.drop_outputs_mask = None
-
- def _initialize_input_masks(self, F, inputs, states):
- if self.drop_states and self.drop_states_mask is None:
- self.drop_states_mask = F.Dropout(F.ones_like(states[0]),
- p=self.drop_states)
-
- if self.drop_inputs and self.drop_inputs_mask is None:
- self.drop_inputs_mask = F.Dropout(F.ones_like(inputs),
- p=self.drop_inputs)
-
- def _initialize_output_mask(self, F, output):
- if self.drop_outputs and self.drop_outputs_mask is None:
- self.drop_outputs_mask = F.Dropout(F.ones_like(output),
- p=self.drop_outputs)
-
-
- def hybrid_forward(self, F, inputs, states):
- cell = self.base_cell
- self._initialize_input_masks(F, inputs, states)
-
- if self.drop_states:
- states = list(states)
- # state dropout only needs to be applied on h, which is always the first state.
- states[0] = states[0] * self.drop_states_mask
-
- if self.drop_inputs:
- inputs = inputs * self.drop_inputs_mask
-
- next_output, next_states = cell(inputs, states)
-
- self._initialize_output_mask(F, next_output)
- if self.drop_outputs:
- next_output = next_output * self.drop_outputs_mask
-
- return next_output, next_states
-
- def __repr__(self):
- s = '{name}(p_out = {drop_outputs}, p_state = {drop_states})'
- return s.format(name=self.__class__.__name__,
- **self.__dict__)
-
- def unroll(self, length, inputs, begin_state=None, layout='NTC', merge_outputs=None,
- valid_length=None):
- """Unrolls an RNN cell across time steps.
-
- Parameters
- ----------
- length : int
- Number of steps to unroll.
- inputs : Symbol, list of Symbol, or None
- If `inputs` is a single Symbol (usually the output
- of Embedding symbol), it should have shape
- (batch_size, length, ...) if `layout` is 'NTC',
- or (length, batch_size, ...) if `layout` is 'TNC'.
-
- If `inputs` is a list of symbols (usually output of
- previous unroll), they should all have shape
- (batch_size, ...).
- begin_state : nested list of Symbol, optional
- Input states created by `begin_state()`
- or output state of another cell.
- Created from `begin_state()` if `None`.
- layout : str, optional
- `layout` of input symbol. Only used if inputs
- is a single Symbol.
- merge_outputs : bool, optional
- If `False`, returns outputs as a list of Symbols.
- If `True`, concatenates output across time steps
- and returns a single symbol with shape
- (batch_size, length, ...) if layout is 'NTC',
- or (length, batch_size, ...) if layout is 'TNC'.
- If `None`, output whatever is faster.
- valid_length : Symbol, NDArray or None
- `valid_length` specifies the length of the sequences in the batch without padding.
- This option is especially useful for building sequence-to-sequence models where
- the input and output sequences would potentially be padded.
- If `valid_length` is None, all sequences are assumed to have the same length.
- If `valid_length` is a Symbol or NDArray, it should have shape (batch_size,).
- The ith element will be the length of the ith sequence in the batch.
- The last valid state will be return and the padded outputs will be masked with 0.
- Note that `valid_length` must be smaller or equal to `length`.
-
- Returns
- -------
- outputs : list of Symbol or Symbol
- Symbol (if `merge_outputs` is True) or list of Symbols
- (if `merge_outputs` is False) corresponding to the output from
- the RNN from this unrolling.
-
- states : list of Symbol
- The new state of this RNN after this unrolling.
- The type of this symbol is same as the output of `begin_state()`.
- """
-
- # Dropout on inputs and outputs can be performed on the whole sequence
- # only when state dropout is not present.
- if self.drop_states:
- return super(VariationalDropoutCell, self).unroll(length, inputs, begin_state,
- layout, merge_outputs,
- valid_length=valid_length)
-
- self.reset()
-
- inputs, axis, F, batch_size = _format_sequence(length, inputs, layout, True)
- states = _get_begin_state(self, F, begin_state, inputs, batch_size)
-
- if self.drop_inputs:
- inputs = F.Dropout(inputs, p=self.drop_inputs, axes=(axis,))
-
- outputs, states = self.base_cell.unroll(length, inputs, states, layout, merge_outputs=True,
- valid_length=valid_length)
- if self.drop_outputs:
- outputs = F.Dropout(outputs, p=self.drop_outputs, axes=(axis,))
- merge_outputs = isinstance(outputs, tensor_types) if merge_outputs is None else \
- merge_outputs
- outputs, _, _, _ = _format_sequence(length, outputs, layout, merge_outputs)
- if valid_length is not None:
- outputs = _mask_sequence_variable_length(F, outputs, length, valid_length, axis,
- merge_outputs)
- return outputs, states
-
-
-class LSTMPCell(HybridRecurrentCell):
- r"""Long-Short Term Memory Projected (LSTMP) network cell.
- (https://arxiv.org/abs/1402.1128)
-
- Each call computes the following function:
-
- .. math::
- \begin{array}{ll}
- i_t = sigmoid(W_{ii} x_t + b_{ii} + W_{ri} r_{(t-1)} + b_{ri}) \\
- f_t = sigmoid(W_{if} x_t + b_{if} + W_{rf} r_{(t-1)} + b_{rf}) \\
- g_t = \tanh(W_{ig} x_t + b_{ig} + W_{rc} r_{(t-1)} + b_{rg}) \\
- o_t = sigmoid(W_{io} x_t + b_{io} + W_{ro} r_{(t-1)} + b_{ro}) \\
- c_t = f_t * c_{(t-1)} + i_t * g_t \\
- h_t = o_t * \tanh(c_t) \\
- r_t = W_{hr} h_t
- \end{array}
-
- where :math:`r_t` is the projected recurrent activation at time `t`,
- :math:`h_t` is the hidden state at time `t`, :math:`c_t` is the
- cell state at time `t`, :math:`x_t` is the input at time `t`, and :math:`i_t`,
- :math:`f_t`, :math:`g_t`, :math:`o_t` are the input, forget, cell, and
- out gates, respectively.
-
- Parameters
- ----------
-
- hidden_size : int
- Number of units in cell state symbol.
- projection_size : int
- Number of units in output symbol.
- i2h_weight_initializer : str or Initializer
- Initializer for the input weights matrix, used for the linear
- transformation of the inputs.
- h2h_weight_initializer : str or Initializer
- Initializer for the recurrent weights matrix, used for the linear
- transformation of the hidden state.
- h2r_weight_initializer : str or Initializer
- Initializer for the projection weights matrix, used for the linear
- transformation of the recurrent state.
- i2h_bias_initializer : str or Initializer, default 'lstmbias'
- Initializer for the bias vector. By default, bias for the forget
- gate is initialized to 1 while all other biases are initialized
- to zero.
- h2h_bias_initializer : str or Initializer
- Initializer for the bias vector.
- Inputs:
- - **data**: input tensor with shape `(batch_size, input_size)`.
- - **states**: a list of two initial recurrent state tensors, with shape
- `(batch_size, projection_size)` and `(batch_size, hidden_size)` respectively.
- Outputs:
- - **out**: output tensor with shape `(batch_size, num_hidden)`.
- - **next_states**: a list of two output recurrent state tensors. Each has
- the same shape as `states`.
- """
- def __init__(self, hidden_size, projection_size,
- i2h_weight_initializer=None, h2h_weight_initializer=None,
- h2r_weight_initializer=None,
- i2h_bias_initializer='zeros', h2h_bias_initializer='zeros',
- input_size=0):
- super(LSTMPCell, self).__init__()
-
- self._hidden_size = hidden_size
- self._input_size = input_size
- self._projection_size = projection_size
- self.i2h_weight = Parameter('i2h_weight', shape=(4*hidden_size, input_size),
- init=i2h_weight_initializer,
- allow_deferred_init=True)
- self.h2h_weight = Parameter('h2h_weight', shape=(4*hidden_size, projection_size),
- init=h2h_weight_initializer,
- allow_deferred_init=True)
- self.h2r_weight = Parameter('h2r_weight', shape=(projection_size, hidden_size),
- init=h2r_weight_initializer,
- allow_deferred_init=True)
- self.i2h_bias = Parameter('i2h_bias', shape=(4*hidden_size,),
- init=i2h_bias_initializer,
- allow_deferred_init=True)
- self.h2h_bias = Parameter('h2h_bias', shape=(4*hidden_size,),
- init=h2h_bias_initializer,
- allow_deferred_init=True)
-
- def state_info(self, batch_size=0):
- return [{'shape': (batch_size, self._projection_size), '__layout__': 'NC'},
- {'shape': (batch_size, self._hidden_size), '__layout__': 'NC'}]
-
- def _alias(self):
- return 'lstmp'
-
- def __repr__(self):
- s = '{name}({mapping})'
- shape = self.i2h_weight.shape
- proj_shape = self.h2r_weight.shape
- mapping = '{0} -> {1} -> {2}'.format(shape[1] if shape[1] else None,
- shape[0], proj_shape[0])
- return s.format(name=self.__class__.__name__,
- mapping=mapping,
- **self.__dict__)
-
- # pylint: disable= arguments-differ
- def hybrid_forward(self, F, inputs, states, i2h_weight,
- h2h_weight, h2r_weight, i2h_bias, h2h_bias):
- prefix = 't%d_'%self._counter
- i2h = F.FullyConnected(data=inputs, weight=i2h_weight, bias=i2h_bias,
- num_hidden=self._hidden_size*4, name=prefix+'i2h')
- h2h = F.FullyConnected(data=states[0], weight=h2h_weight, bias=h2h_bias,
- num_hidden=self._hidden_size*4, name=prefix+'h2h')
- gates = i2h + h2h
- slice_gates = F.SliceChannel(gates, num_outputs=4, name=prefix+'slice')
- in_gate = F.Activation(slice_gates[0], act_type="sigmoid", name=prefix+'i')
- forget_gate = F.Activation(slice_gates[1], act_type="sigmoid", name=prefix+'f')
- in_transform = F.Activation(slice_gates[2], act_type="tanh", name=prefix+'c')
- out_gate = F.Activation(slice_gates[3], act_type="sigmoid", name=prefix+'o')
- next_c = F.elemwise_add(forget_gate * states[1], in_gate * in_transform,
- name=prefix+'state')
- hidden = F.elemwise_mul(out_gate, F.Activation(next_c, act_type="tanh"),
- name=prefix+'hidden')
- next_r = F.FullyConnected(data=hidden, num_hidden=self._projection_size,
- weight=h2r_weight, no_bias=True, name=prefix+'out')
-
- return next_r, [next_r, next_c]
- # pylint: enable= arguments-differ
-
-
-def dynamic_unroll(cell, inputs, begin_state, drop_inputs=0, drop_outputs=0,
- layout='TNC', valid_length=None):
- """Unrolls an RNN cell across time steps.
-
- Currently, 'TNC' is a preferred layout. unroll on the input of this layout
- runs much faster.
-
- Parameters
- ----------
- cell : an object whose base class is RNNCell.
- The RNN cell to run on the input sequence.
- inputs : Symbol
- It should have shape (batch_size, length, ...) if `layout` is 'NTC',
- or (length, batch_size, ...) if `layout` is 'TNC'.
- begin_state : nested list of Symbol
- The initial states of the RNN sequence.
- drop_inputs : float, default 0.
- The dropout rate for inputs. Won't apply dropout if it equals 0.
- drop_outputs : float, default 0.
- The dropout rate for outputs. Won't apply dropout if it equals 0.
- layout : str, optional
- `layout` of input symbol. Only used if inputs
- is a single Symbol.
- valid_length : Symbol, NDArray or None
- `valid_length` specifies the length of the sequences in the batch without padding.
- This option is especially useful for building sequence-to-sequence models where
- the input and output sequences would potentially be padded.
- If `valid_length` is None, all sequences are assumed to have the same length.
- If `valid_length` is a Symbol or NDArray, it should have shape (batch_size,).
- The ith element will be the length of the ith sequence in the batch.
- The last valid state will be return and the padded outputs will be masked with 0.
- Note that `valid_length` must be smaller or equal to `length`.
-
- Returns
- -------
- outputs : Symbol
- the output of the RNN from this unrolling.
-
- states : list of Symbol
- The new state of this RNN after this unrolling.
- The type of this symbol is same as the output of `begin_state`.
-
- Examples
- --------
- >>> seq_len = 3
- >>> batch_size = 2
- >>> input_size = 5
- >>> cell = mx.gluon.rnn.LSTMCell(input_size)
- >>> cell.initialize(ctx=mx.cpu())
- >>> rnn_data = mx.nd.normal(loc=0, scale=1, shape=(seq_len, batch_size, input_size))
- >>> state_shape = (batch_size, input_size)
- >>> states = [mx.nd.normal(loc=0, scale=1, shape=state_shape) for i in range(2)]
- >>> valid_length = mx.nd.array([2, 3])
- >>> output, states = mx.gluon.contrib.rnn.rnn_cell.dynamic_unroll(cell, rnn_data, states,
- valid_length=valid_length,
- layout='TNC')
- >>> print(output)
- [[[ 0.00767238 0.00023103 0.03973929 -0.00925503 -0.05660512]
- [ 0.00881535 0.05428379 -0.02493718 -0.01834097 0.02189514]]
- [[-0.00676967 0.01447039 0.01287002 -0.00574152 -0.05734247]
- [ 0.01568508 0.02650866 -0.04270559 -0.04328435 0.00904011]]
- [[ 0. 0. 0. 0. 0. ]
- [ 0.01055336 0.02734251 -0.03153727 -0.03742751 -0.01378113]]]
- <NDArray 3x2x5 @cpu(0)>
- """
-
- # Merge is always True, so we don't need length.
- inputs, axis, F, _ = _format_sequence(0, inputs, layout, True)
- if axis != 0:
- axes = list(range(len(layout)))
- tmp = axes[0]
- axes[0] = axes[axis]
- axes[axis] = tmp
- inputs = F.transpose(inputs, axes=axes)
- states = begin_state
-
- if drop_inputs:
- inputs = F.Dropout(inputs, p=drop_inputs, axes=(axis,))
-
- if valid_length is None:
- def loop_body(inputs, states):
- return cell(inputs, states)
- else:
- zeros = []
- for s in states:
- zeros.append(F.zeros_like(s))
- states = list(_as_list(states))
- states.append(F.zeros((1)))
- def loop_body(inputs, states):
- cell_states = states[:-1]
- iter_no = states[-1]
- out, new_states = cell(inputs, cell_states)
- for i, state in enumerate(cell_states):
- new_states[i] = F.where(F.broadcast_greater(valid_length, iter_no),
- new_states[i], state)
- new_states.append(iter_no + 1)
- return out, new_states
-
- outputs, states = F.contrib.foreach(loop_body, inputs, states)
- if drop_outputs:
- outputs = F.Dropout(outputs, p=drop_outputs, axes=(axis,))
- if valid_length is not None:
- if axis != 0:
- outputs = F.transpose(outputs, axes)
- outputs = F.SequenceMask(outputs, sequence_length=valid_length,
- use_sequence_length=True, axis=axis)
- # the last state is the iteration number. We don't need it.
- return outputs, states[:-1]
- else:
- if axis != 0:
- outputs = F.transpose(outputs, axes)
- return outputs, states
diff --git a/python/mxnet/gluon/data/sampler.py b/python/mxnet/gluon/data/sampler.py
index f53e636..143f54e 100644
--- a/python/mxnet/gluon/data/sampler.py
+++ b/python/mxnet/gluon/data/sampler.py
@@ -18,7 +18,8 @@
# coding: utf-8
# pylint: disable=
"""Dataset sampler."""
-__all__ = ['Sampler', 'SequentialSampler', 'RandomSampler', 'FilterSampler', 'BatchSampler']
+__all__ = ['Sampler', 'SequentialSampler', 'RandomSampler', 'FilterSampler', 'BatchSampler',
+ 'IntervalSampler']
import numpy as np
@@ -159,3 +160,43 @@ class BatchSampler(Sampler):
raise ValueError(
"last_batch must be one of 'keep', 'discard', or 'rollover', " \
"but got %s"%self._last_batch)
+
+
+class IntervalSampler(Sampler):
+ """Samples elements from [0, length) at fixed intervals.
+
+ Parameters
+ ----------
+ length : int
+ Length of the sequence.
+ interval : int
+ The number of items to skip between two samples.
+ rollover : bool, default True
+ Whether to start again from the first skipped item after reaching the end.
+ If true, this sampler would start again from the first skipped item until all items
+ are visited.
+ Otherwise, iteration stops when end is reached and skipped items are ignored.
+
+ Examples
+ --------
+ >>> sampler = contrib.data.IntervalSampler(13, interval=3)
+ >>> list(sampler)
+ [0, 3, 6, 9, 12, 1, 4, 7, 10, 2, 5, 8, 11]
+ >>> sampler = contrib.data.IntervalSampler(13, interval=3, rollover=False)
+ >>> list(sampler)
+ [0, 3, 6, 9, 12]
+ """
+ def __init__(self, length, interval, rollover=True):
+ assert interval <= length, \
+ "Interval {} must be smaller than or equal to length {}".format(interval, length)
+ self._length = length
+ self._interval = interval
+ self._rollover = rollover
+
+ def __iter__(self):
+ for i in range(self._interval if self._rollover else 1):
+ for j in range(i, self._length, self._interval):
+ yield j
+
+ def __len__(self):
+ return self._length
diff --git a/python/mxnet/gluon/model_zoo/vision/densenet.py b/python/mxnet/gluon/model_zoo/vision/densenet.py
index 51779b2..21d984d 100644
--- a/python/mxnet/gluon/model_zoo/vision/densenet.py
+++ b/python/mxnet/gluon/model_zoo/vision/densenet.py
@@ -25,7 +25,6 @@ import os
from ....context import cpu
from ...block import HybridBlock
from ... import nn
-from ...contrib.nn import HybridConcurrent, Identity
from .... import base
# Helpers
@@ -46,8 +45,8 @@ def _make_dense_layer(growth_rate, bn_size, dropout):
if dropout:
new_features.add(nn.Dropout(dropout))
- out = HybridConcurrent(axis=1)
- out.add(Identity())
+ out = nn.HybridConcatenate(axis=1)
+ out.add(nn.Identity())
out.add(new_features)
return out
diff --git a/python/mxnet/gluon/model_zoo/vision/inception.py b/python/mxnet/gluon/model_zoo/vision/inception.py
index b13b0ac..c2db7f9 100644
--- a/python/mxnet/gluon/model_zoo/vision/inception.py
+++ b/python/mxnet/gluon/model_zoo/vision/inception.py
@@ -25,7 +25,6 @@ import os
from ....context import cpu
from ...block import HybridBlock
from ... import nn
-from ...contrib.nn import HybridConcurrent
from .... import base
# Helpers
@@ -52,7 +51,7 @@ def _make_branch(use_pool, *conv_settings):
return out
def _make_A(pool_features):
- out = HybridConcurrent(axis=1)
+ out = nn.HybridConcatenate(axis=1)
out.add(_make_branch(None,
(64, 1, None, None)))
out.add(_make_branch(None,
@@ -67,7 +66,7 @@ def _make_A(pool_features):
return out
def _make_B():
- out = HybridConcurrent(axis=1)
+ out = nn.HybridConcatenate(axis=1)
out.add(_make_branch(None,
(384, 3, 2, None)))
out.add(_make_branch(None,
@@ -78,7 +77,7 @@ def _make_B():
return out
def _make_C(channels_7x7):
- out = HybridConcurrent(axis=1)
+ out = nn.HybridConcatenate(axis=1)
out.add(_make_branch(None,
(192, 1, None, None)))
out.add(_make_branch(None,
@@ -96,7 +95,7 @@ def _make_C(channels_7x7):
return out
def _make_D():
- out = HybridConcurrent(axis=1)
+ out = nn.HybridConcatenate(axis=1)
out.add(_make_branch(None,
(192, 1, None, None),
(320, 3, 2, None)))
@@ -109,7 +108,7 @@ def _make_D():
return out
def _make_E():
- out = HybridConcurrent(axis=1)
+ out = nn.HybridConcatenate(axis=1)
out.add(_make_branch(None,
(320, 1, None, None)))
@@ -117,7 +116,7 @@ def _make_E():
out.add(branch_3x3)
branch_3x3.add(_make_branch(None,
(384, 1, None, None)))
- branch_3x3_split = HybridConcurrent(axis=1)
+ branch_3x3_split = nn.HybridConcatenate(axis=1)
branch_3x3_split.add(_make_branch(None,
(384, (1, 3), None, (0, 1))))
branch_3x3_split.add(_make_branch(None,
@@ -129,7 +128,7 @@ def _make_E():
branch_3x3dbl.add(_make_branch(None,
(448, 1, None, None),
(384, 3, None, 1)))
- branch_3x3dbl_split = HybridConcurrent(axis=1)
+ branch_3x3dbl_split = nn.HybridConcatenate(axis=1)
branch_3x3dbl.add(branch_3x3dbl_split)
branch_3x3dbl_split.add(_make_branch(None,
(384, (1, 3), None, (0, 1))))
diff --git a/python/mxnet/gluon/model_zoo/vision/squeezenet.py b/python/mxnet/gluon/model_zoo/vision/squeezenet.py
index 81d1e9a..6d3336c 100644
--- a/python/mxnet/gluon/model_zoo/vision/squeezenet.py
+++ b/python/mxnet/gluon/model_zoo/vision/squeezenet.py
@@ -25,7 +25,6 @@ import os
from ....context import cpu
from ...block import HybridBlock
from ... import nn
-from ...contrib.nn import HybridConcurrent
from .... import base
# Helpers
@@ -33,7 +32,7 @@ def _make_fire(squeeze_channels, expand1x1_channels, expand3x3_channels):
out = nn.HybridSequential()
out.add(_make_fire_conv(squeeze_channels, 1))
- paths = HybridConcurrent(axis=1)
+ paths = nn.HybridConcatenate(axis=1)
paths.add(_make_fire_conv(expand1x1_channels, 1))
paths.add(_make_fire_conv(expand3x3_channels, 3, 1))
out.add(paths)
diff --git a/python/mxnet/gluon/nn/basic_layers.py b/python/mxnet/gluon/nn/basic_layers.py
index 5973bf0..0cc192a 100644
--- a/python/mxnet/gluon/nn/basic_layers.py
+++ b/python/mxnet/gluon/nn/basic_layers.py
@@ -19,15 +19,16 @@
# pylint: disable= arguments-differ
"""Basic neural network layers."""
__all__ = ['Sequential', 'HybridSequential', 'Dense', 'Dropout', 'Embedding',
- 'BatchNorm', 'BatchNormReLU', 'InstanceNorm', 'LayerNorm', 'GroupNorm',
- 'Flatten', 'Lambda', 'HybridLambda']
+ 'BatchNorm', 'SyncBatchNorm', 'BatchNormReLU', 'InstanceNorm', 'LayerNorm', 'GroupNorm',
+ 'Flatten', 'Lambda', 'HybridLambda', 'Concatenate', 'HybridConcatenate', 'Identity']
import warnings
+import uuid
import numpy as np
from .activations import Activation
from ..block import Block, HybridBlock
from ..utils import _indent
-from ... import ndarray as nd, symbol as sym
+from ... import ndarray as nd, symbol as sym, context
from ...util import is_np_array
from ..parameter import Parameter
@@ -940,3 +941,176 @@ class HybridLambda(HybridBlock):
def __repr__(self):
return '{name}({function})'.format(name=self.__class__.__name__,
function=self._func_name)
+
+
+class Concatenate(Sequential):
+ """Lays `Block` s concurrently.
+
+ This block feeds its input to all children blocks, and
+ produce the output by concatenating all the children blocks' outputs
+ on the specified axis.
+
+ Example::
+
+ net = Concatenate()
+ net.add(nn.Dense(10, activation='relu'))
+ net.add(nn.Dense(20))
+ net.add(Identity())
+
+ Parameters
+ ----------
+ axis : int, default -1
+ The axis on which to concatenate the outputs.
+ """
+ def __init__(self, axis=-1):
+ super(Concatenate, self).__init__()
+ self.axis = axis
+
+ def forward(self, x):
+ out = []
+ for block in self._children.values():
+ out.append(block()(x))
+ if is_np_array():
+ out = np.concatenate(out, axis=self.axis)
+ else:
+ out = nd.concat(*out, dim=self.axis)
+ return out
+
+
+class HybridConcatenate(HybridSequential):
+ """Lays `HybridBlock` s concurrently.
+
+ This block feeds its input to all children blocks, and
+ produce the output by concatenating all the children blocks' outputs
+ on the specified axis.
+
+ Example::
+
+ net = HybridConcatenate()
+ net.add(nn.Dense(10, activation='relu'))
+ net.add(nn.Dense(20))
+ net.add(Identity())
+
+ Parameters
+ ----------
+ axis : int, default -1
+ The axis on which to concatenate the outputs.
+ """
+ def __init__(self, axis=-1):
+ super(HybridConcatenate, self).__init__()
+ self.axis = axis
+
+ def hybrid_forward(self, F, x):
+ out = []
+ for block in self._children.values():
+ out.append(block()(x))
+ if is_np_array():
+ out = F.np.concatenate(out, axis=self.axis)
+ else:
+ out = F.concat(*out, dim=self.axis)
+ return out
+
+
+class Identity(HybridBlock):
+ """Block that passes through the input directly.
+
+ This block can be used in conjunction with HybridConcatenate
+ block for residual connection.
+
+ Example::
+
+ net = HybridConcatenate()
+ net.add(nn.Dense(10, activation='relu'))
+ net.add(nn.Dense(20))
+ net.add(Identity())
+ """
+ def __init__(self):
+ super(Identity, self).__init__()
+
+ def hybrid_forward(self, F, x):
+ return x
+
+
+class SyncBatchNorm(BatchNorm):
+ """Cross-GPU Synchronized Batch normalization (SyncBN)
+
+ Standard BN [1]_ implementation only normalize the data within each device.
+ SyncBN normalizes the input within the whole mini-batch.
+ We follow the implementation described in the paper [2]_.
+
+ Note: Current implementation of SyncBN does not support FP16 training.
+ For FP16 inference, use standard nn.BatchNorm instead of SyncBN.
+
+ Parameters
+ ----------
+ in_channels : int, default 0
+ Number of channels (feature maps) in input data. If not specified,
+ initialization will be deferred to the first time `forward` is called
+ and `in_channels` will be inferred from the shape of input data.
+ num_devices : int, default number of visible GPUs
+ momentum: float, default 0.9
+ Momentum for the moving average.
+ epsilon: float, default 1e-5
+ Small float added to variance to avoid dividing by zero.
+ center: bool, default True
+ If True, add offset of `beta` to normalized tensor.
+ If False, `beta` is ignored.
+ scale: bool, default True
+ If True, multiply by `gamma`. If False, `gamma` is not used.
+ When the next layer is linear (also e.g. `nn.relu`),
+ this can be disabled since the scaling
+ will be done by the next layer.
+ use_global_stats: bool, default False
+ If True, use global moving statistics instead of local batch-norm. This will force
+ change batch-norm into a scale shift operator.
+ If False, use local batch-norm.
+ beta_initializer: str or `Initializer`, default 'zeros'
+ Initializer for the beta weight.
+ gamma_initializer: str or `Initializer`, default 'ones'
+ Initializer for the gamma weight.
+ running_mean_initializer: str or `Initializer`, default 'zeros'
+ Initializer for the running mean.
+ running_variance_initializer: str or `Initializer`, default 'ones'
+ Initializer for the running variance.
+
+
+ Inputs:
+ - **data**: input tensor with arbitrary shape.
+ Outputs:
+ - **out**: output tensor with the same shape as `data`.
+
+ Reference:
+ .. [1] Ioffe, Sergey, and Christian Szegedy. "Batch normalization: Accelerating \
+ deep network training by reducing internal covariate shift." *ICML 2015*
+ .. [2] Hang Zhang, Kristin Dana, Jianping Shi, Zhongyue Zhang, Xiaogang Wang, \
+ Ambrish Tyagi, and Amit Agrawal. "Context Encoding for Semantic Segmentation." *CVPR 2018*
+ """
+ def __init__(self, in_channels=0, num_devices=None, momentum=0.9, epsilon=1e-5,
+ center=True, scale=True, use_global_stats=False, beta_initializer='zeros',
+ gamma_initializer='ones', running_mean_initializer='zeros',
+ running_variance_initializer='ones', **kwargs):
+ super(SyncBatchNorm, self).__init__(
+ axis=1, momentum=momentum, epsilon=epsilon,
+ center=center, scale=scale,
+ use_global_stats=use_global_stats,
+ beta_initializer=beta_initializer,
+ gamma_initializer=gamma_initializer,
+ running_mean_initializer=running_mean_initializer,
+ running_variance_initializer=running_variance_initializer,
+ in_channels=in_channels, **kwargs)
+ num_devices = self._get_num_devices() if num_devices is None else num_devices
+ self._kwargs = {'eps': epsilon, 'momentum': momentum,
+ 'fix_gamma': not scale, 'use_global_stats': use_global_stats,
+ 'ndev': num_devices, 'key': uuid.uuid4()}
+
+ def _get_num_devices(self):
+ warnings.warn("Caution using SyncBatchNorm: "
+ "if not using all the GPUs, please mannually set num_devices",
+ UserWarning)
+ num_devices = context.num_gpus()
+ num_devices = num_devices if num_devices > 0 else 1
+ return num_devices
+
+ def hybrid_forward(self, F, x, gamma, beta, running_mean, running_var):
+ return F.contrib.SyncBatchNorm(x, gamma, beta, running_mean, running_var,
+ name='fwd', **self._kwargs)
diff --git a/python/mxnet/gluon/nn/conv_layers.py b/python/mxnet/gluon/nn/conv_layers.py
index 1ed0ae4..fd29327 100644
--- a/python/mxnet/gluon/nn/conv_layers.py
+++ b/python/mxnet/gluon/nn/conv_layers.py
@@ -24,14 +24,15 @@ __all__ = ['Conv1D', 'Conv2D', 'Conv3D',
'AvgPool1D', 'AvgPool2D', 'AvgPool3D',
'GlobalMaxPool1D', 'GlobalMaxPool2D', 'GlobalMaxPool3D',
'GlobalAvgPool1D', 'GlobalAvgPool2D', 'GlobalAvgPool3D',
- 'ReflectionPad2D']
+ 'ReflectionPad2D', 'DeformableConvolution', 'ModulatedDeformableConvolution',
+ 'PixelShuffle1D', 'PixelShuffle2D', 'PixelShuffle3D']
from ..block import HybridBlock
from ..parameter import Parameter
from ... import symbol
from ...base import numeric_types
from .activations import Activation
-from ...util import is_np_array
+from ...util import is_np_array, np_array
def _infer_weight_shape(op_name, data_shape, kwargs):
@@ -84,7 +85,7 @@ class _Conv(HybridBlock):
initialization will be deferred to the first time `forward` is called
and `in_channels` will be inferred from the shape of input data.
activation : str
- Activation function to use. See :func:`~mxnet.ndarray.Activation`.
+ Activation function to use. See :func:`~mxnet.npx.activation`.
If you don't specify anything, no activation is applied
(ie. "linear" activation: `a(x) = x`).
use_bias: bool
@@ -218,7 +219,7 @@ class Conv1D(_Conv):
initialization will be deferred to the first time `forward` is called
and `in_channels` will be inferred from the shape of input data.
activation : str
- Activation function to use. See :func:`~mxnet.ndarray.Activation`.
+ Activation function to use. See :func:`~mxnet.npx.activation`.
If you don't specify anything, no activation is applied
(ie. "linear" activation: `a(x) = x`).
use_bias : bool
@@ -299,7 +300,7 @@ class Conv2D(_Conv):
initialization will be deferred to the first time `forward` is called
and `in_channels` will be inferred from the shape of input data.
activation : str
- Activation function to use. See :func:`~mxnet.ndarray.Activation`.
+ Activation function to use. See :func:`~mxnet.npx.activation`.
If you don't specify anything, no activation is applied
(ie. "linear" activation: `a(x) = x`).
use_bias : bool
@@ -383,7 +384,7 @@ class Conv3D(_Conv):
initialization will be deferred to the first time `forward` is called
and `in_channels` will be inferred from the shape of input data.
activation : str
- Activation function to use. See :func:`~mxnet.ndarray.Activation`.
+ Activation function to use. See :func:`~mxnet.npx.activation`.
If you don't specify anything, no activation is applied
(ie. "linear" activation: `a(x) = x`).
use_bias : bool
@@ -472,7 +473,7 @@ class Conv1DTranspose(_Conv):
initialization will be deferred to the first time `forward` is called
and `in_channels` will be inferred from the shape of input data.
activation : str
- Activation function to use. See :func:`~mxnet.ndarray.Activation`.
+ Activation function to use. See :func:`~mxnet.npx.activation`.
If you don't specify anything, no activation is applied
(ie. "linear" activation: `a(x) = x`).
use_bias : bool
@@ -563,7 +564,7 @@ class Conv2DTranspose(_Conv):
initialization will be deferred to the first time `forward` is called
and `in_channels` will be inferred from the shape of input data.
activation : str
- Activation function to use. See :func:`~mxnet.ndarray.Activation`.
+ Activation function to use. See :func:`~mxnet.npx.activation`.
If you don't specify anything, no activation is applied
(ie. "linear" activation: `a(x) = x`).
use_bias : bool
@@ -657,7 +658,7 @@ class Conv3DTranspose(_Conv):
initialization will be deferred to the first time `forward` is called
and `in_channels` will be inferred from the shape of input data.
activation : str
- Activation function to use. See :func:`~mxnet.ndarray.Activation`.
+ Activation function to use. See :func:`~mxnet.npx.activation`.
If you don't specify anything, no activation is applied
(ie. "linear" activation: `a(x) = x`).
use_bias : bool
@@ -1236,3 +1237,575 @@ class ReflectionPad2D(HybridBlock):
def hybrid_forward(self, F, x):
return F.pad(x, mode='reflect', pad_width=self._padding)
+
+
+class DeformableConvolution(HybridBlock):
+ """2-D Deformable Convolution v_1 (Dai, 2017).
+ Normal Convolution uses sampling points in a regular grid, while the sampling
+ points of Deformablem Convolution can be offset. The offset is learned with a
+ separate convolution layer during the training. Both the convolution layer for
+ generating the output features and the offsets are included in this gluon layer.
+
+ Parameters
+ ----------
+ channels : int,
+ The dimensionality of the output space
+ i.e. the number of output channels in the convolution.
+ kernel_size : int or tuple/list of 2 ints, (Default value = (1,1))
+ Specifies the dimensions of the convolution window.
+ strides : int or tuple/list of 2 ints, (Default value = (1,1))
+ Specifies the strides of the convolution.
+ padding : int or tuple/list of 2 ints, (Default value = (0,0))
+ If padding is non-zero, then the input is implicitly zero-padded
+ on both sides for padding number of points.
+ dilation : int or tuple/list of 2 ints, (Default value = (1,1))
+ Specifies the dilation rate to use for dilated convolution.
+ groups : int, (Default value = 1)
+ Controls the connections between inputs and outputs.
+ At groups=1, all inputs are convolved to all outputs.
+ At groups=2, the operation becomes equivalent to having two convolution
+ layers side by side, each seeing half the input channels, and producing
+ half the output channels, and both subsequently concatenated.
+ num_deformable_group : int, (Default value = 1)
+ Number of deformable group partitions.
+ layout : str, (Default value = NCHW)
+ Dimension ordering of data and weight. Can be 'NCW', 'NWC', 'NCHW',
+ 'NHWC', 'NCDHW', 'NDHWC', etc. 'N', 'C', 'H', 'W', 'D' stands for
+ batch, channel, height, width and depth dimensions respectively.
+ Convolution is performed over 'D', 'H', and 'W' dimensions.
+ use_bias : bool, (Default value = True)
+ Whether the layer for generating the output features uses a bias vector.
+ in_channels : int, (Default value = 0)
+ The number of input channels to this layer. If not specified,
+ initialization will be deferred to the first time `forward` is called
+ and input channels will be inferred from the shape of input data.
+ activation : str, (Default value = None)
+ Activation function to use. See :func:`~mxnet.npx.activation`.
+ If you don't specify anything, no activation is applied
+ (ie. "linear" activation: `a(x) = x`).
+ weight_initializer : str or `Initializer`, (Default value = None)
+ Initializer for the `weight` weights matrix for the convolution layer
+ for generating the output features.
+ bias_initializer : str or `Initializer`, (Default value = zeros)
+ Initializer for the bias vector for the convolution layer
+ for generating the output features.
+ offset_weight_initializer : str or `Initializer`, (Default value = zeros)
+ Initializer for the `weight` weights matrix for the convolution layer
+ for generating the offset.
+ offset_bias_initializer : str or `Initializer`, (Default value = zeros),
+ Initializer for the bias vector for the convolution layer
+ for generating the offset.
+ offset_use_bias: bool, (Default value = True)
+ Whether the layer for generating the offset uses a bias vector.
+
+ Inputs:
+ - **data**: 4D input tensor with shape
+ `(batch_size, in_channels, height, width)` when `layout` is `NCHW`.
+ For other layouts shape is permuted accordingly.
+
+ Outputs:
+ - **out**: 4D output tensor with shape
+ `(batch_size, channels, out_height, out_width)` when `layout` is `NCHW`.
+ out_height and out_width are calculated as::
+
+ out_height = floor((height+2*padding[0]-dilation[0]*(kernel_size[0]-1)-1)/stride[0])+1
+ out_width = floor((width+2*padding[1]-dilation[1]*(kernel_size[1]-1)-1)/stride[1])+1
+ """
+
+ def __init__(self, channels, kernel_size=(1, 1), strides=(1, 1), padding=(0, 0), dilation=(1, 1), groups=1,
+ num_deformable_group=1, layout='NCHW', use_bias=True, in_channels=0, activation=None,
+ weight_initializer=None, bias_initializer='zeros',
+ offset_weight_initializer='zeros', offset_bias_initializer='zeros', offset_use_bias=True,
+ op_name='DeformableConvolution', adj=None):
+ super(DeformableConvolution, self).__init__()
+ self._channels = channels
+ self._in_channels = in_channels
+
+ assert layout in ('NCHW', 'NHWC'), "Only supports 'NCHW' and 'NHWC' layout for now"
+ if isinstance(kernel_size, numeric_types):
+ kernel_size = (kernel_size,) * 2
+ if isinstance(strides, numeric_types):
+ strides = (strides,) * len(kernel_size)
+ if isinstance(padding, numeric_types):
+ padding = (padding,) * len(kernel_size)
+ if isinstance(dilation, numeric_types):
+ dilation = (dilation,) * len(kernel_size)
+ self._op_name = op_name
+
+ offset_channels = 2 * kernel_size[0] * kernel_size[1] * num_deformable_group
+ self._kwargs_offset = {
+ 'kernel': kernel_size, 'stride': strides, 'dilate': dilation,
+ 'pad': padding, 'num_filter': offset_channels, 'num_group': groups,
+ 'no_bias': not offset_use_bias, 'layout': layout}
+
+ self._kwargs_deformable_conv = {
+ 'kernel': kernel_size, 'stride': strides, 'dilate': dilation,
+ 'pad': padding, 'num_filter': channels, 'num_group': groups,
+ 'num_deformable_group': num_deformable_group,
+ 'no_bias': not use_bias, 'layout': layout}
+
+ if adj:
+ self._kwargs_offset['adj'] = adj
+ self._kwargs_deformable_conv['adj'] = adj
+
+ dshape = [0] * (len(kernel_size) + 2)
+ dshape[layout.find('N')] = 1
+ dshape[layout.find('C')] = in_channels
+
+ op_name = 'convolution' if is_np_array() else 'Convolution'
+ offsetshapes = _infer_weight_shape(op_name, dshape, self._kwargs_offset)
+
+ self.offset_weight = Parameter('offset_weight', shape=offsetshapes[1],
+ init=offset_weight_initializer,
+ allow_deferred_init=True)
+
+ if offset_use_bias:
+ self.offset_bias = Parameter('offset_bias', shape=offsetshapes[2],
+ init=offset_bias_initializer,
+ allow_deferred_init=True)
+ else:
+ self.offset_bias = None
+
+ deformable_conv_weight_shape = [0] * (len(kernel_size) + 2)
+ deformable_conv_weight_shape[0] = channels
+ deformable_conv_weight_shape[2] = kernel_size[0]
+ deformable_conv_weight_shape[3] = kernel_size[1]
+
+ self.deformable_conv_weight = Parameter('deformable_conv_weight',
+ shape=deformable_conv_weight_shape,
+ init=weight_initializer,
+ allow_deferred_init=True)
+
+ if use_bias:
+ self.deformable_conv_bias = Parameter('deformable_conv_bias', shape=(channels,),
+ init=bias_initializer,
+ allow_deferred_init=True)
+ else:
+ self.deformable_conv_bias = None
+
+ if activation:
+ self.act = Activation(activation)
+ else:
+ self.act = None
+
+ def hybrid_forward(self, F, x, offset_weight, deformable_conv_weight, offset_bias=None, deformable_conv_bias=None):
+ if not is_np_array():
+ x = x.as_np_ndarray()
+ offset_weight = offset_weight.as_np_ndarray()
+ deformable_conv_weight = deformable_conv_weight.as_np_ndarray()
+ if offset_bias is not None:
+ offset_bias = offset_bias.as_np_ndarray()
+ if deformable_conv_bias is not None:
+ deformable_conv_bias = deformable_conv_bias.as_np_ndarray()
+ if offset_bias is None:
+ offset = F.npx.convolution(x, offset_weight, cudnn_off=True, **self._kwargs_offset)
+ else:
+ offset = F.npx.convolution(x, offset_weight, offset_bias, cudnn_off=True, **self._kwargs_offset)
+
+ if deformable_conv_bias is None:
+ act = F.npx.deformable_convolution(data=x, offset=offset, weight=deformable_conv_weight,
+ name='fwd', **self._kwargs_deformable_conv)
+ else:
+ act = F.npx.deformable_convolution(data=x, offset=offset, weight=deformable_conv_weight,
+ bias=deformable_conv_bias, name='fwd',
+ **self._kwargs_deformable_conv)
+
+ if self.act:
+ with np_array(True):
+ act = self.act(act)
+ return act if is_np_array() else act.as_nd_ndarray()
+
+ def _alias(self):
+ return 'deformable_conv'
+
+ def __repr__(self):
+ s = '{name}({mapping}, kernel_size={kernel}, stride={stride}'
+ len_kernel_size = len(self._kwargs_deformable_conv['kernel'])
+ if self._kwargs_deformable_conv['pad'] != (0,) * len_kernel_size:
+ s += ', padding={pad}'
+ if self._kwargs_deformable_conv['dilate'] != (1,) * len_kernel_size:
+ s += ', dilation={dilate}'
+ if hasattr(self, 'out_pad') and self.out_pad != (0,) * len_kernel_size:
+ s += ', output_padding={out_pad}'.format(out_pad=self.out_pad)
+ if self._kwargs_deformable_conv['num_group'] != 1:
+ s += ', groups={num_group}'
+ if self.deformable_conv_bias is None:
+ s += ', bias=False'
+ if self.act:
+ s += ', {}'.format(self.act)
+ s += ')'
+ shape = self.deformable_conv_weight.shape
+ return s.format(name=self.__class__.__name__,
+ mapping='{0} -> {1}'.format(shape[1] if shape[1] else None, shape[0]),
+ **self._kwargs_deformable_conv)
+
+
+class ModulatedDeformableConvolution(HybridBlock):
+ """2-D Deformable Convolution v2 (Dai, 2018).
+
+ The modulated deformable convolution operation is described in https://arxiv.org/abs/1811.11168
+
+ Parameters
+ ----------
+ channels : int,
+ The dimensionality of the output space
+ i.e. the number of output channels in the convolution.
+ kernel_size : int or tuple/list of 2 ints, (Default value = (1,1))
+ Specifies the dimensions of the convolution window.
+ strides : int or tuple/list of 2 ints, (Default value = (1,1))
+ Specifies the strides of the convolution.
+ padding : int or tuple/list of 2 ints, (Default value = (0,0))
+ If padding is non-zero, then the input is implicitly zero-padded
+ on both sides for padding number of points.
+ dilation : int or tuple/list of 2 ints, (Default value = (1,1))
+ Specifies the dilation rate to use for dilated convolution.
+ groups : int, (Default value = 1)
+ Controls the connections between inputs and outputs.
+ At groups=1, all inputs are convolved to all outputs.
+ At groups=2, the operation becomes equivalent to having two convolution
+ layers side by side, each seeing half the input channels, and producing
+ half the output channels, and both subsequently concatenated.
+ num_deformable_group : int, (Default value = 1)
+ Number of deformable group partitions.
+ layout : str, (Default value = NCHW)
+ Dimension ordering of data and weight. Can be 'NCW', 'NWC', 'NCHW',
+ 'NHWC', 'NCDHW', 'NDHWC', etc. 'N', 'C', 'H', 'W', 'D' stands for
+ batch, channel, height, width and depth dimensions respectively.
+ Convolution is performed over 'D', 'H', and 'W' dimensions.
+ use_bias : bool, (Default value = True)
+ Whether the layer for generating the output features uses a bias vector.
+ in_channels : int, (Default value = 0)
+ The number of input channels to this layer. If not specified,
+ initialization will be deferred to the first time `forward` is called
+ and input channels will be inferred from the shape of input data.
+ activation : str, (Default value = None)
+ Activation function to use. See :func:`~mxnet.ndarray.Activation`.
+ If you don't specify anything, no activation is applied
+ (ie. "linear" activation: `a(x) = x`).
+ weight_initializer : str or `Initializer`, (Default value = None)
+ Initializer for the `weight` weights matrix for the convolution layer
+ for generating the output features.
+ bias_initializer : str or `Initializer`, (Default value = zeros)
+ Initializer for the bias vector for the convolution layer
+ for generating the output features.
+ offset_weight_initializer : str or `Initializer`, (Default value = zeros)
+ Initializer for the `weight` weights matrix for the convolution layer
+ for generating the offset.
+ offset_bias_initializer : str or `Initializer`, (Default value = zeros),
+ Initializer for the bias vector for the convolution layer
+ for generating the offset.
+ offset_use_bias: bool, (Default value = True)
+ Whether the layer for generating the offset uses a bias vector.
+
+ Inputs:
+ - **data**: 4D input tensor with shape
+ `(batch_size, in_channels, height, width)` when `layout` is `NCHW`.
+ For other layouts shape is permuted accordingly.
+
+ Outputs:
+ - **out**: 4D output tensor with shape
+ `(batch_size, channels, out_height, out_width)` when `layout` is `NCHW`.
+ out_height and out_width are calculated as::
+
+ out_height = floor((height+2*padding[0]-dilation[0]*(kernel_size[0]-1)-1)/stride[0])+1
+ out_width = floor((width+2*padding[1]-dilation[1]*(kernel_size[1]-1)-1)/stride[1])+1
+ """
+
+ def __init__(self, channels, kernel_size=(1, 1), strides=(1, 1), padding=(0, 0), dilation=(1, 1), groups=1,
+ num_deformable_group=1, layout='NCHW', use_bias=True, in_channels=0, activation=None,
+ weight_initializer=None, bias_initializer='zeros',
+ offset_weight_initializer='zeros', offset_bias_initializer='zeros', offset_use_bias=True,
+ op_name='ModulatedDeformableConvolution', adj=None):
+ super(ModulatedDeformableConvolution, self).__init__()
+ self._channels = channels
+ self._in_channels = in_channels
+
+ assert layout in ('NCHW', 'NHWC'), "Only supports 'NCHW' and 'NHWC' layout for now"
+ if isinstance(kernel_size, numeric_types):
+ kernel_size = (kernel_size,) * 2
+ if isinstance(strides, numeric_types):
+ strides = (strides,) * len(kernel_size)
+ if isinstance(padding, numeric_types):
+ padding = (padding,) * len(kernel_size)
+ if isinstance(dilation, numeric_types):
+ dilation = (dilation,) * len(kernel_size)
+ self._op_name = op_name
+
+ offset_channels = num_deformable_group * 3 * kernel_size[0] * kernel_size[1]
+ self.offset_split_index = num_deformable_group * 2 * kernel_size[0] * kernel_size[1]
+ self._kwargs_offset = {
+ 'kernel': kernel_size, 'stride': strides, 'dilate': dilation,
+ 'pad': padding, 'num_filter': offset_channels, 'num_group': groups,
+ 'no_bias': not offset_use_bias, 'layout': layout}
+
+ self._kwargs_deformable_conv = {
+ 'kernel': kernel_size, 'stride': strides, 'dilate': dilation,
+ 'pad': padding, 'num_filter': channels, 'num_group': groups,
+ 'num_deformable_group': num_deformable_group,
+ 'no_bias': not use_bias, 'layout': layout}
+
+ if adj:
+ self._kwargs_offset['adj'] = adj
+ self._kwargs_deformable_conv['adj'] = adj
+
+ deformable_conv_weight_shape = [0] * (len(kernel_size) + 2)
+ deformable_conv_weight_shape[0] = channels
+ deformable_conv_weight_shape[2] = kernel_size[0]
+ deformable_conv_weight_shape[3] = kernel_size[1]
+
+ self.deformable_conv_weight = Parameter('deformable_conv_weight',
+ shape=deformable_conv_weight_shape,
+ init=weight_initializer,
+ allow_deferred_init=True)
+
+ if use_bias:
+ self.deformable_conv_bias = Parameter('deformable_conv_bias', shape=(channels,),
+ init=bias_initializer,
+ allow_deferred_init=True)
+ else:
+ self.deformable_conv_bias = None
+
+ dshape = [0] * (len(kernel_size) + 2)
+ dshape[layout.find('N')] = 1
+ dshape[layout.find('C')] = in_channels
+
+ op = getattr(symbol, 'Convolution')
+ offset = op(symbol.var('data', shape=dshape), **self._kwargs_offset)
+
+ offsetshapes = offset.infer_shape_partial()[0]
+
+ self.offset_weight = Parameter('offset_weight', shape=offsetshapes[1],
+ init=offset_weight_initializer,
+ allow_deferred_init=True)
+
+ if offset_use_bias:
+ self.offset_bias = Parameter('offset_bias', shape=offsetshapes[2],
+ init=offset_bias_initializer,
+ allow_deferred_init=True)
+ else:
+ self.offset_bias = None
+
+ if activation:
+ self.act = Activation(activation)
+ else:
+ self.act = None
+
+ def hybrid_forward(self, F, x, offset_weight, deformable_conv_weight, offset_bias=None, deformable_conv_bias=None):
+ if not is_np_array():
+ x = x.as_np_ndarray()
+ offset_weight = offset_weight.as_np_ndarray()
+ deformable_conv_weight = deformable_conv_weight.as_np_ndarray()
+ if offset_bias is not None:
+ offset_bias = offset_bias.as_np_ndarray()
+ if deformable_conv_bias is not None:
+ deformable_conv_bias = deformable_conv_bias.as_np_ndarray()
+ if offset_bias is None:
+ offset = F.npx.convolution(x, offset_weight, cudnn_off=True, **self._kwargs_offset)
+ else:
+ offset = F.npx.convolution(x, offset_weight, offset_bias, cudnn_off=True, **self._kwargs_offset)
+
+ offset_t = F.npx.slice_axis(offset, axis=1, begin=0, end=self.offset_split_index)
+ mask = F.npx.slice_axis(offset, axis=1, begin=self.offset_split_index, end=None)
+ mask = F.npx.sigmoid(mask) * 2
+
+ if deformable_conv_bias is None:
+ act = F.npx.modulated_deformable_convolution(data=x, offset=offset_t, mask=mask,
+ weight=deformable_conv_weight,
+ name='fwd', **self._kwargs_deformable_conv)
+ else:
+ act = F.npx.modulated_deformable_convolution(data=x, offset=offset_t, mask=mask,
+ weight=deformable_conv_weight,
+ bias=deformable_conv_bias, name='fwd',
+ **self._kwargs_deformable_conv)
+
+ if self.act:
+ with np_array(True):
+ act = self.act(act)
+ return act if is_np_array() else act.as_nd_ndarray()
+
+ def _alias(self):
+ return 'modulated_deformable_conv'
+
+
+class PixelShuffle1D(HybridBlock):
+
+ r"""Pixel-shuffle layer for upsampling in 1 dimension.
+
+ Pixel-shuffling is the operation of taking groups of values along
+ the *channel* dimension and regrouping them into blocks of pixels
+ along the ``W`` dimension, thereby effectively multiplying that dimension
+ by a constant factor in size.
+
+ For example, a feature map of shape :math:`(fC, W)` is reshaped
+ into :math:`(C, fW)` by forming little value groups of size :math:`f`
+ and arranging them in a grid of size :math:`W`.
+
+ Parameters
+ ----------
+ factor : int or 1-tuple of int
+ Upsampling factor, applied to the ``W`` dimension.
+
+ Inputs:
+ - **data**: Tensor of shape ``(N, f*C, W)``.
+ Outputs:
+ - **out**: Tensor of shape ``(N, C, W*f)``.
+
+ Examples
+ --------
+ >>> pxshuf = PixelShuffle1D(2)
+ >>> x = mx.nd.zeros((1, 8, 3))
+ >>> pxshuf(x).shape
+ (1, 4, 6)
+ """
+
+ def __init__(self, factor):
+ super(PixelShuffle1D, self).__init__()
+ self._factor = int(factor)
+
+ def hybrid_forward(self, F, x):
+ """Perform pixel-shuffling on the input."""
+ f = self._factor
+ if not is_np_array():
+ x = x.as_np_ndarray()
+ # (N, C*f, W)
+ x = F.npx.reshape(x, (-2, -6, -1, f, -2)) # (N, C, f, W)
+ x = F.np.transpose(x, (0, 1, 3, 2)) # (N, C, W, f)
+ x = F.npx.reshape(x, (-2, -2, -5)) # (N, C, W*f)
+ return x if is_np_array() else x.as_nd_ndarray()
+
+ def __repr__(self):
+ return "{}({})".format(self.__class__.__name__, self._factor)
+
+
+class PixelShuffle2D(HybridBlock):
+
+ r"""Pixel-shuffle layer for upsampling in 2 dimensions.
+
+ Pixel-shuffling is the operation of taking groups of values along
+ the *channel* dimension and regrouping them into blocks of pixels
+ along the ``H`` and ``W`` dimensions, thereby effectively multiplying
+ those dimensions by a constant factor in size.
+
+ For example, a feature map of shape :math:`(f^2 C, H, W)` is reshaped
+ into :math:`(C, fH, fW)` by forming little :math:`f \times f` blocks
+ of pixels and arranging them in an :math:`H \times W` grid.
+
+ Pixel-shuffling together with regular convolution is an alternative,
+ learnable way of upsampling an image by arbitrary factors. It is reported
+ to help overcome checkerboard artifacts that are common in upsampling with
+ transposed convolutions (also called deconvolutions). See the paper
+ `Real-Time Single Image and Video Super-Resolution Using an Efficient
+ Sub-Pixel Convolutional Neural Network <https://arxiv.org/abs/1609.05158>`_
+ for further details.
+
+ Parameters
+ ----------
+ factor : int or 2-tuple of int
+ Upsampling factors, applied to the ``H`` and ``W`` dimensions,
+ in that order.
+
+ Inputs:
+ - **data**: Tensor of shape ``(N, f1*f2*C, H, W)``.
+ Outputs:
+ - **out**: Tensor of shape ``(N, C, H*f1, W*f2)``.
+
+ Examples
+ --------
+ >>> pxshuf = PixelShuffle2D((2, 3))
+ >>> x = mx.nd.zeros((1, 12, 3, 5))
+ >>> pxshuf(x).shape
+ (1, 2, 6, 15)
+ """
+
+ def __init__(self, factor):
+ super(PixelShuffle2D, self).__init__()
+ try:
+ self._factors = (int(factor),) * 2
+ except TypeError:
+ self._factors = tuple(int(fac) for fac in factor)
+ assert len(self._factors) == 2, "wrong length {}".format(len(self._factors))
+
+ def hybrid_forward(self, F, x):
+ """Perform pixel-shuffling on the input."""
+ f1, f2 = self._factors
+ if not is_np_array():
+ x = x.as_np_ndarray()
+ # (N, f1*f2*C, H, W)
+ x = F.npx.reshape(x, (-2, -6, -1, f1 * f2, -2, -2)) # (N, C, f1*f2, H, W)
+ x = F.npx.reshape(x, (-2, -2, -6, f1, f2, -2, -2)) # (N, C, f1, f2, H, W)
+ x = F.np.transpose(x, (0, 1, 4, 2, 5, 3)) # (N, C, H, f1, W, f2)
+ x = F.npx.reshape(x, (-2, -2, -5, -5)) # (N, C, H*f1, W*f2)
+ return x if is_np_array() else x.as_nd_ndarray()
+
+ def __repr__(self):
+ return "{}({})".format(self.__class__.__name__, self._factors)
+
+
+class PixelShuffle3D(HybridBlock):
+
+ r"""Pixel-shuffle layer for upsampling in 3 dimensions.
+
+ Pixel-shuffling (or voxel-shuffling in 3D) is the operation of taking
+ groups of values along the *channel* dimension and regrouping them into
+ blocks of voxels along the ``D``, ``H`` and ``W`` dimensions, thereby
+ effectively multiplying those dimensions by a constant factor in size.
+
+ For example, a feature map of shape :math:`(f^3 C, D, H, W)` is reshaped
+ into :math:`(C, fD, fH, fW)` by forming little :math:`f \times f \times f`
+ blocks of voxels and arranging them in a :math:`D \times H \times W` grid.
+
+ Pixel-shuffling together with regular convolution is an alternative,
+ learnable way of upsampling an image by arbitrary factors. It is reported
+ to help overcome checkerboard artifacts that are common in upsampling with
+ transposed convolutions (also called deconvolutions). See the paper
+ `Real-Time Single Image and Video Super-Resolution Using an Efficient
+ Sub-Pixel Convolutional Neural Network <https://arxiv.org/abs/1609.05158>`_
+ for further details.
+
+ Parameters
+ ----------
+ factor : int or 3-tuple of int
+ Upsampling factors, applied to the ``D``, ``H`` and ``W``
+ dimensions, in that order.
+
+ Inputs:
+ - **data**: Tensor of shape ``(N, f1*f2*f3*C, D, H, W)``.
+ Outputs:
+ - **out**: Tensor of shape ``(N, C, D*f1, H*f2, W*f3)``.
+
+ Examples
+ --------
+ >>> pxshuf = PixelShuffle3D((2, 3, 4))
+ >>> x = mx.nd.zeros((1, 48, 3, 5, 7))
+ >>> pxshuf(x).shape
+ (1, 2, 6, 15, 28)
+ """
+
+ def __init__(self, factor):
+ super(PixelShuffle3D, self).__init__()
+ try:
+ self._factors = (int(factor),) * 3
+ except TypeError:
+ self._factors = tuple(int(fac) for fac in factor)
+ assert len(self._factors) == 3, "wrong length {}".format(len(self._factors))
+
+ def hybrid_forward(self, F, x):
+ """Perform pixel-shuffling on the input."""
+ # `transpose` doesn't support 8D, need other implementation
+ f1, f2, f3 = self._factors
+ if not is_np_array():
+ x = x.as_np_ndarray()
+ # (N, C*f1*f2*f3, D, H, W)
+ x = F.npx.reshape(x, (-2, -6, -1, f1 * f2 * f3, -2, -2, -2)) # (N, C, f1*f2*f3, D, H, W)
+ x = F.np.swapaxes(x, 2, 3) # (N, C, D, f1*f2*f3, H, W)
+ x = F.npx.reshape(x, (-2, -2, -2, -6, f1, f2*f3, -2, -2)) # (N, C, D, f1, f2*f3, H, W)
+ x = F.npx.reshape(x, (-2, -2, -5, -2, -2, -2)) # (N, C, D*f1, f2*f3, H, W)
+ x = F.np.swapaxes(x, 3, 4) # (N, C, D*f1, H, f2*f3, W)
+ x = F.npx.reshape(x, (-2, -2, -2, -2, -6, f2, f3, -2)) # (N, C, D*f1, H, f2, f3, W)
+ x = F.npx.reshape(x, (-2, -2, -2, -5, -2, -2)) # (N, C, D*f1, H*f2, f3, W)
+ x = F.np.swapaxes(x, 4, 5) # (N, C, D*f1, H*f2, W, f3)
+ x = F.npx.reshape(x, (-2, -2, -2, -2, -5)) # (N, C, D*f1, H*f2, W*f3)
+ return x if is_np_array() else x.as_nd_ndarray()
+
+ def __repr__(self):
+ return "{}({})".format(self.__class__.__name__, self._factors)
diff --git a/python/mxnet/gluon/rnn/__init__.py b/python/mxnet/gluon/rnn/__init__.py
index 24cce54..44a283f 100644
--- a/python/mxnet/gluon/rnn/__init__.py
+++ b/python/mxnet/gluon/rnn/__init__.py
@@ -20,5 +20,5 @@
"""Recurrent neural network module."""
from .rnn_cell import *
-
+from .conv_rnn_cell import *
from .rnn_layer import *
diff --git a/python/mxnet/gluon/contrib/rnn/conv_rnn_cell.py b/python/mxnet/gluon/rnn/conv_rnn_cell.py
similarity index 99%
rename from python/mxnet/gluon/contrib/rnn/conv_rnn_cell.py
rename to python/mxnet/gluon/rnn/conv_rnn_cell.py
index 745a0c5..d6cb0f4 100644
--- a/python/mxnet/gluon/contrib/rnn/conv_rnn_cell.py
+++ b/python/mxnet/gluon/rnn/conv_rnn_cell.py
@@ -25,9 +25,9 @@ __all__ = ['Conv1DRNNCell', 'Conv2DRNNCell', 'Conv3DRNNCell',
from math import floor
-from ....base import numeric_types
-from ...rnn import HybridRecurrentCell
-from ...parameter import Parameter
+from ...base import numeric_types
+from .rnn_cell import HybridRecurrentCell
+from ..parameter import Parameter
def _get_conv_out_size(dimensions, kernels, paddings, dilations):
diff --git a/python/mxnet/gluon/rnn/rnn_cell.py b/python/mxnet/gluon/rnn/rnn_cell.py
index 380fb20..236354d 100644
--- a/python/mxnet/gluon/rnn/rnn_cell.py
+++ b/python/mxnet/gluon/rnn/rnn_cell.py
@@ -24,7 +24,7 @@ __all__ = ['RecurrentCell', 'HybridRecurrentCell',
'RNNCell', 'LSTMCell', 'GRUCell',
'SequentialRNNCell', 'HybridSequentialRNNCell', 'DropoutCell',
'ModifierCell', 'ZoneoutCell', 'ResidualCell',
- 'BidirectionalCell']
+ 'BidirectionalCell', 'VariationalDropoutCell', 'LSTMPCell']
from ... import symbol, ndarray
from ...base import string_types, numeric_types, _as_list
@@ -1085,3 +1085,409 @@ class BidirectionalCell(HybridRecurrentCell):
merge_outputs)
states = l_states + r_states
return outputs, states
+
+
+class VariationalDropoutCell(ModifierCell):
+ """
+ Applies Variational Dropout on base cell.
+ https://arxiv.org/pdf/1512.05287.pdf
+
+ Variational dropout uses the same dropout mask across time-steps. It can be applied to RNN
+ inputs, outputs, and states. The masks for them are not shared.
+
+ The dropout mask is initialized when stepping forward for the first time and will remain
+ the same until .reset() is called. Thus, if using the cell and stepping manually without calling
+ .unroll(), the .reset() should be called after each sequence.
+
+ Parameters
+ ----------
+ base_cell : RecurrentCell
+ The cell on which to perform variational dropout.
+ drop_inputs : float, default 0.
+ The dropout rate for inputs. Won't apply dropout if it equals 0.
+ drop_states : float, default 0.
+ The dropout rate for state inputs on the first state channel.
+ Won't apply dropout if it equals 0.
+ drop_outputs : float, default 0.
+ The dropout rate for outputs. Won't apply dropout if it equals 0.
+ """
+ def __init__(self, base_cell, drop_inputs=0., drop_states=0., drop_outputs=0.):
+ assert not drop_states or not isinstance(base_cell, BidirectionalCell), \
+ "BidirectionalCell doesn't support variational state dropout. " \
+ "Please add VariationalDropoutCell to the cells underneath instead."
+ assert not drop_states \
+ or not isinstance(base_cell, SequentialRNNCell) or not base_cell._bidirectional, \
+ "Bidirectional SequentialRNNCell doesn't support variational state dropout. " \
+ "Please add VariationalDropoutCell to the cells underneath instead."
+ super(VariationalDropoutCell, self).__init__(base_cell)
+ self.drop_inputs = drop_inputs
+ self.drop_states = drop_states
+ self.drop_outputs = drop_outputs
+ self.drop_inputs_mask = None
+ self.drop_states_mask = None
+ self.drop_outputs_mask = None
+
+ def _alias(self):
+ return 'vardrop'
+
+ def reset(self):
+ super(VariationalDropoutCell, self).reset()
+ self.drop_inputs_mask = None
+ self.drop_states_mask = None
+ self.drop_outputs_mask = None
+
+ def _initialize_input_masks(self, F, inputs, states):
+ if self.drop_states and self.drop_states_mask is None:
+ self.drop_states_mask = F.Dropout(F.ones_like(states[0]),
+ p=self.drop_states)
+
+ if self.drop_inputs and self.drop_inputs_mask is None:
+ self.drop_inputs_mask = F.Dropout(F.ones_like(inputs),
+ p=self.drop_inputs)
+
+ def _initialize_output_mask(self, F, output):
+ if self.drop_outputs and self.drop_outputs_mask is None:
+ self.drop_outputs_mask = F.Dropout(F.ones_like(output),
+ p=self.drop_outputs)
+
+
+ def hybrid_forward(self, F, inputs, states):
+ cell = self.base_cell
+ self._initialize_input_masks(F, inputs, states)
+
+ if self.drop_states:
+ states = list(states)
+ # state dropout only needs to be applied on h, which is always the first state.
+ states[0] = states[0] * self.drop_states_mask
+
+ if self.drop_inputs:
+ inputs = inputs * self.drop_inputs_mask
+
+ next_output, next_states = cell(inputs, states)
+
+ self._initialize_output_mask(F, next_output)
+ if self.drop_outputs:
+ next_output = next_output * self.drop_outputs_mask
+
+ return next_output, next_states
+
+ def __repr__(self):
+ s = '{name}(p_out = {drop_outputs}, p_state = {drop_states})'
+ return s.format(name=self.__class__.__name__,
+ **self.__dict__)
+
+ def unroll(self, length, inputs, begin_state=None, layout='NTC', merge_outputs=None,
+ valid_length=None):
+ """Unrolls an RNN cell across time steps.
+
+ Parameters
+ ----------
+ length : int
+ Number of steps to unroll.
+ inputs : Symbol, list of Symbol, or None
+ If `inputs` is a single Symbol (usually the output
+ of Embedding symbol), it should have shape
+ (batch_size, length, ...) if `layout` is 'NTC',
+ or (length, batch_size, ...) if `layout` is 'TNC'.
+
+ If `inputs` is a list of symbols (usually output of
+ previous unroll), they should all have shape
+ (batch_size, ...).
+ begin_state : nested list of Symbol, optional
+ Input states created by `begin_state()`
+ or output state of another cell.
+ Created from `begin_state()` if `None`.
+ layout : str, optional
+ `layout` of input symbol. Only used if inputs
+ is a single Symbol.
+ merge_outputs : bool, optional
+ If `False`, returns outputs as a list of Symbols.
+ If `True`, concatenates output across time steps
+ and returns a single symbol with shape
+ (batch_size, length, ...) if layout is 'NTC',
+ or (length, batch_size, ...) if layout is 'TNC'.
+ If `None`, output whatever is faster.
+ valid_length : Symbol, NDArray or None
+ `valid_length` specifies the length of the sequences in the batch without padding.
+ This option is especially useful for building sequence-to-sequence models where
+ the input and output sequences would potentially be padded.
+ If `valid_length` is None, all sequences are assumed to have the same length.
+ If `valid_length` is a Symbol or NDArray, it should have shape (batch_size,).
+ The ith element will be the length of the ith sequence in the batch.
+ The last valid state will be return and the padded outputs will be masked with 0.
+ Note that `valid_length` must be smaller or equal to `length`.
+
+ Returns
+ -------
+ outputs : list of Symbol or Symbol
+ Symbol (if `merge_outputs` is True) or list of Symbols
+ (if `merge_outputs` is False) corresponding to the output from
+ the RNN from this unrolling.
+
+ states : list of Symbol
+ The new state of this RNN after this unrolling.
+ The type of this symbol is same as the output of `begin_state()`.
+ """
+
+ # Dropout on inputs and outputs can be performed on the whole sequence
+ # only when state dropout is not present.
+ if self.drop_states:
+ return super(VariationalDropoutCell, self).unroll(length, inputs, begin_state,
+ layout, merge_outputs,
+ valid_length=valid_length)
+
+ self.reset()
+
+ inputs, axis, F, batch_size = _format_sequence(length, inputs, layout, True)
+ states = _get_begin_state(self, F, begin_state, inputs, batch_size)
+
+ if self.drop_inputs:
+ inputs = F.Dropout(inputs, p=self.drop_inputs, axes=(axis,))
+
+ outputs, states = self.base_cell.unroll(length, inputs, states, layout, merge_outputs=True,
+ valid_length=valid_length)
+ if self.drop_outputs:
+ outputs = F.Dropout(outputs, p=self.drop_outputs, axes=(axis,))
+ merge_outputs = isinstance(outputs, tensor_types) if merge_outputs is None else \
+ merge_outputs
+ outputs, _, _, _ = _format_sequence(length, outputs, layout, merge_outputs)
+ if valid_length is not None:
+ outputs = _mask_sequence_variable_length(F, outputs, length, valid_length, axis,
+ merge_outputs)
+ return outputs, states
+
+
+class LSTMPCell(HybridRecurrentCell):
+ r"""Long-Short Term Memory Projected (LSTMP) network cell.
+ (https://arxiv.org/abs/1402.1128)
+
+ Each call computes the following function:
+
+ .. math::
+ \begin{array}{ll}
+ i_t = sigmoid(W_{ii} x_t + b_{ii} + W_{ri} r_{(t-1)} + b_{ri}) \\
+ f_t = sigmoid(W_{if} x_t + b_{if} + W_{rf} r_{(t-1)} + b_{rf}) \\
+ g_t = \tanh(W_{ig} x_t + b_{ig} + W_{rc} r_{(t-1)} + b_{rg}) \\
+ o_t = sigmoid(W_{io} x_t + b_{io} + W_{ro} r_{(t-1)} + b_{ro}) \\
+ c_t = f_t * c_{(t-1)} + i_t * g_t \\
+ h_t = o_t * \tanh(c_t) \\
+ r_t = W_{hr} h_t
+ \end{array}
+
+ where :math:`r_t` is the projected recurrent activation at time `t`,
+ :math:`h_t` is the hidden state at time `t`, :math:`c_t` is the
+ cell state at time `t`, :math:`x_t` is the input at time `t`, and :math:`i_t`,
+ :math:`f_t`, :math:`g_t`, :math:`o_t` are the input, forget, cell, and
+ out gates, respectively.
+
+ Parameters
+ ----------
+
+ hidden_size : int
+ Number of units in cell state symbol.
+ projection_size : int
+ Number of units in output symbol.
+ i2h_weight_initializer : str or Initializer
+ Initializer for the input weights matrix, used for the linear
+ transformation of the inputs.
+ h2h_weight_initializer : str or Initializer
+ Initializer for the recurrent weights matrix, used for the linear
+ transformation of the hidden state.
+ h2r_weight_initializer : str or Initializer
+ Initializer for the projection weights matrix, used for the linear
+ transformation of the recurrent state.
+ i2h_bias_initializer : str or Initializer, default 'lstmbias'
+ Initializer for the bias vector. By default, bias for the forget
+ gate is initialized to 1 while all other biases are initialized
+ to zero.
+ h2h_bias_initializer : str or Initializer
+ Initializer for the bias vector.
+ Inputs:
+ - **data**: input tensor with shape `(batch_size, input_size)`.
+ - **states**: a list of two initial recurrent state tensors, with shape
+ `(batch_size, projection_size)` and `(batch_size, hidden_size)` respectively.
+ Outputs:
+ - **out**: output tensor with shape `(batch_size, num_hidden)`.
+ - **next_states**: a list of two output recurrent state tensors. Each has
+ the same shape as `states`.
+ """
+ def __init__(self, hidden_size, projection_size,
+ i2h_weight_initializer=None, h2h_weight_initializer=None,
+ h2r_weight_initializer=None,
+ i2h_bias_initializer='zeros', h2h_bias_initializer='zeros',
+ input_size=0):
+ super(LSTMPCell, self).__init__()
+
+ self._hidden_size = hidden_size
+ self._input_size = input_size
+ self._projection_size = projection_size
+ self.i2h_weight = Parameter('i2h_weight', shape=(4*hidden_size, input_size),
+ init=i2h_weight_initializer,
+ allow_deferred_init=True)
+ self.h2h_weight = Parameter('h2h_weight', shape=(4*hidden_size, projection_size),
+ init=h2h_weight_initializer,
+ allow_deferred_init=True)
+ self.h2r_weight = Parameter('h2r_weight', shape=(projection_size, hidden_size),
+ init=h2r_weight_initializer,
+ allow_deferred_init=True)
+ self.i2h_bias = Parameter('i2h_bias', shape=(4*hidden_size,),
+ init=i2h_bias_initializer,
+ allow_deferred_init=True)
+ self.h2h_bias = Parameter('h2h_bias', shape=(4*hidden_size,),
+ init=h2h_bias_initializer,
+ allow_deferred_init=True)
+
+ def state_info(self, batch_size=0):
+ return [{'shape': (batch_size, self._projection_size), '__layout__': 'NC'},
+ {'shape': (batch_size, self._hidden_size), '__layout__': 'NC'}]
+
+ def _alias(self):
+ return 'lstmp'
+
+ def __repr__(self):
+ s = '{name}({mapping})'
+ shape = self.i2h_weight.shape
+ proj_shape = self.h2r_weight.shape
+ mapping = '{0} -> {1} -> {2}'.format(shape[1] if shape[1] else None,
+ shape[0], proj_shape[0])
+ return s.format(name=self.__class__.__name__,
+ mapping=mapping,
+ **self.__dict__)
+
+ # pylint: disable= arguments-differ
+ def hybrid_forward(self, F, inputs, states, i2h_weight,
+ h2h_weight, h2r_weight, i2h_bias, h2h_bias):
+ prefix = 't%d_'%self._counter
+ i2h = F.FullyConnected(data=inputs, weight=i2h_weight, bias=i2h_bias,
+ num_hidden=self._hidden_size*4, name=prefix+'i2h')
+ h2h = F.FullyConnected(data=states[0], weight=h2h_weight, bias=h2h_bias,
+ num_hidden=self._hidden_size*4, name=prefix+'h2h')
+ gates = i2h + h2h
+ slice_gates = F.SliceChannel(gates, num_outputs=4, name=prefix+'slice')
+ in_gate = F.Activation(slice_gates[0], act_type="sigmoid", name=prefix+'i')
+ forget_gate = F.Activation(slice_gates[1], act_type="sigmoid", name=prefix+'f')
+ in_transform = F.Activation(slice_gates[2], act_type="tanh", name=prefix+'c')
+ out_gate = F.Activation(slice_gates[3], act_type="sigmoid", name=prefix+'o')
+ next_c = F.elemwise_add(forget_gate * states[1], in_gate * in_transform,
+ name=prefix+'state')
+ hidden = F.elemwise_mul(out_gate, F.Activation(next_c, act_type="tanh"),
+ name=prefix+'hidden')
+ next_r = F.FullyConnected(data=hidden, num_hidden=self._projection_size,
+ weight=h2r_weight, no_bias=True, name=prefix+'out')
+
+ return next_r, [next_r, next_c]
+ # pylint: enable= arguments-differ
+
+
+def dynamic_unroll(cell, inputs, begin_state, drop_inputs=0, drop_outputs=0,
+ layout='TNC', valid_length=None):
+ """Unrolls an RNN cell across time steps.
+
+ Currently, 'TNC' is a preferred layout. unroll on the input of this layout
+ runs much faster.
+
+ Parameters
+ ----------
+ cell : an object whose base class is RNNCell.
+ The RNN cell to run on the input sequence.
+ inputs : Symbol
+ It should have shape (batch_size, length, ...) if `layout` is 'NTC',
+ or (length, batch_size, ...) if `layout` is 'TNC'.
+ begin_state : nested list of Symbol
+ The initial states of the RNN sequence.
+ drop_inputs : float, default 0.
+ The dropout rate for inputs. Won't apply dropout if it equals 0.
+ drop_outputs : float, default 0.
+ The dropout rate for outputs. Won't apply dropout if it equals 0.
+ layout : str, optional
+ `layout` of input symbol. Only used if inputs
+ is a single Symbol.
+ valid_length : Symbol, NDArray or None
+ `valid_length` specifies the length of the sequences in the batch without padding.
+ This option is especially useful for building sequence-to-sequence models where
+ the input and output sequences would potentially be padded.
+ If `valid_length` is None, all sequences are assumed to have the same length.
+ If `valid_length` is a Symbol or NDArray, it should have shape (batch_size,).
+ The ith element will be the length of the ith sequence in the batch.
+ The last valid state will be return and the padded outputs will be masked with 0.
+ Note that `valid_length` must be smaller or equal to `length`.
+
+ Returns
+ -------
+ outputs : Symbol
+ the output of the RNN from this unrolling.
+
+ states : list of Symbol
+ The new state of this RNN after this unrolling.
+ The type of this symbol is same as the output of `begin_state`.
+
+ Examples
+ --------
+ >>> seq_len = 3
+ >>> batch_size = 2
+ >>> input_size = 5
+ >>> cell = mx.gluon.rnn.LSTMCell(input_size)
+ >>> cell.initialize(ctx=mx.cpu())
+ >>> rnn_data = mx.nd.normal(loc=0, scale=1, shape=(seq_len, batch_size, input_size))
+ >>> state_shape = (batch_size, input_size)
+ >>> states = [mx.nd.normal(loc=0, scale=1, shape=state_shape) for i in range(2)]
+ >>> valid_length = mx.nd.array([2, 3])
+ >>> output, states = mx.gluon.contrib.rnn.rnn_cell.dynamic_unroll(cell, rnn_data, states,
+ valid_length=valid_length,
+ layout='TNC')
+ >>> print(output)
+ [[[ 0.00767238 0.00023103 0.03973929 -0.00925503 -0.05660512]
+ [ 0.00881535 0.05428379 -0.02493718 -0.01834097 0.02189514]]
+ [[-0.00676967 0.01447039 0.01287002 -0.00574152 -0.05734247]
+ [ 0.01568508 0.02650866 -0.04270559 -0.04328435 0.00904011]]
+ [[ 0. 0. 0. 0. 0. ]
+ [ 0.01055336 0.02734251 -0.03153727 -0.03742751 -0.01378113]]]
+ <NDArray 3x2x5 @cpu(0)>
+ """
+
+ # Merge is always True, so we don't need length.
+ inputs, axis, F, _ = _format_sequence(0, inputs, layout, True)
+ if axis != 0:
+ axes = list(range(len(layout)))
+ tmp = axes[0]
+ axes[0] = axes[axis]
+ axes[axis] = tmp
+ inputs = F.transpose(inputs, axes=axes)
+ states = begin_state
+
+ if drop_inputs:
+ inputs = F.Dropout(inputs, p=drop_inputs, axes=(axis,))
+
+ if valid_length is None:
+ def loop_body(inputs, states):
+ return cell(inputs, states)
+ else:
+ zeros = []
+ for s in states:
+ zeros.append(F.zeros_like(s))
+ states = list(_as_list(states))
+ states.append(F.zeros((1)))
+ def loop_body(inputs, states):
+ cell_states = states[:-1]
+ iter_no = states[-1]
+ out, new_states = cell(inputs, cell_states)
+ for i, state in enumerate(cell_states):
+ new_states[i] = F.where(F.broadcast_greater(valid_length, iter_no),
+ new_states[i], state)
+ new_states.append(iter_no + 1)
+ return out, new_states
+
+ outputs, states = F.contrib.foreach(loop_body, inputs, states)
+ if drop_outputs:
+ outputs = F.Dropout(outputs, p=drop_outputs, axes=(axis,))
+ if valid_length is not None:
+ if axis != 0:
+ outputs = F.transpose(outputs, axes)
+ outputs = F.SequenceMask(outputs, sequence_length=valid_length,
+ use_sequence_length=True, axis=axis)
+ # the last state is the iteration number. We don't need it.
+ return outputs, states[:-1]
+ else:
+ if axis != 0:
+ outputs = F.transpose(outputs, axes)
+ return outputs, states
diff --git a/python/mxnet/numpy/random.py b/python/mxnet/numpy/random.py
index e739036..ccfa433 100644
--- a/python/mxnet/numpy/random.py
+++ b/python/mxnet/numpy/random.py
@@ -18,13 +18,15 @@
"""Namespace for ops used in imperative programming."""
from ..ndarray import numpy as _mx_nd_np
+from ..random import seed
__all__ = ["randint", "uniform", "normal", "choice", "rand", "multinomial", "multivariate_normal",
"logistic", "gumbel", "f",
"laplace",
"shuffle", "randn", "gamma", "beta", "chisquare", "exponential", "lognormal",
- "weibull", "pareto", "power", "rayleigh"]
+ "weibull", "pareto", "power", "rayleigh",
+ "seed"]
def randint(low, high=None, size=None, dtype=None, ctx=None, out=None):
diff --git a/python/mxnet/random.py b/python/mxnet/random.py
index 5e018d2..2d1087a 100644
--- a/python/mxnet/random.py
+++ b/python/mxnet/random.py
@@ -55,37 +55,37 @@ def seed(seed_state, ctx="all"):
Example
-------
- >>> print(mx.nd.random.normal(shape=(2,2)).asnumpy())
+ >>> print(mx.np.random.normal(shape=(2,2)).asnumpy())
[[ 1.36481571 -0.62203991]
[-1.4962182 -0.08511394]]
- >>> print(mx.nd.random.normal(shape=(2,2)).asnumpy())
+ >>> print(mx.np.random.normal(shape=(2,2)).asnumpy())
[[ 1.09544981 -0.20014545]
[-0.20808885 0.2527658 ]]
# Same results on the same device with the same seed
- >>> mx.random.seed(128)
- >>> print(mx.nd.random.normal(shape=(2,2)).asnumpy())
+ >>> mx.np.random.seed(128)
+ >>> print(mx.np.random.normal(shape=(2,2)).asnumpy())
[[ 0.47400656 -0.75213492]
[ 0.20251541 0.95352972]]
- >>> mx.random.seed(128)
- >>> print(mx.nd.random.normal(shape=(2,2)).asnumpy())
+ >>> mx.np.random.seed(128)
+ >>> print(mx.np.random.normal(shape=(2,2)).asnumpy())
[[ 0.47400656 -0.75213492]
[ 0.20251541 0.95352972]]
# Different results on gpu(0) and gpu(1) with the same seed
- >>> mx.random.seed(128)
- >>> print(mx.nd.random.normal(shape=(2,2), ctx=mx.gpu(0)).asnumpy())
+ >>> mx.np.random.seed(128)
+ >>> print(mx.np.random.normal(shape=(2,2), ctx=mx.gpu(0)).asnumpy())
[[ 2.5020072 -1.6884501]
[-0.7931333 -1.4218881]]
- >>> mx.random.seed(128)
- >>> print(mx.nd.random.normal(shape=(2,2), ctx=mx.gpu(1)).asnumpy())
+ >>> mx.np.random.seed(128)
+ >>> print(mx.np.random.normal(shape=(2,2), ctx=mx.gpu(1)).asnumpy())
[[ 0.24336822 -1.664805 ]
[-1.0223296 1.253198 ]]
# Seeding with `ctx` argument produces identical results on gpu(0) and gpu(1)
- >>> mx.random.seed(128, ctx=mx.gpu(0))
- >>> print(mx.nd.random.normal(shape=(2,2), ctx=mx.gpu(0)).asnumpy())
+ >>> mx.np.random.seed(128, ctx=mx.gpu(0))
+ >>> print(mx.np.random.normal(shape=(2,2), ctx=mx.gpu(0)).asnumpy())
[[ 2.5020072 -1.6884501]
[-0.7931333 -1.4218881]]
- >>> mx.random.seed(128, ctx=mx.gpu(1))
- >>> print(mx.nd.random.normal(shape=(2,2), ctx=mx.gpu(1)).asnumpy())
+ >>> mx.np.random.seed(128, ctx=mx.gpu(1))
+ >>> print(mx.np.random.normal(shape=(2,2), ctx=mx.gpu(1)).asnumpy())
[[ 2.5020072 -1.6884501]
[-0.7931333 -1.4218881]]
"""
diff --git a/src/operator/contrib/deformable_convolution-inl.h b/src/operator/deformable_convolution-inl.h
similarity index 98%
rename from src/operator/contrib/deformable_convolution-inl.h
rename to src/operator/deformable_convolution-inl.h
index 5e0e86b..6d2f8b0 100644
--- a/src/operator/contrib/deformable_convolution-inl.h
+++ b/src/operator/deformable_convolution-inl.h
@@ -26,8 +26,8 @@
* \ref: https://arxiv.org/abs/1703.06211
* \author Yuwen Xiong, Haozhi Qi, Jifeng Dai
*/
-#ifndef MXNET_OPERATOR_CONTRIB_DEFORMABLE_CONVOLUTION_INL_H_
-#define MXNET_OPERATOR_CONTRIB_DEFORMABLE_CONVOLUTION_INL_H_
+#ifndef MXNET_OPERATOR_DEFORMABLE_CONVOLUTION_INL_H_
+#define MXNET_OPERATOR_DEFORMABLE_CONVOLUTION_INL_H_
#include <mxnet/io.h>
#include <mxnet/base.h>
@@ -41,10 +41,10 @@
#include <vector>
#include <string>
#include <utility>
-#include "../operator_common.h"
-#include "../nn/im2col.h"
-#include "./nn/deformable_im2col.h"
-#include "../linalg.h"
+#include "./operator_common.h"
+#include "./nn/im2col.h"
+#include "./contrib/nn/deformable_im2col.h"
+#include "./linalg.h"
namespace mxnet {
@@ -474,7 +474,7 @@ class DeformableConvolutionProp : public OperatorProperty {
}
std::string TypeString() const override {
- return "_contrib_DeformableConvolution";
+ return "_npx_deformable_convolution";
}
std::vector<int> DeclareBackwardDependency(const std::vector<int> &out_grad,
@@ -508,4 +508,4 @@ class DeformableConvolutionProp : public OperatorProperty {
#endif // DMLC_USE_CXX11
} // namespace op
} // namespace mxnet
-#endif // MXNET_OPERATOR_CONTRIB_DEFORMABLE_CONVOLUTION_INL_H_
+#endif // MXNET_OPERATOR_DEFORMABLE_CONVOLUTION_INL_H_
diff --git a/src/operator/contrib/deformable_convolution.cc b/src/operator/deformable_convolution.cc
similarity index 97%
rename from src/operator/contrib/deformable_convolution.cc
rename to src/operator/deformable_convolution.cc
index 6013837..ad0d0b5 100644
--- a/src/operator/contrib/deformable_convolution.cc
+++ b/src/operator/deformable_convolution.cc
@@ -54,7 +54,7 @@ Operator *DeformableConvolutionProp::CreateOperatorEx(Context ctx,
DO_BIND_DISPATCH(CreateOp, param_, (*in_type)[0], in_shape, &out_shape, ctx);
}
-MXNET_REGISTER_OP_PROPERTY(_contrib_DeformableConvolution, DeformableConvolutionProp)
+MXNET_REGISTER_OP_PROPERTY(_npx_deformable_convolution, DeformableConvolutionProp)
.describe(R"code(Compute 2-D deformable convolution on 4-D input.
The deformable convolution operation is described in https://arxiv.org/abs/1703.06211
diff --git a/src/operator/contrib/deformable_convolution.cu b/src/operator/deformable_convolution.cu
similarity index 100%
rename from src/operator/contrib/deformable_convolution.cu
rename to src/operator/deformable_convolution.cu
diff --git a/src/operator/contrib/modulated_deformable_convolution-inl.h b/src/operator/modulated_deformable_convolution-inl.h
similarity index 98%
rename from src/operator/contrib/modulated_deformable_convolution-inl.h
rename to src/operator/modulated_deformable_convolution-inl.h
index 6ec5d88..c642675 100644
--- a/src/operator/contrib/modulated_deformable_convolution-inl.h
+++ b/src/operator/modulated_deformable_convolution-inl.h
@@ -26,8 +26,8 @@
* \ref: https://arxiv.org/abs/1811.11168
* \author Yuwen Xiong, Haozhi Qi, Jifeng Dai, Xizhou Zhu, Han Hu
*/
-#ifndef MXNET_OPERATOR_CONTRIB_MODULATED_DEFORMABLE_CONVOLUTION_INL_H_
-#define MXNET_OPERATOR_CONTRIB_MODULATED_DEFORMABLE_CONVOLUTION_INL_H_
+#ifndef MXNET_OPERATOR_MODULATED_DEFORMABLE_CONVOLUTION_INL_H_
+#define MXNET_OPERATOR_MODULATED_DEFORMABLE_CONVOLUTION_INL_H_
#include <mxnet/io.h>
#include <mxnet/base.h>
@@ -41,10 +41,10 @@
#include <vector>
#include <string>
#include <utility>
-#include "../operator_common.h"
-#include "../nn/im2col.h"
-#include "./nn/modulated_deformable_im2col.h"
-#include "../linalg.h"
+#include "./operator_common.h"
+#include "./nn/im2col.h"
+#include "./contrib/nn/modulated_deformable_im2col.h"
+#include "./linalg.h"
namespace mxnet {
@@ -537,7 +537,7 @@ class ModulatedDeformableConvolutionProp : public OperatorProperty {
}
std::string TypeString() const override {
- return "_contrib_ModulatedDeformableConvolution";
+ return "_npx_modulated_deformable_convolution";
}
std::vector<int> DeclareBackwardDependency(
@@ -573,4 +573,4 @@ class ModulatedDeformableConvolutionProp : public OperatorProperty {
#endif // DMLC_USE_CXX11
} // namespace op
} // namespace mxnet
-#endif // MXNET_OPERATOR_CONTRIB_MODULATED_DEFORMABLE_CONVOLUTION_INL_H_
+#endif // MXNET_OPERATOR_MODULATED_DEFORMABLE_CONVOLUTION_INL_H_
diff --git a/src/operator/contrib/modulated_deformable_convolution.cc b/src/operator/modulated_deformable_convolution.cc
similarity index 98%
rename from src/operator/contrib/modulated_deformable_convolution.cc
rename to src/operator/modulated_deformable_convolution.cc
index 5fa25f7..dd405fb 100644
--- a/src/operator/contrib/modulated_deformable_convolution.cc
+++ b/src/operator/modulated_deformable_convolution.cc
@@ -55,7 +55,7 @@ Operator *ModulatedDeformableConvolutionProp::CreateOperatorEx(Context ctx,
}
MXNET_REGISTER_OP_PROPERTY(
- _contrib_ModulatedDeformableConvolution, ModulatedDeformableConvolutionProp)
+ _npx_modulated_deformable_convolution, ModulatedDeformableConvolutionProp)
.describe(R"code(Compute 2-D modulated deformable convolution on 4-D input.
The modulated deformable convolution operation is described in https://arxiv.org/abs/1811.11168
diff --git a/src/operator/contrib/modulated_deformable_convolution.cu b/src/operator/modulated_deformable_convolution.cu
similarity index 100%
rename from src/operator/contrib/modulated_deformable_convolution.cu
rename to src/operator/modulated_deformable_convolution.cu
diff --git a/tests/python/gpu/test_gluon_contrib_gpu.py b/tests/python/gpu/test_gluon_contrib_gpu.py
deleted file mode 100644
index 9b43c79..0000000
--- a/tests/python/gpu/test_gluon_contrib_gpu.py
+++ /dev/null
@@ -1,87 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-"""Tests of the contrib APIs in Gluon only with gpu"""
-
-from __future__ import print_function
-import mxnet as mx
-from mxnet.gluon import nn
-from mxnet.gluon import contrib
-from mxnet.gluon.contrib.cnn import DeformableConvolution
-
-
-def test_DeformableConvolution():
- """test of the deformable convolution layer with possible combinations of arguments,
- currently this layer only supports gpu
- """
- net = nn.HybridSequential()
- net.add(
- DeformableConvolution(10, kernel_size=(3, 3), strides=1, padding=0),
- DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, activation='relu',
- offset_use_bias=False, use_bias=False),
- DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, activation='relu',
- offset_use_bias=False),
- DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, activation='relu',
- use_bias=False),
- DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, offset_use_bias=False, use_bias=False),
- DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, offset_use_bias=False),
- DeformableConvolution(12, kernel_size=(3, 2), strides=1, padding=0, use_bias=False),
- DeformableConvolution(12, kernel_size=(3, 2), strides=1, padding=0, use_bias=False, num_deformable_group=4),
- )
-
- try:
- ctx = mx.gpu()
- _ = mx.nd.array([0], ctx=ctx)
- except mx.base.MXNetError:
- print("deformable_convolution only supports GPU")
- return
-
- net.initialize(force_reinit=True, ctx=ctx)
- net.hybridize()
-
- x = mx.nd.random.uniform(shape=(8, 5, 30, 31), ctx=ctx)
- with mx.autograd.record():
- y = net(x)
- y.backward()
-
-def test_ModulatedDeformableConvolution():
- """test of the deformable convolution layer with possible combinations of arguments,
- currently this layer only supports gpu
- """
- net = nn.HybridSequential()
- net.add(
- DeformableConvolution(10, kernel_size=(3, 3), strides=1, padding=0),
- DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, activation='relu',
- offset_use_bias=False, use_bias=False),
- DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, activation='relu',
- offset_use_bias=False),
- DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, activation='relu',
- use_bias=False),
- DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, offset_use_bias=False, use_bias=False),
- DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, offset_use_bias=False),
- DeformableConvolution(12, kernel_size=(3, 2), strides=1, padding=0, use_bias=False),
- DeformableConvolution(12, kernel_size=(3, 2), strides=1, padding=0, use_bias=False, num_deformable_group=4),
- )
-
- ctx = mx.gpu()
- net.initialize(force_reinit=True, ctx=ctx)
- net.hybridize()
-
- x = mx.nd.random.uniform(shape=(8, 5, 30, 31), ctx=ctx)
- with mx.autograd.record():
- y = net(x)
- y.backward()
-
diff --git a/tests/python/gpu/test_gluon_gpu.py b/tests/python/gpu/test_gluon_gpu.py
index 27325db..ddf9200 100644
--- a/tests/python/gpu/test_gluon_gpu.py
+++ b/tests/python/gpu/test_gluon_gpu.py
@@ -93,9 +93,9 @@ def test_lstmp():
weights = {k: rand_ndarray(v) for k, v in shapes.items()}
lstm_layer = gluon.rnn.LSTM(hidden_size, projection_size=projection_size,
input_size=input_size)
- lstm_cell = gluon.contrib.rnn.LSTMPCell(hidden_size=hidden_size,
- projection_size=projection_size,
- input_size=input_size)
+ lstm_cell = gluon.rnn.LSTMPCell(hidden_size=hidden_size,
+ projection_size=projection_size,
+ input_size=input_size)
lstm_layer.initialize(ctx=ctx)
lstm_cell.initialize(ctx=ctx)
layer_params = lstm_layer.collect_params()
@@ -351,9 +351,9 @@ def test_global_norm_clip_multi_device():
def _check_batchnorm_result(input, num_devices=1, cuda=False):
from mxnet.gluon.utils import split_and_load
def _find_bn(module):
- if isinstance(module, (mx.gluon.nn.BatchNorm, mx.gluon.contrib.nn.SyncBatchNorm)):
+ if isinstance(module, (mx.gluon.nn.BatchNorm, mx.gluon.nn.SyncBatchNorm)):
return module
- elif isinstance(module.module, (mx.gluon.nn.BatchNorm, mx.gluon.contrib.nn.SyncBatchNorm)):
+ elif isinstance(module.module, (mx.gluon.nn.BatchNorm, mx.gluon.nn.SyncBatchNorm)):
return module.module
raise RuntimeError('BN not found')
@@ -376,7 +376,7 @@ def _check_batchnorm_result(input, num_devices=1, cuda=False):
nch = input.shape[1]
bn1 = mx.gluon.nn.BatchNorm(in_channels=nch)
- bn2 = mx.gluon.contrib.nn.SyncBatchNorm(in_channels=nch, num_devices=num_devices)
+ bn2 = mx.gluon.nn.SyncBatchNorm(in_channels=nch, num_devices=num_devices)
bn1.initialize(ctx=ctx_list[0])
bn2.initialize(ctx=ctx_list)
diff --git a/tests/python/gpu/test_operator_gpu.py b/tests/python/gpu/test_operator_gpu.py
index 81b9510..38784de 100644
--- a/tests/python/gpu/test_operator_gpu.py
+++ b/tests/python/gpu/test_operator_gpu.py
@@ -1664,7 +1664,7 @@ def test_deformable_convolution_with_type():
tol = {np.dtype(np.float32): 1e-1,
np.dtype(np.float64): 1e-3}
- sym = mx.sym.contrib.DeformableConvolution(num_filter=3, kernel=(3,3), name='deformable_conv')
+ sym = mx.sym.npx.deformable_convolution(num_filter=3, kernel=(3,3), name='deformable_conv')
# since atomicAdd does not support fp16 (which deformable conv uses in backward), we do not test fp16 here
ctx_list = [{'ctx': mx.gpu(0),
'deformable_conv_data': (2, 2, 10, 10),
@@ -1718,7 +1718,7 @@ def test_deformable_convolution_options():
'deformable_conv_offset': (2, 18, 7, 7),
'type_dict': {'deformable_conv_data': np.float32, 'deformable_conv_offset': np.float32}},
]
- sym = mx.sym.contrib.DeformableConvolution(num_filter=3, kernel=(3,3), pad=(1,1), name='deformable_conv')
+ sym = mx.sym.npx.deformable_convolution(num_filter=3, kernel=(3,3), pad=(1,1), name='deformable_conv')
check_consistency(sym, ctx_list, scale=0.1, rtol=tol, atol=tol)
# Stride > 1
@@ -1739,7 +1739,7 @@ def test_deformable_convolution_options():
'deformable_conv_offset': (2, 18, 3, 3),
'type_dict': {'deformable_conv_data': np.float32, 'deformable_conv_offset': np.float32}},
]
- sym = mx.sym.contrib.DeformableConvolution(num_filter=3, kernel=(3,3), stride=(2,2), name='deformable_conv')
+ sym = mx.sym.npx.deformable_convolution(num_filter=3, kernel=(3,3), stride=(2,2), name='deformable_conv')
check_consistency(sym, ctx_list, scale=0.1, rtol=tol, atol=tol)
# Dilate > 1
@@ -1760,7 +1760,7 @@ def test_deformable_convolution_options():
'deformable_conv_offset': (2, 18, 3, 3),
'type_dict': {'deformable_conv_data': np.float32, 'deformable_conv_offset': np.float32}},
]
- sym = mx.sym.contrib.DeformableConvolution(num_filter=3, kernel=(3,3), dilate=(2,2), name='deformable_conv')
+ sym = mx.sym.npx.deformable_convolution(num_filter=3, kernel=(3,3), dilate=(2,2), name='deformable_conv')
check_consistency(sym, ctx_list, scale=0.1, rtol=tol, atol=tol)
# Deformable group > 1
@@ -1781,7 +1781,7 @@ def test_deformable_convolution_options():
'deformable_conv_offset': (2, 36, 5, 5),
'type_dict': {'deformable_conv_data': np.float32, 'deformable_conv_offset': np.float32}},
]
- sym = mx.sym.contrib.DeformableConvolution(num_filter=4, kernel=(3,3), num_deformable_group=2, name='deformable_conv')
+ sym = mx.sym.npx.deformable_convolution(num_filter=4, kernel=(3,3), num_deformable_group=2, name='deformable_conv')
check_consistency(sym, ctx_list, scale=0.1, rtol=tol, atol=tol)
diff --git a/tests/python/unittest/test_contrib_autograd.py b/tests/python/unittest/test_contrib_autograd.py
deleted file mode 100644
index c383744..0000000
--- a/tests/python/unittest/test_contrib_autograd.py
+++ /dev/null
@@ -1,193 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-import mxnet.ndarray as nd
-from mxnet.contrib.autograd import *
-from mxnet.test_utils import *
-from common import setup_module, with_seed, teardown_module, xfail_when_nonstandard_decimal_separator
-
-def autograd_assert(*args, **kwargs):
- func = kwargs["func"]
- grad_f = kwargs["grad_func"]
- argnum = kwargs["argnum"] if 'argnum' in kwargs else None
-
- grad_func = grad_and_loss(func, argnum)
- grad_vals, output = grad_func(*args)
- res = func(*args)
- assert same(output.asnumpy(), res.asnumpy())
- grad_res = grad_f(*args)
- assert len(grad_vals) == len(grad_res)
- for a, b in zip(grad_vals, grad_res):
- assert same(a.asnumpy(), b.asnumpy())
-
-@xfail_when_nonstandard_decimal_separator
-@with_seed()
-def test_unary_func():
- x = nd.uniform(shape=(4, 5))
- f_exp = lambda x: nd.exp(x)
- f_exp_grad = lambda x: [nd.exp(x)]
- autograd_assert(x, func=f_exp, grad_func=f_exp_grad)
- f_half = lambda x: x/2
- f_half_grad = lambda x: [nd.ones(x.shape) * 0.5]
- autograd_assert(x, func=f_half, grad_func=f_half_grad)
- f_square = lambda x: x**2
- f_square_grad = lambda x: [2*x]
- autograd_assert(x, func=f_square, grad_func=f_square_grad)
-
-@with_seed()
-def test_binary_func():
- x = nd.uniform(shape=(4, 5))
- y = nd.uniform(shape=(4, 5))
- f_add = lambda x, y: x+y
- f_add_grad = lambda x, y: [nd.ones(x.shape), nd.ones(y.shape)]
- autograd_assert(x, y, func=f_add, grad_func=f_add_grad)
- f_mul = lambda x, y: x*y
- f_mul_grad = lambda x, y: [y, x]
- autograd_assert(x, y, func=f_mul, grad_func=f_mul_grad)
- f_compose = lambda x, y: x+x*y
- f_compose_grad = lambda x, y: [nd.ones(x.shape) + y, x]
- autograd_assert(x, y, func=f_compose, grad_func=f_compose_grad)
-
-@with_seed()
-def test_operator_with_state():
- def f_fc(a, b, weight, bias):
- x = a*b
- fc = nd.FullyConnected(
- x, weight, bias, num_hidden=32)
- return fc
-
- a = nd.uniform(shape=(64, 50))
- b = nd.uniform(shape=(64, 50))
- weight = nd.uniform(shape=(32, 50))
- bias = nd.uniform(shape=(32, ))
-
- grad_func = grad_and_loss(f_fc)
- grad_vals, outputs = grad_func(a, b, weight, bias)
- # (TODO) assert
-
-@with_seed()
-def test_argnum():
- def f_with_mode(a, b, mode):
- if mode:
- return a+b
- else:
- return a*b
-
- a = nd.uniform(shape=(3, 2))
- b = nd.uniform(shape=(3, 2))
- f_add_grad = lambda x, y, mode: [nd.ones(x.shape), nd.ones(y.shape)]
- f_mul_grad = lambda x, y, mode: [y, x]
- autograd_assert(a, b, True,
- argnum=[0, 1], func=f_with_mode, grad_func=f_add_grad)
- autograd_assert(a, b, False,
- argnum=[0, 1], func=f_with_mode, grad_func=f_mul_grad)
-
-
-@with_seed()
-def test_training():
- x = nd.ones((10, 10))
- with train_section():
- y = nd.Dropout(x, p=0.5)
- assert not (y.asnumpy() == x.asnumpy()).all()
- with test_section():
- y = nd.Dropout(x, p=0.5)
- assert (y.asnumpy() == x.asnumpy()).all()
-
-
-@with_seed()
-def test_out_grads():
- x = nd.ones((3, 5))
- dx = nd.zeros_like(x)
- mark_variables([x], [dx])
- da = None
- db = nd.array([1,2,3,4,5])
- dc = nd.array([5,4,3,2,1])
-
- with train_section():
- a, b, c = nd.split(x, axis=0, num_outputs=3, squeeze_axis=True)
- backward([a, b, c], [da, db, dc])
-
- assert (dx.asnumpy() == np.array(
- [[1,1,1,1,1],
- [1,2,3,4,5],
- [5,4,3,2,1]])).all()
-
-
-@with_seed()
-def test_detach_updated_grad():
- x = nd.ones((2, 2))
- dx = nd.zeros_like(x)
- y = nd.ones_like(x)
- dy = nd.zeros_like(x)
- mark_variables([x, y], [dx, dy])
- assert x._fresh_grad == False
- assert y._fresh_grad == False
-
- with train_section():
- x2 = x + 2
- y2 = x2 + y
- y2.backward()
- assert (dx.asnumpy() == 1).all()
- assert x._fresh_grad == True
- assert y._fresh_grad == True
-
- dx[:] = 0
- x._fresh_grad = False
- y._fresh_grad = False
- assert x._fresh_grad == False
- assert y._fresh_grad == False
- with train_section():
- x2 = x + 2
- x2 = x2.detach()
- y2 = x2 + y
- y2.backward()
- assert (dx.asnumpy() == 0).all()
- assert y._fresh_grad == True
- assert x._fresh_grad == False
-
-
-@with_seed()
-def test_retain_grad():
- x = mx.nd.ones((2, 2))
- dx = mx.nd.zeros((2, 2))
- mark_variables([x], [dx], grad_reqs='add')
- with train_section():
- y = x + 1
- y.backward(retain_graph=False)
- assert (dx.asnumpy() == 1).all()
-
- dx[:] = 0
- with train_section():
- y = x + 1
- y.backward(retain_graph=True)
- y.backward(retain_graph=False)
- assert (dx.asnumpy() == 2).all()
-
- # The following sequence should throw an exception. We discard the expected
- # stderr stack trace output for this operation to keep the test logs clean.
- with discard_stderr():
- try:
- with train_section():
- y = x + 1
- y.backward()
- y.backward()
- except Exception:
- return
-
- raise AssertionError(
- "differentiating the same graph twice without retain_graph should fail")
-
diff --git a/tests/python/unittest/test_contrib_operator.py b/tests/python/unittest/test_contrib_operator.py
index 37a02a7..23cfdf8 100644
--- a/tests/python/unittest/test_contrib_operator.py
+++ b/tests/python/unittest/test_contrib_operator.py
@@ -410,39 +410,3 @@ def test_op_mrcnn_mask_target():
assert_almost_equal(mask_targets.asnumpy(), gt_mask_targets.asnumpy())
assert_almost_equal(mask_cls.asnumpy(), gt_mask_cls.asnumpy())
-
-@with_seed()
-def test_modulated_deformable_convolution():
- for num_batch in [1, 2]:
- for num_channel_data, num_deformable_group in itertools.product([4, 8], [1, 2]):
- for input_height, input_width in itertools.product([5, 6], [5, 6]):
- for dilate in [(1, 1), (2, 2)]:
- for grad_nodes in [['im_data'], ['offset_data'], ['weight']]:
- output_height = input_height
- output_width = input_width
- im_data = np.random.rand(num_batch, num_channel_data, input_height, input_width)
- offset_data = \
- np.random.rand(num_batch, num_deformable_group * 3 * 3 * 2, output_height, output_width)\
- * 0.8 + 0.1
- mask_data = np.random.rand(num_batch, num_deformable_group * 3 * 3, output_height, output_width)
- mask_data = 0.5 * (1 + np.tanh(0.5 * mask_data)) # sigmoid
- weight = np.random.normal(0, 0.001, (num_channel_data, num_channel_data, 3, 3))
- bias = np.zeros(num_channel_data)
-
- im_data_var = mx.symbol.Variable(name="im_data")
- offset_data_var = mx.symbol.Variable(name="offset_data")
- mask_data_var = mx.symbol.Variable(name="mask_data")
- weight_var = mx.symbol.Variable(name="weight")
- bias_var = mx.symbol.Variable(name="bias")
- op = mx.sym.contrib.ModulatedDeformableConvolution(name='test_op', data=im_data_var,
- offset=offset_data_var, mask=mask_data_var,
- weight=weight_var, bias=bias_var,
- num_filter=num_channel_data, pad=dilate,
- kernel=(3, 3), stride=(1, 1), dilate=dilate,
- num_deformable_group=num_deformable_group)
- if grad_nodes[0] == 'offset_data':
- # wider tolerance needed for coordinate differential
- rtol, atol = 1.0, 1e-2
- else:
- rtol, atol = 0.05, 1e-3
-
diff --git a/tests/python/unittest/test_contrib_text.py b/tests/python/unittest/test_contrib_text.py
deleted file mode 100644
index 44d4422..0000000
--- a/tests/python/unittest/test_contrib_text.py
+++ /dev/null
@@ -1,794 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# 'License'); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-# coding: utf-8
-
-from collections import Counter
-
-from common import assertRaises
-from mxnet import ndarray as nd
-from mxnet.test_utils import *
-from mxnet.contrib import text
-
-import pytest
-
-
-def _get_test_str_of_tokens(token_delim, seq_delim):
- seq1 = token_delim + token_delim.join(['Life', 'is', 'great', '!']) + token_delim + seq_delim
- seq2 = token_delim + token_delim.join(['life', 'is', 'good', '.']) + token_delim + seq_delim
- seq3 = token_delim + token_delim.join(['life', "isn't", 'bad', '.']) + token_delim + seq_delim
- seqs = seq1 + seq2 + seq3
- return seqs
-
-
-def _test_count_tokens_from_str_with_delims(token_delim, seq_delim):
- source_str = _get_test_str_of_tokens(token_delim, seq_delim)
-
- cnt1 = text.utils.count_tokens_from_str(
- source_str, token_delim, seq_delim, to_lower=False)
- assert cnt1 == Counter(
- {'is': 2, 'life': 2, '.': 2, 'Life': 1, 'great': 1, '!': 1, 'good': 1, "isn't": 1,
- 'bad': 1})
-
- cnt2 = text.utils.count_tokens_from_str(
- source_str, token_delim, seq_delim, to_lower=True)
- assert cnt2 == Counter(
- {'life': 3, 'is': 2, '.': 2, 'great': 1, '!': 1, 'good': 1, "isn't": 1, 'bad': 1})
-
- counter_to_update = Counter({'life': 2})
-
- cnt3 = text.utils.count_tokens_from_str(
- source_str, token_delim, seq_delim, to_lower=False,
- counter_to_update=counter_to_update.copy())
- assert cnt3 == Counter(
- {'is': 2, 'life': 4, '.': 2, 'Life': 1, 'great': 1, '!': 1, 'good': 1, "isn't": 1,
- 'bad': 1})
-
- cnt4 = text.utils.count_tokens_from_str(
- source_str, token_delim, seq_delim, to_lower=True,
- counter_to_update=counter_to_update.copy())
- assert cnt4 == Counter(
- {'life': 5, 'is': 2, '.': 2, 'great': 1, '!': 1, 'good': 1, "isn't": 1, 'bad': 1})
-
-
-def test_count_tokens_from_str():
- _test_count_tokens_from_str_with_delims(' ', '\n')
- _test_count_tokens_from_str_with_delims('IS', 'LIFE')
-
-
-def test_tokens_to_indices():
- counter = Counter(['a', 'b', 'b', 'c', 'c', 'c', 'some_word$'])
-
- vocab = text.vocab.Vocabulary(counter, most_freq_count=None, min_freq=1, unknown_token='<unk>',
- reserved_tokens=None)
-
- i1 = vocab.to_indices('c')
- assert i1 == 1
-
- i2 = vocab.to_indices(['c'])
- assert i2 == [1]
-
- i3 = vocab.to_indices(['<unk>', 'non-exist'])
- assert i3 == [0, 0]
-
- i4 = vocab.to_indices(['a', 'non-exist', 'a', 'b'])
- assert i4 == [3, 0, 3, 2]
-
-
-def test_indices_to_tokens():
- counter = Counter(['a', 'b', 'b', 'c', 'c', 'c', 'some_word$'])
-
- vocab = text.vocab.Vocabulary(counter, most_freq_count=None, min_freq=1,
- unknown_token='<unknown>', reserved_tokens=None)
- i1 = vocab.to_tokens(1)
- assert i1 == 'c'
-
- i2 = vocab.to_tokens([1])
- assert i2 == ['c']
-
- i3 = vocab.to_tokens([0, 0])
- assert i3 == ['<unknown>', '<unknown>']
-
- i4 = vocab.to_tokens([3, 0, 3, 2])
- assert i4 == ['a', '<unknown>', 'a', 'b']
-
- assertRaises(ValueError, vocab.to_tokens, 100)
-
-
-def test_download_embed():
- @text.embedding.register
- class Test(text.embedding._TokenEmbedding):
- # 33 bytes.
- pretrained_file_name_sha1 = \
- {'embedding_test.vec': '29b9a6511cf4b5aae293c44a9ec1365b74f2a2f8'}
- namespace = 'test'
-
- def __init__(self, embedding_root='embeddings', init_unknown_vec=nd.zeros, **kwargs):
- pretrained_file_name = 'embedding_test.vec'
- Test._check_pretrained_file_names(pretrained_file_name)
-
- super(Test, self).__init__(**kwargs)
-
- pretrained_file_path = Test._get_pretrained_file(embedding_root, pretrained_file_name)
-
- self._load_embedding(pretrained_file_path, ' ', init_unknown_vec)
-
- test_embed = text.embedding.create('test')
- assert test_embed.token_to_idx['hello'] == 1
- assert test_embed.token_to_idx['world'] == 2
- assert_almost_equal(test_embed.idx_to_vec[1].asnumpy(), (nd.arange(5) + 1).asnumpy())
- assert_almost_equal(test_embed.idx_to_vec[2].asnumpy(), (nd.arange(5) + 6).asnumpy())
- assert_almost_equal(test_embed.idx_to_vec[0].asnumpy(), nd.zeros((5,)).asnumpy())
-
-
-def _mk_my_pretrain_file(path, token_delim, pretrain_file):
- path = os.path.expanduser(path)
- if not os.path.exists(path):
- os.makedirs(path)
- seq1 = token_delim.join(['a', '0.1', '0.2', '0.3', '0.4', '0.5']) + '\n'
- seq2 = token_delim.join(['b', '0.6', '0.7', '0.8', '0.9', '1.0']) + '\n'
- seqs = seq1 + seq2
- with open(os.path.join(path, pretrain_file), 'w') as fout:
- fout.write(seqs)
-
-
-def _mk_my_pretrain_file2(path, token_delim, pretrain_file):
- path = os.path.expanduser(path)
- if not os.path.exists(path):
- os.makedirs(path)
- seq1 = token_delim.join(['a', '0.01', '0.02', '0.03', '0.04', '0.05']) + '\n'
- seq2 = token_delim.join(['c', '0.06', '0.07', '0.08', '0.09', '0.1']) + '\n'
- seqs = seq1 + seq2
- with open(os.path.join(path, pretrain_file), 'w') as fout:
- fout.write(seqs)
-
-
-def _mk_my_pretrain_file3(path, token_delim, pretrain_file):
- path = os.path.expanduser(path)
- if not os.path.exists(path):
- os.makedirs(path)
- seq1 = token_delim.join(['a', '0.1', '0.2', '0.3', '0.4', '0.5']) + '\n'
- seq2 = token_delim.join(['b', '0.6', '0.7', '0.8', '0.9', '1.0']) + '\n'
- seq3 = token_delim.join(['<unk1>', '1.1', '1.2', '1.3', '1.4',
- '1.5']) + '\n'
- seqs = seq1 + seq2 + seq3
- with open(os.path.join(path, pretrain_file), 'w') as fout:
- fout.write(seqs)
-
-
-def _mk_my_pretrain_file4(path, token_delim, pretrain_file):
- path = os.path.expanduser(path)
- if not os.path.exists(path):
- os.makedirs(path)
- seq1 = token_delim.join(['a', '0.01', '0.02', '0.03', '0.04', '0.05']) + '\n'
- seq2 = token_delim.join(['c', '0.06', '0.07', '0.08', '0.09', '0.1']) + '\n'
- seq3 = token_delim.join(['<unk2>', '0.11', '0.12', '0.13', '0.14', '0.15']) + '\n'
- seqs = seq1 + seq2 + seq3
- with open(os.path.join(path, pretrain_file), 'w') as fout:
- fout.write(seqs)
-
-
-def _mk_my_invalid_pretrain_file(path, token_delim, pretrain_file):
- path = os.path.expanduser(path)
- if not os.path.exists(path):
- os.makedirs(path)
- seq1 = token_delim.join(['a', '0.1', '0.2', '0.3', '0.4', '0.5']) + '\n'
- seq2 = token_delim.join(['b', '0.6', '0.7', '0.8', '0.9', '1.0']) + '\n'
- seq3 = token_delim.join(['c']) + '\n'
- seqs = seq1 + seq2 + seq3
- with open(os.path.join(path, pretrain_file), 'w') as fout:
- fout.write(seqs)
-
-
-def _mk_my_invalid_pretrain_file2(path, token_delim, pretrain_file):
- path = os.path.expanduser(path)
- if not os.path.exists(path):
- os.makedirs(path)
- seq1 = token_delim.join(['a', '0.1', '0.2', '0.3', '0.4', '0.5']) + '\n'
- seq2 = token_delim.join(['b', '0.6', '0.7', '0.8', '0.9', '1.0']) + '\n'
- seq3 = token_delim.join(['c', '0.6', '0.7', '0.8']) + '\n'
- seqs = seq1 + seq2 + seq3
- with open(os.path.join(path, pretrain_file), 'w') as fout:
- fout.write(seqs)
-
-
-def test_custom_embed():
- embed_root = 'embeddings'
- embed_name = 'my_embed'
- elem_delim = '\t'
- pretrain_file = 'my_pretrain_file.txt'
-
- _mk_my_pretrain_file(os.path.join(embed_root, embed_name), elem_delim, pretrain_file)
-
- pretrain_file_path = os.path.join(embed_root, embed_name, pretrain_file)
-
- my_embed = text.embedding.CustomEmbedding(pretrain_file_path, elem_delim)
-
- assert len(my_embed) == 3
- assert my_embed.vec_len == 5
- assert my_embed.token_to_idx['a'] == 1
- assert my_embed.idx_to_token[1] == 'a'
-
- first_vec = my_embed.idx_to_vec[0]
- assert_almost_equal(first_vec.asnumpy(), np.array([0, 0, 0, 0, 0]))
-
- unk_vec = my_embed.get_vecs_by_tokens('A')
- assert_almost_equal(unk_vec.asnumpy(), np.array([0, 0, 0, 0, 0]))
-
- a_vec = my_embed.get_vecs_by_tokens('A', lower_case_backup=True)
- assert_almost_equal(a_vec.asnumpy(), np.array([0.1, 0.2, 0.3, 0.4, 0.5]))
-
- unk_vecs = my_embed.get_vecs_by_tokens(['<un...@unk>', '<un...@unk>'])
- assert_almost_equal(unk_vecs.asnumpy(), np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]))
-
- # Test loaded unknown vectors.
- pretrain_file2 = 'my_pretrain_file2.txt'
- _mk_my_pretrain_file3(os.path.join(embed_root, embed_name), elem_delim, pretrain_file2)
- pretrain_file_path = os.path.join(embed_root, embed_name, pretrain_file2)
- my_embed2 = text.embedding.CustomEmbedding(pretrain_file_path, elem_delim,
- init_unknown_vec=nd.ones, unknown_token='<unk>')
- unk_vec2 = my_embed2.get_vecs_by_tokens('<unk>')
- assert_almost_equal(unk_vec2.asnumpy(), np.array([1, 1, 1, 1, 1]))
- unk_vec2 = my_embed2.get_vecs_by_tokens('<un...@unk>')
- assert_almost_equal(unk_vec2.asnumpy(), np.array([1, 1, 1, 1, 1]))
-
- my_embed3 = text.embedding.CustomEmbedding(pretrain_file_path, elem_delim,
- init_unknown_vec=nd.ones, unknown_token='<unk1>')
- unk_vec3 = my_embed3.get_vecs_by_tokens('<unk1>')
- assert_almost_equal(unk_vec3.asnumpy(), np.array([1.1, 1.2, 1.3, 1.4, 1.5]))
- unk_vec3 = my_embed3.get_vecs_by_tokens('<un...@unk>')
- assert_almost_equal(unk_vec3.asnumpy(), np.array([1.1, 1.2, 1.3, 1.4, 1.5]))
-
- # Test error handling.
- invalid_pretrain_file = 'invalid_pretrain_file.txt'
- _mk_my_invalid_pretrain_file(os.path.join(embed_root, embed_name), elem_delim,
- invalid_pretrain_file)
- pretrain_file_path = os.path.join(embed_root, embed_name, invalid_pretrain_file)
- assertRaises(AssertionError, text.embedding.CustomEmbedding, pretrain_file_path, elem_delim)
-
- invalid_pretrain_file2 = 'invalid_pretrain_file2.txt'
- _mk_my_invalid_pretrain_file2(os.path.join(embed_root, embed_name), elem_delim,
- invalid_pretrain_file2)
- pretrain_file_path = os.path.join(embed_root, embed_name, invalid_pretrain_file2)
- assertRaises(AssertionError, text.embedding.CustomEmbedding, pretrain_file_path, elem_delim)
-
-
-def test_vocabulary():
- counter = Counter(['a', 'b', 'b', 'c', 'c', 'c', 'some_word$'])
-
- v1 = text.vocab.Vocabulary(counter, most_freq_count=None, min_freq=1, unknown_token='<unk>',
- reserved_tokens=None)
- assert len(v1) == 5
- assert v1.token_to_idx == {'<unk>': 0, 'c': 1, 'b': 2, 'a': 3, 'some_word$': 4}
- assert v1.idx_to_token[1] == 'c'
- assert v1.unknown_token == '<unk>'
- assert v1.reserved_tokens is None
-
- v2 = text.vocab.Vocabulary(counter, most_freq_count=None, min_freq=2, unknown_token='<unk>',
- reserved_tokens=None)
- assert len(v2) == 3
- assert v2.token_to_idx == {'<unk>': 0, 'c': 1, 'b': 2}
- assert v2.idx_to_token[1] == 'c'
- assert v2.unknown_token == '<unk>'
- assert v2.reserved_tokens is None
-
- v3 = text.vocab.Vocabulary(counter, most_freq_count=None, min_freq=100, unknown_token='<unk>',
- reserved_tokens=None)
- assert len(v3) == 1
- assert v3.token_to_idx == {'<unk>': 0}
- assert v3.idx_to_token[0] == '<unk>'
- assert v3.unknown_token == '<unk>'
- assert v3.reserved_tokens is None
-
- v4 = text.vocab.Vocabulary(counter, most_freq_count=2, min_freq=1, unknown_token='<unk>',
- reserved_tokens=None)
- assert len(v4) == 3
- assert v4.token_to_idx == {'<unk>': 0, 'c': 1, 'b': 2}
- assert v4.idx_to_token[1] == 'c'
- assert v4.unknown_token == '<unk>'
- assert v4.reserved_tokens is None
-
- v5 = text.vocab.Vocabulary(counter, most_freq_count=3, min_freq=1, unknown_token='<unk>',
- reserved_tokens=None)
- assert len(v5) == 4
- assert v5.token_to_idx == {'<unk>': 0, 'c': 1, 'b': 2, 'a': 3}
- assert v5.idx_to_token[1] == 'c'
- assert v5.unknown_token == '<unk>'
- assert v5.reserved_tokens is None
-
- v6 = text.vocab.Vocabulary(counter, most_freq_count=100, min_freq=1, unknown_token='<unk>',
- reserved_tokens=None)
- assert len(v6) == 5
- assert v6.token_to_idx == {'<unk>': 0, 'c': 1, 'b': 2, 'a': 3,
- 'some_word$': 4}
- assert v6.idx_to_token[1] == 'c'
- assert v6.unknown_token == '<unk>'
- assert v6.reserved_tokens is None
-
- v7 = text.vocab.Vocabulary(counter, most_freq_count=1, min_freq=2, unknown_token='<unk>',
- reserved_tokens=None)
- assert len(v7) == 2
- assert v7.token_to_idx == {'<unk>': 0, 'c': 1}
- assert v7.idx_to_token[1] == 'c'
- assert v7.unknown_token == '<unk>'
- assert v7.reserved_tokens is None
-
- assertRaises(AssertionError, text.vocab.Vocabulary, counter, most_freq_count=None,
- min_freq=0, unknown_token='<unknown>', reserved_tokens=['b'])
-
- assertRaises(AssertionError, text.vocab.Vocabulary, counter, most_freq_count=None,
- min_freq=1, unknown_token='<unknown>', reserved_tokens=['b', 'b'])
-
- assertRaises(AssertionError, text.vocab.Vocabulary, counter, most_freq_count=None,
- min_freq=1, unknown_token='<unknown>', reserved_tokens=['b', '<unknown>'])
-
- v8 = text.vocab.Vocabulary(counter, most_freq_count=None, min_freq=1, unknown_token='<unknown>',
- reserved_tokens=['b'])
- assert len(v8) == 5
- assert v8.token_to_idx == {'<unknown>': 0, 'b': 1, 'c': 2, 'a': 3, 'some_word$': 4}
- assert v8.idx_to_token[1] == 'b'
- assert v8.unknown_token == '<unknown>'
- assert v8.reserved_tokens == ['b']
-
- v9 = text.vocab.Vocabulary(counter, most_freq_count=None, min_freq=2, unknown_token='<unk>',
- reserved_tokens=['b', 'a'])
- assert len(v9) == 4
- assert v9.token_to_idx == {'<unk>': 0, 'b': 1, 'a': 2, 'c': 3}
- assert v9.idx_to_token[1] == 'b'
- assert v9.unknown_token == '<unk>'
- assert v9.reserved_tokens == ['b', 'a']
-
- v10 = text.vocab.Vocabulary(counter, most_freq_count=None, min_freq=100, unknown_token='<unk>',
- reserved_tokens=['b', 'c'])
- assert len(v10) == 3
- assert v10.token_to_idx == {'<unk>': 0, 'b': 1, 'c': 2}
- assert v10.idx_to_token[1] == 'b'
- assert v10.unknown_token == '<unk>'
- assert v10.reserved_tokens == ['b', 'c']
-
- v11 = text.vocab.Vocabulary(counter, most_freq_count=1, min_freq=2, unknown_token='<unk>',
- reserved_tokens=['<pad>', 'b'])
- assert len(v11) == 4
- assert v11.token_to_idx == {'<unk>': 0, '<pad>': 1, 'b': 2, 'c': 3}
- assert v11.idx_to_token[1] == '<pad>'
- assert v11.unknown_token == '<unk>'
- assert v11.reserved_tokens == ['<pad>', 'b']
-
- v12 = text.vocab.Vocabulary(counter, most_freq_count=None, min_freq=2, unknown_token='b',
- reserved_tokens=['<pad>'])
- assert len(v12) == 3
- assert v12.token_to_idx == {'b': 0, '<pad>': 1, 'c': 2}
- assert v12.idx_to_token[1] == '<pad>'
- assert v12.unknown_token == 'b'
- assert v12.reserved_tokens == ['<pad>']
-
- v13 = text.vocab.Vocabulary(counter, most_freq_count=None, min_freq=2, unknown_token='a',
- reserved_tokens=['<pad>'])
- assert len(v13) == 4
- assert v13.token_to_idx == {'a': 0, '<pad>': 1, 'c': 2, 'b': 3}
- assert v13.idx_to_token[1] == '<pad>'
- assert v13.unknown_token == 'a'
- assert v13.reserved_tokens == ['<pad>']
-
- counter_tuple = Counter([('a', 'a'), ('b', 'b'), ('b', 'b'), ('c', 'c'), ('c', 'c'), ('c', 'c'),
- ('some_word$', 'some_word$')])
-
- v14 = text.vocab.Vocabulary(counter_tuple, most_freq_count=None, min_freq=1,
- unknown_token=('<unk>', '<unk>'), reserved_tokens=None)
- assert len(v14) == 5
- assert v14.token_to_idx == {('<unk>', '<unk>'): 0, ('c', 'c'): 1, ('b', 'b'): 2, ('a', 'a'): 3,
- ('some_word$', 'some_word$'): 4}
- assert v14.idx_to_token[1] == ('c', 'c')
- assert v14.unknown_token == ('<unk>', '<unk>')
- assert v14.reserved_tokens is None
-
-
-def test_custom_embedding_with_vocabulary():
- embed_root = 'embeddings'
- embed_name = 'my_embed'
- elem_delim = '\t'
- pretrain_file = 'my_pretrain_file1.txt'
-
- _mk_my_pretrain_file(os.path.join(embed_root, embed_name), elem_delim, pretrain_file)
-
- pretrain_file_path = os.path.join(embed_root, embed_name, pretrain_file)
-
- counter = Counter(['a', 'b', 'b', 'c', 'c', 'c', 'some_word$'])
-
- v1 = text.vocab.Vocabulary(counter, most_freq_count=None, min_freq=1, unknown_token='<unk>',
- reserved_tokens=['<pad>'])
-
- e1 = text.embedding.CustomEmbedding(pretrain_file_path, elem_delim, init_unknown_vec=nd.ones,
- vocabulary=v1)
-
- assert e1.token_to_idx == {'<unk>': 0, '<pad>': 1, 'c': 2, 'b': 3, 'a': 4, 'some_word$': 5}
- assert e1.idx_to_token == ['<unk>', '<pad>', 'c', 'b', 'a', 'some_word$']
-
- assert_almost_equal(e1.idx_to_vec.asnumpy(),
- np.array([[1, 1, 1, 1, 1],
- [1, 1, 1, 1, 1],
- [1, 1, 1, 1, 1],
- [0.6, 0.7, 0.8, 0.9, 1],
- [0.1, 0.2, 0.3, 0.4, 0.5],
- [1, 1, 1, 1, 1]])
- )
-
- assert e1.vec_len == 5
- assert e1.reserved_tokens == ['<pad>']
-
- assert_almost_equal(e1.get_vecs_by_tokens('c').asnumpy(),
- np.array([1, 1, 1, 1, 1])
- )
-
- assert_almost_equal(e1.get_vecs_by_tokens(['c']).asnumpy(),
- np.array([[1, 1, 1, 1, 1]])
- )
-
- assert_almost_equal(e1.get_vecs_by_tokens(['a', 'not_exist']).asnumpy(),
- np.array([[0.1, 0.2, 0.3, 0.4, 0.5],
- [1, 1, 1, 1, 1]])
- )
-
- assert_almost_equal(e1.get_vecs_by_tokens(['a', 'b']).asnumpy(),
- np.array([[0.1, 0.2, 0.3, 0.4, 0.5],
- [0.6, 0.7, 0.8, 0.9, 1]])
- )
-
- assert_almost_equal(e1.get_vecs_by_tokens(['A', 'b']).asnumpy(),
- np.array([[1, 1, 1, 1, 1],
- [0.6, 0.7, 0.8, 0.9, 1]])
- )
-
- assert_almost_equal(e1.get_vecs_by_tokens(['A', 'b'], lower_case_backup=True).asnumpy(),
- np.array([[0.1, 0.2, 0.3, 0.4, 0.5],
- [0.6, 0.7, 0.8, 0.9, 1]])
- )
-
- e1.update_token_vectors(['a', 'b'],
- nd.array([[2, 2, 2, 2, 2],
- [3, 3, 3, 3, 3]])
- )
-
- assert_almost_equal(e1.idx_to_vec.asnumpy(),
- np.array([[1, 1, 1, 1, 1],
- [1, 1, 1, 1, 1],
- [1, 1, 1, 1, 1],
- [3, 3, 3, 3, 3],
- [2, 2, 2, 2, 2],
- [1, 1, 1, 1, 1]])
- )
-
- assertRaises(ValueError, e1.update_token_vectors, 'unknown$$$', nd.array([0, 0, 0, 0, 0]))
-
- assertRaises(AssertionError, e1.update_token_vectors, '<unk>',
- nd.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]))
-
- assertRaises(AssertionError, e1.update_token_vectors, '<unk>', nd.array([0]))
-
- e1.update_token_vectors(['<unk>'], nd.array([0, 0, 0, 0, 0]))
- assert_almost_equal(e1.idx_to_vec.asnumpy(),
- np.array([[0, 0, 0, 0, 0],
- [1, 1, 1, 1, 1],
- [1, 1, 1, 1, 1],
- [3, 3, 3, 3, 3],
- [2, 2, 2, 2, 2],
- [1, 1, 1, 1, 1]])
- )
- e1.update_token_vectors(['<unk>'], nd.array([[10, 10, 10, 10, 10]]))
- assert_almost_equal(e1.idx_to_vec.asnumpy(),
- np.array([[10, 10, 10, 10, 10],
- [1, 1, 1, 1, 1],
- [1, 1, 1, 1, 1],
- [3, 3, 3, 3, 3],
- [2, 2, 2, 2, 2],
- [1, 1, 1, 1, 1]])
- )
- e1.update_token_vectors('<unk>', nd.array([0, 0, 0, 0, 0]))
- assert_almost_equal(e1.idx_to_vec.asnumpy(),
- np.array([[0, 0, 0, 0, 0],
- [1, 1, 1, 1, 1],
- [1, 1, 1, 1, 1],
- [3, 3, 3, 3, 3],
- [2, 2, 2, 2, 2],
- [1, 1, 1, 1, 1]])
- )
- e1.update_token_vectors('<unk>', nd.array([[10, 10, 10, 10, 10]]))
- assert_almost_equal(e1.idx_to_vec.asnumpy(),
- np.array([[10, 10, 10, 10, 10],
- [1, 1, 1, 1, 1],
- [1, 1, 1, 1, 1],
- [3, 3, 3, 3, 3],
- [2, 2, 2, 2, 2],
- [1, 1, 1, 1, 1]])
- )
-
-
-@pytest.mark.skip(reason='https://github.com/apache/incubator-mxnet/issues/18282')
-def test_composite_embedding_with_one_embedding():
- embed_root = 'embeddings'
- embed_name = 'my_embed'
- elem_delim = '\t'
- pretrain_file = 'my_pretrain_file1.txt'
-
- _mk_my_pretrain_file(os.path.join(embed_root, embed_name), elem_delim, pretrain_file)
-
- pretrain_file_path = os.path.join(embed_root, embed_name, pretrain_file)
-
- my_embed = text.embedding.CustomEmbedding(pretrain_file_path, elem_delim,
- init_unknown_vec=nd.ones)
-
- counter = Counter(['a', 'b', 'b', 'c', 'c', 'c', 'some_word$'])
-
- v1 = text.vocab.Vocabulary(counter, most_freq_count=None, min_freq=1, unknown_token='<unk>',
- reserved_tokens=['<pad>'])
- ce1 = text.embedding.CompositeEmbedding(v1, my_embed)
-
- assert ce1.token_to_idx == {'<unk>': 0, '<pad>': 1, 'c': 2, 'b': 3, 'a': 4, 'some_word$': 5}
- assert ce1.idx_to_token == ['<unk>', '<pad>', 'c', 'b', 'a', 'some_word$']
-
- assert_almost_equal(ce1.idx_to_vec.asnumpy(),
- np.array([[1, 1, 1, 1, 1],
- [1, 1, 1, 1, 1],
- [1, 1, 1, 1, 1],
- [0.6, 0.7, 0.8, 0.9, 1],
- [0.1, 0.2, 0.3, 0.4, 0.5],
- [1, 1, 1, 1, 1]])
- )
-
- assert ce1.vec_len == 5
- assert ce1.reserved_tokens == ['<pad>']
-
- assert_almost_equal(ce1.get_vecs_by_tokens('c').asnumpy(),
- np.array([1, 1, 1, 1, 1])
- )
-
- assert_almost_equal(ce1.get_vecs_by_tokens(['c']).asnumpy(),
- np.array([[1, 1, 1, 1, 1]])
- )
-
- assert_almost_equal(ce1.get_vecs_by_tokens(['a', 'not_exist']).asnumpy(),
- np.array([[0.1, 0.2, 0.3, 0.4, 0.5],
- [1, 1, 1, 1, 1]])
- )
-
- assert_almost_equal(ce1.get_vecs_by_tokens(['a', 'b']).asnumpy(),
- np.array([[0.1, 0.2, 0.3, 0.4, 0.5],
- [0.6, 0.7, 0.8, 0.9, 1]])
- )
-
- assert_almost_equal(ce1.get_vecs_by_tokens(['A', 'b']).asnumpy(),
- np.array([[1, 1, 1, 1, 1],
- [0.6, 0.7, 0.8, 0.9, 1]])
- )
-
- assert_almost_equal(ce1.get_vecs_by_tokens(['A', 'b'], lower_case_backup=True).asnumpy(),
- np.array([[0.1, 0.2, 0.3, 0.4, 0.5],
- [0.6, 0.7, 0.8, 0.9, 1]])
- )
-
- ce1.update_token_vectors(['a', 'b'],
- nd.array([[2, 2, 2, 2, 2],
- [3, 3, 3, 3, 3]])
- )
-
- assert_almost_equal(ce1.idx_to_vec.asnumpy(),
- np.array([[1, 1, 1, 1, 1],
- [1, 1, 1, 1, 1],
- [1, 1, 1, 1, 1],
- [3, 3, 3, 3, 3],
- [2, 2, 2, 2, 2],
- [1, 1, 1, 1, 1]])
- )
-
- assertRaises(ValueError, ce1.update_token_vectors, 'unknown$$$', nd.array([0, 0, 0, 0, 0]))
-
- assertRaises(AssertionError, ce1.update_token_vectors, '<unk>',
- nd.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]))
-
- assertRaises(AssertionError, ce1.update_token_vectors, '<unk>', nd.array([0]))
-
- ce1.update_token_vectors(['<unk>'], nd.array([0, 0, 0, 0, 0]))
- assert_almost_equal(ce1.idx_to_vec.asnumpy(),
- np.array([[0, 0, 0, 0, 0],
- [1, 1, 1, 1, 1],
- [1, 1, 1, 1, 1],
- [3, 3, 3, 3, 3],
- [2, 2, 2, 2, 2],
- [1, 1, 1, 1, 1]])
- )
- ce1.update_token_vectors(['<unk>'], nd.array([[10, 10, 10, 10, 10]]))
- assert_almost_equal(ce1.idx_to_vec.asnumpy(),
- np.array([[10, 10, 10, 10, 10],
- [1, 1, 1, 1, 1],
- [1, 1, 1, 1, 1],
- [3, 3, 3, 3, 3],
- [2, 2, 2, 2, 2],
- [1, 1, 1, 1, 1]])
- )
- ce1.update_token_vectors('<unk>', nd.array([0, 0, 0, 0, 0]))
- assert_almost_equal(ce1.idx_to_vec.asnumpy(),
- np.array([[0, 0, 0, 0, 0],
- [1, 1, 1, 1, 1],
- [1, 1, 1, 1, 1],
- [3, 3, 3, 3, 3],
- [2, 2, 2, 2, 2],
- [1, 1, 1, 1, 1]])
- )
- ce1.update_token_vectors('<unk>', nd.array([[10, 10, 10, 10, 10]]))
- assert_almost_equal(ce1.idx_to_vec.asnumpy(),
- np.array([[10, 10, 10, 10, 10],
- [1, 1, 1, 1, 1],
- [1, 1, 1, 1, 1],
- [3, 3, 3, 3, 3],
- [2, 2, 2, 2, 2],
- [1, 1, 1, 1, 1]])
- )
-
-
-def test_composite_embedding_with_two_embeddings():
- embed_root = '.'
- embed_name = 'my_embed'
- elem_delim = '\t'
- pretrain_file1 = 'my_pretrain_file1.txt'
- pretrain_file2 = 'my_pretrain_file2.txt'
-
- _mk_my_pretrain_file(os.path.join(embed_root, embed_name), elem_delim, pretrain_file1)
- _mk_my_pretrain_file2(os.path.join(embed_root, embed_name), elem_delim, pretrain_file2)
-
- pretrain_file_path1 = os.path.join(embed_root, embed_name, pretrain_file1)
- pretrain_file_path2 = os.path.join(embed_root, embed_name, pretrain_file2)
-
- my_embed1 = text.embedding.CustomEmbedding(pretrain_file_path1, elem_delim,
- init_unknown_vec=nd.ones)
- my_embed2 = text.embedding.CustomEmbedding(pretrain_file_path2, elem_delim)
-
- counter = Counter(['a', 'b', 'b', 'c', 'c', 'c', 'some_word$'])
-
- v1 = text.vocab.Vocabulary(counter, most_freq_count=None, min_freq=1, unknown_token='<unk>',
- reserved_tokens=None)
- ce1 = text.embedding.CompositeEmbedding(v1, [my_embed1, my_embed2])
-
- assert ce1.token_to_idx == {'<unk>': 0, 'c': 1, 'b': 2, 'a': 3, 'some_word$': 4}
- assert ce1.idx_to_token == ['<unk>', 'c', 'b', 'a', 'some_word$']
-
- assert_almost_equal(ce1.idx_to_vec.asnumpy(),
- np.array([[1, 1, 1, 1, 1, 0, 0, 0, 0, 0],
- [1, 1, 1, 1, 1, 0.06, 0.07, 0.08, 0.09, 0.1],
- [0.6, 0.7, 0.8, 0.9, 1, 0, 0, 0, 0, 0],
- [0.1, 0.2, 0.3, 0.4, 0.5,
- 0.01, 0.02, 0.03, 0.04, 0.05],
- [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]])
- )
-
- assert ce1.vec_len == 10
- assert ce1.reserved_tokens is None
- assert_almost_equal(ce1.get_vecs_by_tokens('c').asnumpy(),
- np.array([1, 1, 1, 1, 1, 0.06, 0.07, 0.08, 0.09, 0.1])
- )
-
- assert_almost_equal(ce1.get_vecs_by_tokens(['b', 'not_exist']).asnumpy(),
- np.array([[0.6, 0.7, 0.8, 0.9, 1, 0, 0, 0, 0, 0],
- [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]])
- )
-
- ce1.update_token_vectors(['a', 'b'],
- nd.array([[2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
- [3, 3, 3, 3, 3, 3, 3, 3, 3, 3]])
- )
- assert_almost_equal(ce1.idx_to_vec.asnumpy(),
- np.array([[1, 1, 1, 1, 1, 0, 0, 0, 0, 0],
- [1, 1, 1, 1, 1, 0.06, 0.07, 0.08, 0.09, 0.1],
- [3, 3, 3, 3, 3, 3, 3, 3, 3, 3],
- [2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
- [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]])
- )
-
- # Test loaded unknown tokens
- pretrain_file3 = 'my_pretrain_file3.txt'
- pretrain_file4 = 'my_pretrain_file4.txt'
-
- _mk_my_pretrain_file3(os.path.join(embed_root, embed_name), elem_delim, pretrain_file3)
- _mk_my_pretrain_file4(os.path.join(embed_root, embed_name), elem_delim, pretrain_file4)
-
- pretrain_file_path3 = os.path.join(embed_root, embed_name, pretrain_file3)
- pretrain_file_path4 = os.path.join(embed_root, embed_name, pretrain_file4)
-
- my_embed3 = text.embedding.CustomEmbedding(pretrain_file_path3, elem_delim,
- init_unknown_vec=nd.ones, unknown_token='<unk1>')
- my_embed4 = text.embedding.CustomEmbedding(pretrain_file_path4, elem_delim,
- unknown_token='<unk2>')
-
- v2 = text.vocab.Vocabulary(counter, most_freq_count=None, min_freq=1, unknown_token='<unk>',
- reserved_tokens=None)
- ce2 = text.embedding.CompositeEmbedding(v2, [my_embed3, my_embed4])
- assert_almost_equal(ce2.idx_to_vec.asnumpy(),
- np.array([[1.1, 1.2, 1.3, 1.4, 1.5,
- 0.11, 0.12, 0.13, 0.14, 0.15],
- [1.1, 1.2, 1.3, 1.4, 1.5,
- 0.06, 0.07, 0.08, 0.09, 0.1],
- [0.6, 0.7, 0.8, 0.9, 1,
- 0.11, 0.12, 0.13, 0.14, 0.15],
- [0.1, 0.2, 0.3, 0.4, 0.5,
- 0.01, 0.02, 0.03, 0.04, 0.05],
- [1.1, 1.2, 1.3, 1.4, 1.5,
- 0.11, 0.12, 0.13, 0.14, 0.15]])
- )
-
- v3 = text.vocab.Vocabulary(counter, most_freq_count=None, min_freq=1, unknown_token='<unk1>',
- reserved_tokens=None)
- ce3 = text.embedding.CompositeEmbedding(v3, [my_embed3, my_embed4])
- assert_almost_equal(ce3.idx_to_vec.asnumpy(),
- np.array([[1.1, 1.2, 1.3, 1.4, 1.5,
- 0.11, 0.12, 0.13, 0.14, 0.15],
- [1.1, 1.2, 1.3, 1.4, 1.5,
- 0.06, 0.07, 0.08, 0.09, 0.1],
- [0.6, 0.7, 0.8, 0.9, 1,
- 0.11, 0.12, 0.13, 0.14, 0.15],
- [0.1, 0.2, 0.3, 0.4, 0.5,
- 0.01, 0.02, 0.03, 0.04, 0.05],
- [1.1, 1.2, 1.3, 1.4, 1.5,
- 0.11, 0.12, 0.13, 0.14, 0.15]])
- )
-
- v4 = text.vocab.Vocabulary(counter, most_freq_count=None, min_freq=1, unknown_token='<unk2>',
- reserved_tokens=None)
- ce4 = text.embedding.CompositeEmbedding(v4, [my_embed3, my_embed4])
- assert_almost_equal(ce4.idx_to_vec.asnumpy(),
- np.array([[1.1, 1.2, 1.3, 1.4, 1.5,
- 0.11, 0.12, 0.13, 0.14, 0.15],
- [1.1, 1.2, 1.3, 1.4, 1.5,
- 0.06, 0.07, 0.08, 0.09, 0.1],
- [0.6, 0.7, 0.8, 0.9, 1,
- 0.11, 0.12, 0.13, 0.14, 0.15],
- [0.1, 0.2, 0.3, 0.4, 0.5,
- 0.01, 0.02, 0.03, 0.04, 0.05],
- [1.1, 1.2, 1.3, 1.4, 1.5,
- 0.11, 0.12, 0.13, 0.14, 0.15]])
- )
-
- counter2 = Counter(['b', 'b', 'c', 'c', 'c', 'some_word$'])
-
- v5 = text.vocab.Vocabulary(counter2, most_freq_count=None, min_freq=1, unknown_token='a',
- reserved_tokens=None)
- ce5 = text.embedding.CompositeEmbedding(v5, [my_embed3, my_embed4])
- assert ce5.token_to_idx == {'a': 0, 'c': 1, 'b': 2, 'some_word$': 3}
- assert ce5.idx_to_token == ['a', 'c', 'b', 'some_word$']
- assert_almost_equal(ce5.idx_to_vec.asnumpy(),
- np.array([[1.1, 1.2, 1.3, 1.4, 1.5,
- 0.11, 0.12, 0.13, 0.14, 0.15],
- [1.1, 1.2, 1.3, 1.4, 1.5,
- 0.06, 0.07, 0.08, 0.09, 0.1],
- [0.6, 0.7, 0.8, 0.9, 1,
- 0.11, 0.12, 0.13, 0.14, 0.15],
- [1.1, 1.2, 1.3, 1.4, 1.5,
- 0.11, 0.12, 0.13, 0.14, 0.15]])
- )
-
-
-def test_get_and_pretrain_file_names():
- assert len(text.embedding.get_pretrained_file_names(
- embedding_name='fasttext')) == 327
-
- assert len(text.embedding.get_pretrained_file_names(embedding_name='glove')) == 10
-
- reg = text.embedding.get_pretrained_file_names(embedding_name=None)
-
- assert len(reg['glove']) == 10
- assert len(reg['fasttext']) == 327
-
- assertRaises(KeyError, text.embedding.get_pretrained_file_names, 'unknown$$')
-
diff --git a/tests/python/unittest/test_gluon.py b/tests/python/unittest/test_gluon.py
index 71ae41c2..eb07f43 100644
--- a/tests/python/unittest/test_gluon.py
+++ b/tests/python/unittest/test_gluon.py
@@ -22,7 +22,7 @@ import mxnet as mx
from mxnet import gluon
from mxnet.gluon import nn
from mxnet.base import py_str, MXNetError
-from mxnet.test_utils import assert_almost_equal, default_context
+from mxnet.test_utils import assert_almost_equal, default_context, assert_allclose
from mxnet.util import is_np_array
from mxnet.ndarray.ndarray import _STORAGE_TYPE_STR_TO_ID
from mxnet.test_utils import use_np
@@ -714,9 +714,9 @@ def test_sync_batchnorm():
from mxnet.gluon.utils import split_and_load
def _find_bn(module):
- if isinstance(module, (mx.gluon.nn.BatchNorm, mx.gluon.contrib.nn.SyncBatchNorm)):
+ if isinstance(module, (mx.gluon.nn.BatchNorm, mx.gluon.nn.SyncBatchNorm)):
return module
- elif isinstance(module.module, (mx.gluon.nn.BatchNorm, mx.gluon.contrib.nn.SyncBatchNorm)):
+ elif isinstance(module.module, (mx.gluon.nn.BatchNorm, mx.gluon.nn.SyncBatchNorm)):
return module.module
raise RuntimeError('BN not found')
@@ -739,7 +739,7 @@ def test_sync_batchnorm():
nch = input.shape[1] if input.ndim > 1 else 1
bn1 = mx.gluon.nn.BatchNorm(in_channels=nch)
- bn2 = mx.gluon.contrib.nn.SyncBatchNorm(
+ bn2 = mx.gluon.nn.SyncBatchNorm(
in_channels=nch, num_devices=num_devices)
bn1.initialize(ctx=ctx_list[0])
@@ -2066,8 +2066,7 @@ def test_concat():
kernel,
**kwargs):
super(Net, self).__init__(**kwargs)
- from mxnet.gluon.contrib.nn import HybridConcurrent
- self.concat = HybridConcurrent(axis=check_dim)
+ self.concat = nn.HybridConcatenate(axis=check_dim)
for i in range(input_num):
self.concat.add(gluon.nn.Conv2D(chn_num, (kernel, kernel)))
@@ -3091,3 +3090,181 @@ def test_no_memory_leak_in_gluon():
self.net = mx.gluon.nn.Dense(10, in_units=10)
net = MyNet()
net.initialize()
+
+def test_DeformableConvolution():
+ """test of the deformable convolution layer with possible combinations of arguments,
+ currently this layer only supports gpu
+ """
+ try:
+ ctx = mx.gpu()
+ _ = mx.nd.array([0], ctx=ctx)
+ except mx.base.MXNetError:
+ pytest.skip("deformable_convolution only supports GPU")
+ net = nn.HybridSequential()
+ net.add(
+ nn.DeformableConvolution(10, kernel_size=(3, 3), strides=1, padding=0),
+ nn.DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, activation='relu',
+ offset_use_bias=False, use_bias=False),
+ nn.DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, activation='relu',
+ offset_use_bias=False),
+ nn.DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, activation='relu',
+ use_bias=False),
+ nn.DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, offset_use_bias=False, use_bias=False),
+ nn.DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, offset_use_bias=False),
+ nn.DeformableConvolution(12, kernel_size=(3, 2), strides=1, padding=0, use_bias=False),
+ nn.DeformableConvolution(12, kernel_size=(3, 2), strides=1, padding=0, use_bias=False, num_deformable_group=4),
+ )
+
+ net.initialize(force_reinit=True, ctx=ctx)
+ net.hybridize()
+
+ x = mx.nd.random.uniform(shape=(8, 5, 30, 31), ctx=ctx)
+ with mx.autograd.record():
+ y = net(x)
+ y.backward()
+
+@with_seed()
+def test_ModulatedDeformableConvolution():
+ """test of the deformable convolution layer with possible combinations of arguments,
+ currently this layer only supports gpu
+ """
+ net = nn.HybridSequential()
+ net.add(
+ nn.DeformableConvolution(10, kernel_size=(3, 3), strides=1, padding=0),
+ nn.DeformableConvolution(10, kernel_size=(1, 1), strides=1, padding=0),
+ nn.DeformableConvolution(10, kernel_size=(5, 5), strides=1, padding=0),
+ nn.DeformableConvolution(10, kernel_size=(3, 5), strides=1, padding=0),
+ nn.DeformableConvolution(10, kernel_size=(5, 1), strides=1, padding=0, num_deformable_group=2),
+ nn.DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, activation='relu',
+ offset_use_bias=False, use_bias=False),
+ nn.DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, activation='relu',
+ offset_use_bias=False),
+ nn.DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, activation='relu',
+ use_bias=False),
+ nn.DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, offset_use_bias=False, use_bias=False),
+ nn.DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, offset_use_bias=False),
+ nn.DeformableConvolution(12, kernel_size=(3, 2), strides=1, padding=0, use_bias=False),
+ nn.DeformableConvolution(12, kernel_size=(3, 2), strides=1, padding=0, use_bias=False, num_deformable_group=4),
+ )
+
+ ctx = default_context()
+ net.initialize(force_reinit=True, ctx=ctx)
+ net.hybridize()
+
+ x = mx.nd.random.uniform(shape=(8, 5, 30, 31), ctx=ctx)
+ with mx.autograd.record():
+ y = net(x)
+
+def test_concatenate():
+ model = nn.HybridConcatenate(axis=1)
+ model.add(nn.Dense(128, activation='tanh', in_units=10))
+ model.add(nn.Dense(64, activation='tanh', in_units=10))
+ model.add(nn.Dense(32, in_units=10))
+ model2 = nn.Concatenate(axis=1)
+ model2.add(nn.Dense(128, activation='tanh', in_units=10))
+ model2.add(nn.Dense(64, activation='tanh', in_units=10))
+ model2.add(nn.Dense(32, in_units=10))
+
+ # symbol
+ x = mx.sym.var('data')
+ y = model(x)
+ assert len(y.list_arguments()) == 7
+
+ # ndarray
+ model.initialize(mx.init.Xavier(magnitude=2.24))
+ model2.initialize(mx.init.Xavier(magnitude=2.24))
+ x = model(mx.nd.zeros((32, 10)))
+ x2 = model2(mx.nd.zeros((32, 10)))
+ assert x.shape == (32, 224)
+ assert x2.shape == (32, 224)
+ x.wait_to_read()
+ x2.wait_to_read()
+
+@with_seed()
+def test_identity():
+ model = nn.Identity()
+ x = mx.nd.random.uniform(shape=(128, 33, 64))
+ assert_almost_equal(model(x), x)
+
+def test_pixelshuffle1d():
+ nchan = 2
+ up_x = 2
+ nx = 3
+ shape_before = (1, nchan * up_x, nx)
+ shape_after = (1, nchan, nx * up_x)
+ layer = nn.PixelShuffle1D(up_x)
+ x = mx.nd.arange(np.prod(shape_before)).reshape(shape_before)
+ y = layer(x)
+ assert y.shape == shape_after
+ assert_allclose(
+ y,
+ [[[0, 3, 1, 4, 2, 5],
+ [6, 9, 7, 10, 8, 11]]]
+ )
+
+def test_pixelshuffle2d():
+ nchan = 2
+ up_x = 2
+ up_y = 3
+ nx = 2
+ ny = 3
+ shape_before = (1, nchan * up_x * up_y, nx, ny)
+ shape_after = (1, nchan, nx * up_x, ny * up_y)
+ layer = nn.PixelShuffle2D((up_x, up_y))
+ x = mx.nd.arange(np.prod(shape_before)).reshape(shape_before)
+ y = layer(x)
+ assert y.shape == shape_after
+ # - Channels are reshaped to form 2x3 blocks
+ # - Within each block, the increment is `nx * ny` when increasing the column
+ # index by 1
+ # - Increasing the block index adds an offset of 1
+ # - Increasing the channel index adds an offset of `nx * up_x * ny * up_y`
+ assert_allclose(
+ y,
+ [[[[ 0, 6, 12, 1, 7, 13, 2, 8, 14],
+ [18, 24, 30, 19, 25, 31, 20, 26, 32],
+ [ 3, 9, 15, 4, 10, 16, 5, 11, 17],
+ [21, 27, 33, 22, 28, 34, 23, 29, 35]],
+
+ [[36, 42, 48, 37, 43, 49, 38, 44, 50],
+ [54, 60, 66, 55, 61, 67, 56, 62, 68],
+ [39, 45, 51, 40, 46, 52, 41, 47, 53],
+ [57, 63, 69, 58, 64, 70, 59, 65, 71]]]]
+ )
+
+def test_pixelshuffle3d():
+ nchan = 1
+ up_x = 2
+ up_y = 1
+ up_z = 2
+ nx = 2
+ ny = 3
+ nz = 4
+ shape_before = (1, nchan * up_x * up_y * up_z, nx, ny, nz)
+ shape_after = (1, nchan, nx * up_x, ny * up_y, nz * up_z)
+ layer = nn.PixelShuffle3D((up_x, up_y, up_z))
+ x = mx.nd.arange(np.prod(shape_before)).reshape(shape_before)
+ y = layer(x)
+ assert y.shape == shape_after
+ # - Channels are reshaped to form 2x1x2 blocks
+ # - Within each block, the increment is `nx * ny * nz` when increasing the
+ # column index by 1, e.g. the block [[[ 0, 24]], [[48, 72]]]
+ # - Increasing the block index adds an offset of 1
+ assert_allclose(
+ y,
+ [[[[[ 0, 24, 1, 25, 2, 26, 3, 27],
+ [ 4, 28, 5, 29, 6, 30, 7, 31],
+ [ 8, 32, 9, 33, 10, 34, 11, 35]],
+
+ [[48, 72, 49, 73, 50, 74, 51, 75],
+ [52, 76, 53, 77, 54, 78, 55, 79],
+ [56, 80, 57, 81, 58, 82, 59, 83]],
+
+ [[12, 36, 13, 37, 14, 38, 15, 39],
+ [16, 40, 17, 41, 18, 42, 19, 43],
+ [20, 44, 21, 45, 22, 46, 23, 47]],
+
+ [[60, 84, 61, 85, 62, 86, 63, 87],
+ [64, 88, 65, 89, 66, 90, 67, 91],
+ [68, 92, 69, 93, 70, 94, 71, 95]]]]]
+ )
diff --git a/tests/python/unittest/test_gluon_contrib.py b/tests/python/unittest/test_gluon_contrib.py
deleted file mode 100644
index f3c7000..0000000
--- a/tests/python/unittest/test_gluon_contrib.py
+++ /dev/null
@@ -1,426 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-from __future__ import print_function
-import mxnet as mx
-import copy
-from mxnet import gluon
-from mxnet.gluon import contrib
-from mxnet.gluon import nn
-from mxnet.gluon.contrib.nn import (
- Concurrent, HybridConcurrent, Identity, PixelShuffle1D,
- PixelShuffle2D, PixelShuffle3D)
-from mxnet.test_utils import almost_equal, default_context, assert_almost_equal, assert_allclose
-from common import setup_module, with_seed, teardown_module
-import numpy as np
-
-
-def check_rnn_cell(cell, in_shape=(10, 50), out_shape=(10, 100), begin_state=None):
- inputs = [mx.sym.Variable('rnn_t%d_data'%i) for i in range(3)]
- outputs, _ = cell.unroll(3, inputs, begin_state=begin_state)
- outputs = mx.sym.Group(outputs)
- assert sorted(cell.collect_params().keys()) == ['h2h_bias', 'h2h_weight',
- 'i2h_bias', 'i2h_weight']
- assert outputs.list_outputs() == [type(cell).__name__.lower() + name for name in ['_t0_out_output', '_t1_out_output', '_t2_out_output']]
-
- args, outs, auxs = outputs.infer_shape(rnn_t0_data=in_shape,
- rnn_t1_data=in_shape,
- rnn_t2_data=in_shape)
- assert outs == [out_shape] * 3
-
-
-def check_rnn_forward(layer, inputs):
- inputs.attach_grad()
- layer.initialize()
- with mx.autograd.record():
- layer.unroll(3, inputs, merge_outputs=True)[0].backward()
- mx.autograd.backward(layer.unroll(3, inputs, merge_outputs=False)[0])
- mx.nd.waitall()
-
-
-@with_seed()
-def test_rnn_cells():
- check_rnn_forward(contrib.rnn.Conv1DLSTMCell((5, 7), 10, (3,), (3,)),
- mx.nd.ones((8, 3, 5, 7)))
- check_rnn_forward(contrib.rnn.Conv1DRNNCell((5, 7), 10, (3,), (3,)),
- mx.nd.ones((8, 3, 5, 7)))
- check_rnn_forward(contrib.rnn.Conv1DGRUCell((5, 7), 10, (3,), (3,)),
- mx.nd.ones((8, 3, 5, 7)))
-
- net = mx.gluon.rnn.SequentialRNNCell()
- net.add(contrib.rnn.Conv1DLSTMCell((5, 7), 10, (3,), (3,)))
- net.add(contrib.rnn.Conv1DRNNCell((10, 5), 11, (3,), (3,)))
- net.add(contrib.rnn.Conv1DGRUCell((11, 3), 12, (3,), (3,)))
- check_rnn_forward(net, mx.nd.ones((8, 3, 5, 7)))
-
-
-@with_seed()
-def test_convrnn():
- cell = contrib.rnn.Conv1DRNNCell((10, 50), 100, 3, 3)
- check_rnn_cell(cell, in_shape=(1, 10, 50), out_shape=(1, 100, 48))
-
- cell = contrib.rnn.Conv2DRNNCell((10, 20, 50), 100, 3, 3)
- check_rnn_cell(cell, in_shape=(1, 10, 20, 50), out_shape=(1, 100, 18, 48))
-
- cell = contrib.rnn.Conv3DRNNCell((10, 20, 30, 50), 100, 3, 3)
- check_rnn_cell(cell, in_shape=(1, 10, 20, 30, 50), out_shape=(1, 100, 18, 28, 48))
-
-
-@with_seed()
-def test_convlstm():
- cell = contrib.rnn.Conv1DLSTMCell((10, 50), 100, 3, 3)
- check_rnn_cell(cell, in_shape=(1, 10, 50), out_shape=(1, 100, 48))
-
- cell = contrib.rnn.Conv2DLSTMCell((10, 20, 50), 100, 3, 3)
- check_rnn_cell(cell, in_shape=(1, 10, 20, 50), out_shape=(1, 100, 18, 48))
-
- cell = contrib.rnn.Conv3DLSTMCell((10, 20, 30, 50), 100, 3, 3)
- check_rnn_cell(cell, in_shape=(1, 10, 20, 30, 50), out_shape=(1, 100, 18, 28, 48))
-
-
-@with_seed()
-def test_convgru():
- cell = contrib.rnn.Conv1DGRUCell((10, 50), 100, 3, 3)
- check_rnn_cell(cell, in_shape=(1, 10, 50), out_shape=(1, 100, 48))
-
- cell = contrib.rnn.Conv2DGRUCell((10, 20, 50), 100, 3, 3)
- check_rnn_cell(cell, in_shape=(1, 10, 20, 50), out_shape=(1, 100, 18, 48))
-
- cell = contrib.rnn.Conv3DGRUCell((10, 20, 30, 50), 100, 3, 3)
- check_rnn_cell(cell, in_shape=(1, 10, 20, 30, 50), out_shape=(1, 100, 18, 28, 48))
-
-
-@with_seed()
-def test_conv_fill_shape():
- cell = contrib.rnn.Conv1DLSTMCell((0, 7), 10, (3,), (3,))
- cell.hybridize()
- check_rnn_forward(cell, mx.nd.ones((8, 3, 5, 7)))
- assert cell.i2h_weight.shape[1] == 5, cell.i2h_weight.shape[1]
-
-
-@with_seed()
-def test_lstmp():
- nhid = 100
- nproj = 64
- cell = contrib.rnn.LSTMPCell(nhid, nproj)
- inputs = [mx.sym.Variable('rnn_t%d_data'%i) for i in range(3)]
- outputs, _ = cell.unroll(3, inputs)
- outputs = mx.sym.Group(outputs)
- expected_params = ['h2h_bias', 'h2h_weight', 'h2r_weight', 'i2h_bias', 'i2h_weight']
- expected_outputs = [type(cell).__name__.lower() + name for name in ['_t0_out_output', '_t1_out_output', '_t2_out_output']]
- assert sorted(cell.collect_params().keys()) == expected_params
- assert outputs.list_outputs() == expected_outputs, outputs.list_outputs()
-
- args, outs, auxs = outputs.infer_shape(rnn_t0_data=(10,50), rnn_t1_data=(10,50), rnn_t2_data=(10,50))
- assert outs == [(10, nproj), (10, nproj), (10, nproj)]
-
-
-@with_seed()
-def test_vardrop():
- def check_vardrop(drop_inputs, drop_states, drop_outputs):
- cell = contrib.rnn.VariationalDropoutCell(mx.gluon.rnn.RNNCell(100),
- drop_outputs=drop_outputs,
- drop_states=drop_states,
- drop_inputs=drop_inputs)
- cell.initialize(init='xavier')
- input_data = mx.nd.random_uniform(shape=(10, 3, 50), ctx=mx.context.current_context())
- with mx.autograd.record():
- outputs1, _ = cell.unroll(3, input_data, merge_outputs=True)
- mx.nd.waitall()
- outputs2, _ = cell.unroll(3, input_data, merge_outputs=True)
- assert not almost_equal(outputs1.asnumpy(), outputs2.asnumpy())
-
- inputs = [mx.sym.Variable('rnn_t%d_data'%i) for i in range(3)]
- outputs, _ = cell.unroll(3, inputs, merge_outputs=False)
- outputs = mx.sym.Group(outputs)
-
- args, outs, auxs = outputs.infer_shape(rnn_t0_data=(10,50), rnn_t1_data=(10,50), rnn_t2_data=(10,50))
- assert outs == [(10, 100), (10, 100), (10, 100)]
-
- cell.reset()
- cell.hybridize()
- with mx.autograd.record():
- outputs3, _ = cell.unroll(3, input_data, merge_outputs=True)
- mx.nd.waitall()
- outputs4, _ = cell.unroll(3, input_data, merge_outputs=True)
- assert not almost_equal(outputs3.asnumpy(), outputs4.asnumpy())
- assert not almost_equal(outputs1.asnumpy(), outputs3.asnumpy())
-
- check_vardrop(0.5, 0.5, 0.5)
- check_vardrop(0.5, 0, 0.5)
-
-
-def test_concurrent():
- model = HybridConcurrent(axis=1)
- model.add(nn.Dense(128, activation='tanh', in_units=10))
- model.add(nn.Dense(64, activation='tanh', in_units=10))
- model.add(nn.Dense(32, in_units=10))
- model2 = Concurrent(axis=1)
- model2.add(nn.Dense(128, activation='tanh', in_units=10))
- model2.add(nn.Dense(64, activation='tanh', in_units=10))
- model2.add(nn.Dense(32, in_units=10))
-
- # symbol
- x = mx.sym.var('data')
- y = model(x)
- assert len(y.list_arguments()) == 7
-
- # ndarray
- model.initialize(mx.init.Xavier(magnitude=2.24))
- model2.initialize(mx.init.Xavier(magnitude=2.24))
- x = model(mx.nd.zeros((32, 10)))
- x2 = model2(mx.nd.zeros((32, 10)))
- assert x.shape == (32, 224)
- assert x2.shape == (32, 224)
- x.wait_to_read()
- x2.wait_to_read()
-
-@with_seed()
-def test_identity():
- model = Identity()
- x = mx.nd.random.uniform(shape=(128, 33, 64))
- assert_almost_equal(model(x), x)
-
-def test_pixelshuffle1d():
- nchan = 2
- up_x = 2
- nx = 3
- shape_before = (1, nchan * up_x, nx)
- shape_after = (1, nchan, nx * up_x)
- layer = PixelShuffle1D(up_x)
- x = mx.nd.arange(np.prod(shape_before)).reshape(shape_before)
- y = layer(x)
- assert y.shape == shape_after
- assert_allclose(
- y,
- [[[0, 3, 1, 4, 2, 5],
- [6, 9, 7, 10, 8, 11]]]
- )
-
-def test_pixelshuffle2d():
- nchan = 2
- up_x = 2
- up_y = 3
- nx = 2
- ny = 3
- shape_before = (1, nchan * up_x * up_y, nx, ny)
- shape_after = (1, nchan, nx * up_x, ny * up_y)
- layer = PixelShuffle2D((up_x, up_y))
- x = mx.nd.arange(np.prod(shape_before)).reshape(shape_before)
- y = layer(x)
- assert y.shape == shape_after
- # - Channels are reshaped to form 2x3 blocks
- # - Within each block, the increment is `nx * ny` when increasing the column
- # index by 1
- # - Increasing the block index adds an offset of 1
- # - Increasing the channel index adds an offset of `nx * up_x * ny * up_y`
- assert_allclose(
- y,
- [[[[ 0, 6, 12, 1, 7, 13, 2, 8, 14],
- [18, 24, 30, 19, 25, 31, 20, 26, 32],
- [ 3, 9, 15, 4, 10, 16, 5, 11, 17],
- [21, 27, 33, 22, 28, 34, 23, 29, 35]],
-
- [[36, 42, 48, 37, 43, 49, 38, 44, 50],
- [54, 60, 66, 55, 61, 67, 56, 62, 68],
- [39, 45, 51, 40, 46, 52, 41, 47, 53],
- [57, 63, 69, 58, 64, 70, 59, 65, 71]]]]
- )
-
-def test_pixelshuffle3d():
- nchan = 1
- up_x = 2
- up_y = 1
- up_z = 2
- nx = 2
- ny = 3
- nz = 4
- shape_before = (1, nchan * up_x * up_y * up_z, nx, ny, nz)
- shape_after = (1, nchan, nx * up_x, ny * up_y, nz * up_z)
- layer = PixelShuffle3D((up_x, up_y, up_z))
- x = mx.nd.arange(np.prod(shape_before)).reshape(shape_before)
- y = layer(x)
- assert y.shape == shape_after
- # - Channels are reshaped to form 2x1x2 blocks
- # - Within each block, the increment is `nx * ny * nz` when increasing the
- # column index by 1, e.g. the block [[[ 0, 24]], [[48, 72]]]
- # - Increasing the block index adds an offset of 1
- assert_allclose(
- y,
- [[[[[ 0, 24, 1, 25, 2, 26, 3, 27],
- [ 4, 28, 5, 29, 6, 30, 7, 31],
- [ 8, 32, 9, 33, 10, 34, 11, 35]],
-
- [[48, 72, 49, 73, 50, 74, 51, 75],
- [52, 76, 53, 77, 54, 78, 55, 79],
- [56, 80, 57, 81, 58, 82, 59, 83]],
-
- [[12, 36, 13, 37, 14, 38, 15, 39],
- [16, 40, 17, 41, 18, 42, 19, 43],
- [20, 44, 21, 45, 22, 46, 23, 47]],
-
- [[60, 84, 61, 85, 62, 86, 63, 87],
- [64, 88, 65, 89, 66, 90, 67, 91],
- [68, 92, 69, 93, 70, 94, 71, 95]]]]]
- )
-
-def test_datasets():
- wikitext2_train = contrib.data.text.WikiText2(root='data/wikitext-2', segment='train')
- wikitext2_val = contrib.data.text.WikiText2(root='data/wikitext-2', segment='validation',
- vocab=wikitext2_train.vocabulary)
- wikitext2_test = contrib.data.text.WikiText2(root='data/wikitext-2', segment='test')
- assert len(wikitext2_train) == 59305, len(wikitext2_train)
- assert len(wikitext2_train.vocabulary) == 33278, len(wikitext2_train.vocabulary)
- assert len(wikitext2_train.frequencies) == 33277, len(wikitext2_train.frequencies)
- assert len(wikitext2_val) == 6181, len(wikitext2_val)
- assert len(wikitext2_val.vocabulary) == 33278, len(wikitext2_val.vocabulary)
- assert len(wikitext2_val.frequencies) == 13776, len(wikitext2_val.frequencies)
- assert len(wikitext2_test) == 6974, len(wikitext2_test)
- assert len(wikitext2_test.vocabulary) == 14143, len(wikitext2_test.vocabulary)
- assert len(wikitext2_test.frequencies) == 14142, len(wikitext2_test.frequencies)
- assert wikitext2_test.frequencies['English'] == 32
-
-
-def test_sampler():
- interval_sampler = contrib.data.IntervalSampler(10, 3)
- assert sorted(list(interval_sampler)) == list(range(10))
- interval_sampler = contrib.data.IntervalSampler(10, 3, rollover=False)
- assert list(interval_sampler) == [0, 3, 6, 9]
-
-
-class RNNLayer(gluon.HybridBlock):
- def __init__(self, cell_type, hidden_size, layout):
- super(RNNLayer, self).__init__()
- self.cell = cell_type(hidden_size)
- self.layout = layout
-
- def hybrid_forward(self, F, inputs, states, valid_length):
- if isinstance(valid_length, list) and len(valid_length) == 0:
- valid_length = None
- return contrib.rnn.rnn_cell.dynamic_unroll(self.cell, inputs, states,
- valid_length=valid_length,
- layout=self.layout)
-
-def check_unroll(cell_type, num_states, layout):
- batch_size = 20
- input_size = 50
- hidden_size = 30
- seq_len = 10
- if layout == 'TNC':
- rnn_data = mx.nd.normal(loc=0, scale=1, shape=(seq_len, batch_size, input_size))
- elif layout == 'NTC':
- rnn_data = mx.nd.normal(loc=0, scale=1, shape=(batch_size, seq_len, input_size))
- else:
- print("Wrong layout")
- return
- valid_length = mx.nd.round(mx.nd.random.uniform(low=1, high=10, shape=(batch_size)))
- state_shape = (batch_size, hidden_size)
- states = [mx.nd.normal(loc=0, scale=1, shape=state_shape) for i in range(num_states)]
-
- cell = cell_type(hidden_size)
- cell.initialize(ctx=default_context())
- if layout == 'TNC':
- cell(rnn_data[0], states)
- else:
- cell(rnn_data[:,0,:], states)
- params1 = cell.collect_params()
- orig_params1 = copy.deepcopy(params1)
-
- trainer = gluon.Trainer(params1, 'sgd', {'learning_rate' : 0.03})
- with mx.autograd.record():
- res1, states1 = cell.unroll(seq_len, rnn_data, states, valid_length=valid_length,
- layout=layout, merge_outputs=True)
- res1.backward()
- trainer.step(batch_size)
-
- configs = [
- lambda layer: None,
- lambda layer: layer.hybridize(),
- lambda layer: layer.hybridize({'inline_limit': 0}),
- lambda layer: layer.hybridize({'static_alloc': True}),
- lambda layer: layer.hybridize({'static_alloc': True, 'static_shape': True}) ]
- # We can't pass None to a hybrid block, but it accepts an empty list.
- # so we use an empty list to represent valid_length if it's None.
- if valid_length is None:
- valid_length = []
- for config in configs:
- layer = RNNLayer(cell_type, hidden_size, layout)
- layer.initialize(ctx=default_context())
- config(layer)
- res2, states2 = layer(rnn_data, states, valid_length)
- params2 = layer.collect_params()
- for key, val in orig_params1.items():
- params2['cell.' + key].set_data(copy.deepcopy(val.data()))
-
- trainer = gluon.Trainer(params2, 'sgd', {'learning_rate' : 0.03})
- with mx.autograd.record():
- res2, states2 = layer(rnn_data, states, valid_length)
- assert_almost_equal(res1, res2, rtol=0.001, atol=0.0001)
- assert len(states1) == len(states2)
- for i in range(len(states1)):
- assert_almost_equal(states1[i], states2[i], rtol=0.001, atol=0.0001)
- res2.backward()
- trainer.step(batch_size)
-
- for key, val in params1.items():
- weight1 = val.data()
- weight2 = params2['cell.' + key].data()
- assert_almost_equal(weight1, weight2, rtol=0.001, atol=0.0001)
-
-
-@with_seed()
-def test_contrib_unroll():
- cell_types = [(gluon.rnn.RNNCell, 1), (gluon.rnn.LSTMCell, 2),
- (gluon.rnn.GRUCell, 1)]
- for cell_type, num_states in cell_types:
- check_unroll(cell_type, num_states, 'TNC')
- check_unroll(cell_type, num_states, 'NTC')
-
-@with_seed()
-def test_ModulatedDeformableConvolution():
- """test of the deformable convolution layer with possible combinations of arguments,
- currently this layer only supports gpu
- """
- from mxnet.gluon.contrib.cnn import DeformableConvolution
- net = nn.HybridSequential()
- net.add(
- DeformableConvolution(10, kernel_size=(3, 3), strides=1, padding=0),
- DeformableConvolution(10, kernel_size=(1, 1), strides=1, padding=0),
- DeformableConvolution(10, kernel_size=(5, 5), strides=1, padding=0),
- DeformableConvolution(10, kernel_size=(3, 5), strides=1, padding=0),
- DeformableConvolution(10, kernel_size=(5, 1), strides=1, padding=0, num_deformable_group=2),
- DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, activation='relu',
- offset_use_bias=False, use_bias=False),
- DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, activation='relu',
- offset_use_bias=False),
- DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, activation='relu',
- use_bias=False),
- DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, offset_use_bias=False, use_bias=False),
- DeformableConvolution(10, kernel_size=(3, 2), strides=1, padding=0, offset_use_bias=False),
- DeformableConvolution(12, kernel_size=(3, 2), strides=1, padding=0, use_bias=False),
- DeformableConvolution(12, kernel_size=(3, 2), strides=1, padding=0, use_bias=False, num_deformable_group=4),
- )
-
- ctx = mx.cpu()
-
- net.initialize(force_reinit=True, ctx=ctx)
- net.hybridize()
-
- x = mx.nd.random.uniform(shape=(8, 5, 30, 31), ctx=ctx)
- with mx.autograd.record():
- y = net(x)
-
diff --git a/tests/python/unittest/test_gluon_data.py b/tests/python/unittest/test_gluon_data.py
index abdf558..53cbf8b 100644
--- a/tests/python/unittest/test_gluon_data.py
+++ b/tests/python/unittest/test_gluon_data.py
@@ -612,3 +612,9 @@ def test_batchify_group():
[[ 4., 5., 6., -1.], [-1., -1., -1., -1.]],
[[ 9., 10., -1., -1.], [-1., -1., -1., -1.]]])
assert mx.test_utils.almost_equal(d[1].asnumpy(), expected)
+
+def test_sampler():
+ interval_sampler = mx.gluon.data.IntervalSampler(10, 3)
+ assert sorted(list(interval_sampler)) == list(range(10))
+ interval_sampler = mx.gluon.data.IntervalSampler(10, 3, rollover=False)
+ assert list(interval_sampler) == [0, 3, 6, 9]
diff --git a/tests/python/unittest/test_gluon_rnn.py b/tests/python/unittest/test_gluon_rnn.py
index fbb7070..d608296 100644
--- a/tests/python/unittest/test_gluon_rnn.py
+++ b/tests/python/unittest/test_gluon_rnn.py
@@ -23,7 +23,7 @@ from itertools import product
from functools import partial
from numpy.testing import assert_allclose
import pytest
-from mxnet.test_utils import almost_equal, assert_almost_equal
+from mxnet.test_utils import almost_equal, assert_almost_equal, default_context
from common import assert_raises_cudnn_not_satisfied, with_seed, retry
@@ -93,8 +93,8 @@ def test_lstmp():
stack_layer = mx.gluon.rnn.HybridSequentialRNNCell()
for i in range(num_layers):
- stack_layer.add(gluon.contrib.rnn.LSTMPCell(hidden_size,
- projection_size=projection_size))
+ stack_layer.add(gluon.rnn.LSTMPCell(hidden_size,
+ projection_size=projection_size))
fused_layer.initialize()
stack_layer.initialize()
@@ -125,10 +125,10 @@ def test_lstmp():
stack_layer = mx.gluon.rnn.HybridSequentialRNNCell()
for i in range(num_layers):
stack_layer.add(
- gluon.rnn.BidirectionalCell(gluon.contrib.rnn.LSTMPCell(hidden_size,
- projection_size=projection_size),
- gluon.contrib.rnn.LSTMPCell(hidden_size,
- projection_size=projection_size)))
+ gluon.rnn.BidirectionalCell(gluon.rnn.LSTMPCell(hidden_size,
+ projection_size=projection_size),
+ gluon.rnn.LSTMPCell(hidden_size,
+ projection_size=projection_size)))
fused_layer.initialize()
stack_layer.initialize()
@@ -817,7 +817,7 @@ def test_rnn_unroll_variant_length():
cell_list.append(gluon.rnn.BidirectionalCell(
l_cell=base_cell_class(20),
r_cell=base_cell_class(20)))
- cell_list.append(gluon.contrib.rnn.VariationalDropoutCell(base_cell=base_cell_class(20)))
+ cell_list.append(gluon.rnn.VariationalDropoutCell(base_cell=base_cell_class(20)))
stack_res_rnn_cell = gluon.rnn.SequentialRNNCell()
stack_res_rnn_cell.add(gluon.rnn.ResidualCell(base_cell=gluon.rnn.RNNCell(20)))
stack_res_rnn_cell.add(gluon.rnn.ResidualCell(base_cell=gluon.rnn.RNNCell(20)))
@@ -912,3 +912,225 @@ def test_bidirectional_unroll_valid_length():
_check_bidirectional_unroll_valid_length(1)
_check_bidirectional_unroll_valid_length(3)
+
+
+def check_rnn_cell(cell, in_shape=(10, 50), out_shape=(10, 100), begin_state=None):
+ inputs = [mx.sym.Variable('rnn_t%d_data'%i) for i in range(3)]
+ outputs, _ = cell.unroll(3, inputs, begin_state=begin_state)
+ outputs = mx.sym.Group(outputs)
+ assert sorted(cell.collect_params().keys()) == ['h2h_bias', 'h2h_weight',
+ 'i2h_bias', 'i2h_weight']
+ assert outputs.list_outputs() == [type(cell).__name__.lower() + name for name in ['_t0_out_output', '_t1_out_output', '_t2_out_output']]
+
+ args, outs, auxs = outputs.infer_shape(rnn_t0_data=in_shape,
+ rnn_t1_data=in_shape,
+ rnn_t2_data=in_shape)
+ assert outs == [out_shape] * 3
+
+
+def check_rnn_forward(layer, inputs):
+ inputs.attach_grad()
+ layer.initialize()
+ with mx.autograd.record():
+ layer.unroll(3, inputs, merge_outputs=True)[0].backward()
+ mx.autograd.backward(layer.unroll(3, inputs, merge_outputs=False)[0])
+ mx.nd.waitall()
+
+
+@with_seed()
+def test_rnn_cells():
+ check_rnn_forward(gluon.rnn.Conv1DLSTMCell((5, 7), 10, (3,), (3,)),
+ mx.nd.ones((8, 3, 5, 7)))
+ check_rnn_forward(gluon.rnn.Conv1DRNNCell((5, 7), 10, (3,), (3,)),
+ mx.nd.ones((8, 3, 5, 7)))
+ check_rnn_forward(gluon.rnn.Conv1DGRUCell((5, 7), 10, (3,), (3,)),
+ mx.nd.ones((8, 3, 5, 7)))
+
+ net = mx.gluon.rnn.SequentialRNNCell()
+ net.add(gluon.rnn.Conv1DLSTMCell((5, 7), 10, (3,), (3,)))
+ net.add(gluon.rnn.Conv1DRNNCell((10, 5), 11, (3,), (3,)))
+ net.add(gluon.rnn.Conv1DGRUCell((11, 3), 12, (3,), (3,)))
+ check_rnn_forward(net, mx.nd.ones((8, 3, 5, 7)))
+
+
+@with_seed()
+def test_convrnn():
+ cell = gluon.rnn.Conv1DRNNCell((10, 50), 100, 3, 3)
+ check_rnn_cell(cell, in_shape=(1, 10, 50), out_shape=(1, 100, 48))
+
+ cell = gluon.rnn.Conv2DRNNCell((10, 20, 50), 100, 3, 3)
+ check_rnn_cell(cell, in_shape=(1, 10, 20, 50), out_shape=(1, 100, 18, 48))
+
+ cell = gluon.rnn.Conv3DRNNCell((10, 20, 30, 50), 100, 3, 3)
+ check_rnn_cell(cell, in_shape=(1, 10, 20, 30, 50), out_shape=(1, 100, 18, 28, 48))
+
+
+@with_seed()
+def test_convlstm():
+ cell = gluon.rnn.Conv1DLSTMCell((10, 50), 100, 3, 3)
+ check_rnn_cell(cell, in_shape=(1, 10, 50), out_shape=(1, 100, 48))
+
+ cell = gluon.rnn.Conv2DLSTMCell((10, 20, 50), 100, 3, 3)
+ check_rnn_cell(cell, in_shape=(1, 10, 20, 50), out_shape=(1, 100, 18, 48))
+
+ cell = gluon.rnn.Conv3DLSTMCell((10, 20, 30, 50), 100, 3, 3)
+ check_rnn_cell(cell, in_shape=(1, 10, 20, 30, 50), out_shape=(1, 100, 18, 28, 48))
+
+
+@with_seed()
+def test_convgru():
+ cell = gluon.rnn.Conv1DGRUCell((10, 50), 100, 3, 3)
+ check_rnn_cell(cell, in_shape=(1, 10, 50), out_shape=(1, 100, 48))
+
+ cell = gluon.rnn.Conv2DGRUCell((10, 20, 50), 100, 3, 3)
+ check_rnn_cell(cell, in_shape=(1, 10, 20, 50), out_shape=(1, 100, 18, 48))
+
+ cell = gluon.rnn.Conv3DGRUCell((10, 20, 30, 50), 100, 3, 3)
+ check_rnn_cell(cell, in_shape=(1, 10, 20, 30, 50), out_shape=(1, 100, 18, 28, 48))
+
+
+@with_seed()
+def test_conv_fill_shape():
+ cell = gluon.rnn.Conv1DLSTMCell((0, 7), 10, (3,), (3,))
+ cell.hybridize()
+ check_rnn_forward(cell, mx.nd.ones((8, 3, 5, 7)))
+ assert cell.i2h_weight.shape[1] == 5, cell.i2h_weight.shape[1]
+
+
+@with_seed()
+def test_lstmp():
+ nhid = 100
+ nproj = 64
+ cell = gluon.rnn.LSTMPCell(nhid, nproj)
+ inputs = [mx.sym.Variable('rnn_t%d_data'%i) for i in range(3)]
+ outputs, _ = cell.unroll(3, inputs)
+ outputs = mx.sym.Group(outputs)
+ expected_params = ['h2h_bias', 'h2h_weight', 'h2r_weight', 'i2h_bias', 'i2h_weight']
+ expected_outputs = [type(cell).__name__.lower() + name for name in ['_t0_out_output', '_t1_out_output', '_t2_out_output']]
+ assert sorted(cell.collect_params().keys()) == expected_params
+ assert outputs.list_outputs() == expected_outputs, outputs.list_outputs()
+
+ args, outs, auxs = outputs.infer_shape(rnn_t0_data=(10,50), rnn_t1_data=(10,50), rnn_t2_data=(10,50))
+ assert outs == [(10, nproj), (10, nproj), (10, nproj)]
+
+
+@with_seed()
+def test_vardrop():
+ def check_vardrop(drop_inputs, drop_states, drop_outputs):
+ cell = gluon.rnn.VariationalDropoutCell(mx.gluon.rnn.RNNCell(100),
+ drop_outputs=drop_outputs,
+ drop_states=drop_states,
+ drop_inputs=drop_inputs)
+ cell.initialize(init='xavier')
+ input_data = mx.nd.random_uniform(shape=(10, 3, 50), ctx=mx.context.current_context())
+ with mx.autograd.record():
+ outputs1, _ = cell.unroll(3, input_data, merge_outputs=True)
+ mx.nd.waitall()
+ outputs2, _ = cell.unroll(3, input_data, merge_outputs=True)
+ assert not almost_equal(outputs1.asnumpy(), outputs2.asnumpy())
+
+ inputs = [mx.sym.Variable('rnn_t%d_data'%i) for i in range(3)]
+ outputs, _ = cell.unroll(3, inputs, merge_outputs=False)
+ outputs = mx.sym.Group(outputs)
+
+ args, outs, auxs = outputs.infer_shape(rnn_t0_data=(10,50), rnn_t1_data=(10,50), rnn_t2_data=(10,50))
+ assert outs == [(10, 100), (10, 100), (10, 100)]
+
+ cell.reset()
+ cell.hybridize()
+ with mx.autograd.record():
+ outputs3, _ = cell.unroll(3, input_data, merge_outputs=True)
+ mx.nd.waitall()
+ outputs4, _ = cell.unroll(3, input_data, merge_outputs=True)
+ assert not almost_equal(outputs3.asnumpy(), outputs4.asnumpy())
+ assert not almost_equal(outputs1.asnumpy(), outputs3.asnumpy())
+
+ check_vardrop(0.5, 0.5, 0.5)
+ check_vardrop(0.5, 0, 0.5)
+
+
+@with_seed()
+@pytest.mark.parametrize('cell_type,num_states', [
+ (gluon.rnn.RNNCell, 1),
+ (gluon.rnn.LSTMCell, 2),
+ (gluon.rnn.GRUCell, 1)
+])
+@pytest.mark.parametrize('layout', ['NTC', 'TNC'])
+def test_unroll(cell_type, num_states, layout):
+ class RNNLayer(gluon.HybridBlock):
+ def __init__(self, cell_type, hidden_size, layout):
+ super(RNNLayer, self).__init__()
+ self.cell = cell_type(hidden_size)
+ self.layout = layout
+
+ def hybrid_forward(self, F, inputs, states, valid_length):
+ if isinstance(valid_length, list) and len(valid_length) == 0:
+ valid_length = None
+ return gluon.rnn.rnn_cell.dynamic_unroll(self.cell, inputs, states,
+ valid_length=valid_length,
+ layout=self.layout)
+ batch_size = 20
+ input_size = 50
+ hidden_size = 30
+ seq_len = 10
+ ctx = default_context()
+ if layout == 'TNC':
+ rnn_data = mx.nd.normal(loc=0, scale=1, shape=(seq_len, batch_size, input_size), ctx=ctx)
+ elif layout == 'NTC':
+ rnn_data = mx.nd.normal(loc=0, scale=1, shape=(batch_size, seq_len, input_size), ctx=ctx)
+ else:
+ print("Wrong layout")
+ return
+ valid_length = mx.nd.round(mx.nd.random.uniform(low=1, high=10, shape=(batch_size), ctx=ctx))
+ state_shape = (batch_size, hidden_size)
+ states = [mx.nd.normal(loc=0, scale=1, shape=state_shape, ctx=ctx) for i in range(num_states)]
+
+ cell = cell_type(hidden_size)
+ cell.initialize(ctx=default_context())
+ if layout == 'TNC':
+ cell(rnn_data[0], states)
+ else:
+ cell(rnn_data[:,0,:], states)
+ params1 = cell.collect_params()
+ orig_params1 = copy.deepcopy(params1)
+
+ trainer = gluon.Trainer(params1, 'sgd', {'learning_rate' : 0.03})
+ with mx.autograd.record():
+ res1, states1 = cell.unroll(seq_len, rnn_data, states, valid_length=valid_length,
+ layout=layout, merge_outputs=True)
+ res1.backward()
+ trainer.step(batch_size)
+
+ configs = [
+ lambda layer: None,
+ lambda layer: layer.hybridize(),
+ lambda layer: layer.hybridize({'inline_limit': 0}),
+ lambda layer: layer.hybridize({'static_alloc': True}),
+ lambda layer: layer.hybridize({'static_alloc': True, 'static_shape': True}) ]
+ # We can't pass None to a hybrid block, but it accepts an empty list.
+ # so we use an empty list to represent valid_length if it's None.
+ if valid_length is None:
+ valid_length = []
+ for config in configs:
+ layer = RNNLayer(cell_type, hidden_size, layout)
+ layer.initialize(ctx=default_context())
+ config(layer)
+ res2, states2 = layer(rnn_data, states, valid_length)
+ params2 = layer.collect_params()
+ for key, val in orig_params1.items():
+ params2['cell.' + key].set_data(copy.deepcopy(val.data()))
+
+ trainer = gluon.Trainer(params2, 'sgd', {'learning_rate' : 0.03})
+ with mx.autograd.record():
+ res2, states2 = layer(rnn_data, states, valid_length)
+ assert_almost_equal(res1, res2, rtol=0.001, atol=0.0001)
+ assert len(states1) == len(states2)
+ for i in range(len(states1)):
+ assert_almost_equal(states1[i], states2[i], rtol=0.001, atol=0.0001)
+ res2.backward()
+ trainer.step(batch_size)
+
+ for key, val in params1.items():
+ weight1 = val.data()
+ weight2 = params2['cell.' + key].data()
+ assert_almost_equal(weight1, weight2, rtol=0.001, atol=0.0001)
diff --git a/tests/python/unittest/test_numpy_gluon.py b/tests/python/unittest/test_numpy_gluon.py
index a3adad6..c0147ce 100644
--- a/tests/python/unittest/test_numpy_gluon.py
+++ b/tests/python/unittest/test_numpy_gluon.py
@@ -24,10 +24,11 @@ from uuid import uuid4
import numpy as _np
import mxnet as mx
from mxnet import gluon, autograd, np
-from mxnet.test_utils import use_np, assert_almost_equal, check_gluon_hybridize_consistency
+from mxnet.test_utils import use_np, assert_almost_equal, check_gluon_hybridize_consistency, assert_allclose
from mxnet.gluon import nn
from common import with_seed
import random
+import pytest
@with_seed()
@@ -475,3 +476,117 @@ def test_activations_swish():
act_layer = nn.Swish()
out = act_layer(mx.np.random.uniform(size=(10,)))
out.asnumpy()
+
+@use_np
+def test_concatenate():
+ model = nn.HybridConcatenate(axis=1)
+ model.add(nn.Dense(128, activation='tanh', in_units=10))
+ model.add(nn.Dense(64, activation='tanh', in_units=10))
+ model.add(nn.Dense(32, in_units=10))
+ model2 = nn.Concatenate(axis=1)
+ model2.add(nn.Dense(128, activation='tanh', in_units=10))
+ model2.add(nn.Dense(64, activation='tanh', in_units=10))
+ model2.add(nn.Dense(32, in_units=10))
+
+ # ndarray
+ model.initialize(mx.init.Xavier(magnitude=2.24))
+ model2.initialize(mx.init.Xavier(magnitude=2.24))
+ x = model(mx.np.zeros((32, 10)))
+ x2 = model2(mx.np.zeros((32, 10)))
+ assert x.shape == (32, 224)
+ assert x2.shape == (32, 224)
+ x.wait_to_read()
+ x2.wait_to_read()
+
+@use_np
+@with_seed()
+def test_identity():
+ model = nn.Identity()
+ x = mx.np.random.uniform(size=(128, 33, 64))
+ assert_almost_equal(model(x), x)
+
+@use_np
+def test_pixelshuffle1d():
+ nchan = 2
+ up_x = 2
+ nx = 3
+ shape_before = (1, nchan * up_x, nx)
+ shape_after = (1, nchan, nx * up_x)
+ layer = nn.PixelShuffle1D(up_x)
+ x = mx.np.reshape(mx.np.arange(_np.prod(shape_before)), shape_before)
+ y = layer(x)
+ assert y.shape == shape_after
+ assert_allclose(
+ y,
+ [[[0, 3, 1, 4, 2, 5],
+ [6, 9, 7, 10, 8, 11]]]
+ )
+
+@use_np
+def test_pixelshuffle2d():
+ nchan = 2
+ up_x = 2
+ up_y = 3
+ nx = 2
+ ny = 3
+ shape_before = (1, nchan * up_x * up_y, nx, ny)
+ shape_after = (1, nchan, nx * up_x, ny * up_y)
+ layer = nn.PixelShuffle2D((up_x, up_y))
+ x = mx.np.reshape(mx.np.arange(_np.prod(shape_before)), shape_before)
+ y = layer(x)
+ assert y.shape == shape_after
+ # - Channels are reshaped to form 2x3 blocks
+ # - Within each block, the increment is `nx * ny` when increasing the column
+ # index by 1
+ # - Increasing the block index adds an offset of 1
+ # - Increasing the channel index adds an offset of `nx * up_x * ny * up_y`
+ assert_allclose(
+ y,
+ [[[[ 0, 6, 12, 1, 7, 13, 2, 8, 14],
+ [18, 24, 30, 19, 25, 31, 20, 26, 32],
+ [ 3, 9, 15, 4, 10, 16, 5, 11, 17],
+ [21, 27, 33, 22, 28, 34, 23, 29, 35]],
+
+ [[36, 42, 48, 37, 43, 49, 38, 44, 50],
+ [54, 60, 66, 55, 61, 67, 56, 62, 68],
+ [39, 45, 51, 40, 46, 52, 41, 47, 53],
+ [57, 63, 69, 58, 64, 70, 59, 65, 71]]]]
+ )
+
+@use_np
+def test_pixelshuffle3d():
+ nchan = 1
+ up_x = 2
+ up_y = 1
+ up_z = 2
+ nx = 2
+ ny = 3
+ nz = 4
+ shape_before = (1, nchan * up_x * up_y * up_z, nx, ny, nz)
+ shape_after = (1, nchan, nx * up_x, ny * up_y, nz * up_z)
+ layer = nn.PixelShuffle3D((up_x, up_y, up_z))
+ x = mx.np.arange(_np.prod(shape_before)).reshape(shape_before)
+ y = layer(x)
+ assert y.shape == shape_after
+ # - Channels are reshaped to form 2x1x2 blocks
+ # - Within each block, the increment is `nx * ny * nz` when increasing the
+ # column index by 1, e.g. the block [[[ 0, 24]], [[48, 72]]]
+ # - Increasing the block index adds an offset of 1
+ assert_allclose(
+ y,
+ [[[[[ 0, 24, 1, 25, 2, 26, 3, 27],
+ [ 4, 28, 5, 29, 6, 30, 7, 31],
+ [ 8, 32, 9, 33, 10, 34, 11, 35]],
+
+ [[48, 72, 49, 73, 50, 74, 51, 75],
+ [52, 76, 53, 77, 54, 78, 55, 79],
+ [56, 80, 57, 81, 58, 82, 59, 83]],
+
+ [[12, 36, 13, 37, 14, 38, 15, 39],
+ [16, 40, 17, 41, 18, 42, 19, 43],
+ [20, 44, 21, 45, 22, 46, 23, 47]],
+
+ [[60, 84, 61, 85, 62, 86, 63, 87],
+ [64, 88, 65, 89, 66, 90, 67, 91],
+ [68, 92, 69, 93, 70, 94, 71, 95]]]]]
+ )
diff --git a/tests/python/unittest/test_numpy_op.py b/tests/python/unittest/test_numpy_op.py
index 16e25b2..0224abb 100644
--- a/tests/python/unittest/test_numpy_op.py
+++ b/tests/python/unittest/test_numpy_op.py
@@ -10326,3 +10326,42 @@ def test_np_broadcast_ops_on_misaligned_input_oneside(dtype, lead_dim, both_ways
expected = c.asnumpy() + d.asnumpy()
mx.nd.waitall()
assert_almost_equal(f, expected)
+
+@with_seed()
+@use_np
+@pytest.mark.parametrize('num_batch', [1, 2])
+@pytest.mark.parametrize('num_channel_data', [4, 8])
+@pytest.mark.parametrize('num_deformable_group', [1, 2])
+@pytest.mark.parametrize('input_height', [5, 6])
+@pytest.mark.parametrize('input_width', [5, 6])
+@pytest.mark.parametrize('dilate', [(1, 1), (2, 2)])
+@pytest.mark.parametrize('grad_nodes', [['im_data'], ['offset_data'], ['weight']])
+def test_modulated_deformable_convolution(num_batch, num_channel_data, num_deformable_group,
+ input_height, input_width, dilate, grad_nodes):
+ output_height = input_height
+ output_width = input_width
+ im_data = np.random.rand(num_batch, num_channel_data, input_height, input_width)
+ offset_data = \
+ np.random.rand(num_batch, num_deformable_group * 3 * 3 * 2, output_height, output_width)\
+ * 0.8 + 0.1
+ mask_data = np.random.rand(num_batch, num_deformable_group * 3 * 3, output_height, output_width)
+ mask_data = 0.5 * (1 + np.tanh(0.5 * mask_data)) # sigmoid
+ weight = np.random.normal(0, 0.001, (num_channel_data, num_channel_data, 3, 3))
+ bias = np.zeros(num_channel_data)
+
+ im_data_var = mx.symbol.Variable(name="im_data").as_np_ndarray()
+ offset_data_var = mx.symbol.Variable(name="offset_data").as_np_ndarray()
+ mask_data_var = mx.symbol.Variable(name="mask_data").as_np_ndarray()
+ weight_var = mx.symbol.Variable(name="weight").as_np_ndarray()
+ bias_var = mx.symbol.Variable(name="bias").as_np_ndarray()
+ op = mx.sym.npx.modulated_deformable_convolution(name='test_op', data=im_data_var,
+ offset=offset_data_var, mask=mask_data_var,
+ weight=weight_var, bias=bias_var,
+ num_filter=num_channel_data, pad=dilate,
+ kernel=(3, 3), stride=(1, 1), dilate=dilate,
+ num_deformable_group=num_deformable_group)
+ if grad_nodes[0] == 'offset_data':
+ # wider tolerance needed for coordinate differential
+ rtol, atol = 1.0, 1e-2
+ else:
+ rtol, atol = 0.05, 1e-3
diff --git a/tests/python/unittest/test_operator.py b/tests/python/unittest/test_operator.py
index bdb7c3f..110204b 100644
--- a/tests/python/unittest/test_operator.py
+++ b/tests/python/unittest/test_operator.py
@@ -5806,16 +5806,16 @@ def test_deformable_convolution():
weight = np.random.normal(0, 0.001, (num_channel_data, num_channel_data, 3, 3))
bias = np.zeros(num_channel_data)
- im_data_var = mx.symbol.Variable(name="im_data")
- offset_data_var = mx.symbol.Variable(name="offset_data")
- weight_var = mx.symbol.Variable(name="weight")
- bias_var = mx.symbol.Variable(name="bias")
- op = mx.sym.contrib.DeformableConvolution(name='test_op', data=im_data_var,
- offset=offset_data_var,
- weight=weight_var, bias=bias_var,
- num_filter=num_channel_data, pad=dilate,
- kernel=(3, 3), stride=(1, 1), dilate=dilate,
- num_deformable_group=num_deformable_group)
+ im_data_var = mx.symbol.Variable(name="im_data").as_np_ndarray()
+ offset_data_var = mx.symbol.Variable(name="offset_data").as_np_ndarray()
+ weight_var = mx.symbol.Variable(name="weight").as_np_ndarray()
+ bias_var = mx.symbol.Variable(name="bias").as_np_ndarray()
+ op = mx.sym.npx.deformable_convolution(name='test_op', data=im_data_var,
+ offset=offset_data_var,
+ weight=weight_var, bias=bias_var,
+ num_filter=num_channel_data, pad=dilate,
+ kernel=(3, 3), stride=(1, 1), dilate=dilate,
+ num_deformable_group=num_deformable_group)
if grad_nodes[0] == 'offset_data':
# wider tolerance needed for coordinate differential
rtol, atol = 1.0, 1e-2
diff --git a/tests/python/unittest/test_random.py b/tests/python/unittest/test_random.py
index d45ae0f..5647b1c 100644
--- a/tests/python/unittest/test_random.py
+++ b/tests/python/unittest/test_random.py
@@ -572,7 +572,7 @@ def test_parallel_random_seed_setting_for_context():
def test_sample_multinomial(dtype, x):
x = mx.nd.array(x) / 10.0
dx = mx.nd.ones_like(x)
- mx.contrib.autograd.mark_variables([x], [dx])
+ mx.autograd.mark_variables([x], [dx])
# Adding rtol and increasing samples needed to pass with seed 2951820647
samples = 10000
with mx.autograd.record():