Skip to content

fix the logging in construct part and clean content expression #437

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 0 additions & 5 deletions mindocr/models/necks/rnn.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,7 @@
import mindspore as ms
from mindspore import Tensor, nn, ops

from mindocr.utils.logger import Logger

__all__ = ['RNNEncoder']
_logger = Logger("mindocr")


# TODO: check mindspore nn LSTM diff in performance and precision from paddle/pytorch
Expand Down Expand Up @@ -53,14 +50,12 @@ def construct(self, features):
Tensor: Encoded features . Shape :math:`(W, N, 2*C)` where
"""
x = features[0]
assert x.shape[2] == 1, f'Feature height must be 1, but got {x.shape[2]} from x.shape {x.shape}'
x = ops.squeeze(x, axis=2) # [N, C, W]
x = ops.transpose(x, (2, 0, 1)) # [W, N, C]

if self.hx is None:
x, hx_n = self.seq_encoder(x)
else:
_logger.info('using self.hx')
x, hx_n = self.seq_encoder(x, self.hx) # the results are the same

return x
Expand Down
66 changes: 2 additions & 64 deletions mindocr/models/utils/rnn_cells.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
"""
import mindspore.ops as P
from mindspore.nn.layer.rnn_cells import RNNCellBase
from mindspore.ops.primitive import constexpr

__all__ = ["GRUCell"]

Expand All @@ -26,75 +25,14 @@ def _gru_cell(inputs, hidden, w_ih, w_hh, b_ih, b_hh):
return hy


@constexpr
def _check_batch_size_equal(batch_size_x, batch_size_hx, cls_name):
if batch_size_x != batch_size_hx:
raise ValueError(f"For '{cls_name}' batch size of x and hx must be equal, but got {batch_size_x} of x "
f"and {batch_size_hx} of hx.")


class GRUCell(RNNCellBase):
r"""
A GRU(Gated Recurrent Unit) cell.

.. math::

\begin{array}{ll}
r = \sigma(W_{ir} x + b_{ir} + W_{hr} h + b_{hr}) \\
z = \sigma(W_{iz} x + b_{iz} + W_{hz} h + b_{hz}) \\
n = \tanh(W_{in} x + b_{in} + r * (W_{hn} h + b_{hn})) \\
h' = (1 - z) * n + z * h
\end{array}

Here :math:`\sigma` is the sigmoid function, and :math:`*` is the Hadamard product. :math:`W, b`
are learnable weights between the output and the input in the formula. For instance,
:math:`W_{ir}, b_{ir}` are the weight and bias used to transform from input :math:`x` to :math:`r`.
Details can be found in paper
`Learning Phrase Representations using RNN Encoder-Decoder for Statistical Machine Translation
<https://aclanthology.org/D14-1179.pdf>`_.

The LSTMCell can be simplified in NN layer, the following formula:

.. math::
h^{'},c^{'} = LSTMCell(x, (h_0, c_0))

Args:
input_size (int): Number of features of input.
hidden_size (int): Number of features of hidden layer.
has_bias (bool): Whether the cell has bias `b_in` and `b_hn`. Default: True.

Inputs:
- **x** (Tensor) - Tensor of shape (batch_size, `input_size`).
- **hx** (Tensor) - Tensor of data type mindspore.float32 and shape (batch_size, `hidden_size`).
Data type of `hx` must be the same as `x`.

Outputs:
- **hx'** (Tensor) - Tensor of shape (batch_size, `hidden_size`).

Raises:
TypeError: If `input_size`, `hidden_size` is not an int.
TypeError: If `has_bias` is not a bool.

Supported Platforms:
``Ascend`` ``GPU`` ``CPU``

Examples:
>>> net = nn.GRUCell(10, 16)
>>> x = Tensor(np.ones([5, 3, 10]).astype(np.float32))
>>> hx = Tensor(np.ones([3, 16]).astype(np.float32))
>>> output = []
>>> for i in range(5):
... hx = net(x[i], hx)
... output.append(hx)
>>> print(output[0].shape)
(3, 16)
"""A Modified version of RU(Gated Recurrent Unit) cell, based on mindspore.nn.layer.rnn_cells.GRUCell
It adds a type cast protection of all initial variable
"""
def __init__(self, input_size: int, hidden_size: int, has_bias: bool = True):
super().__init__(input_size, hidden_size, has_bias, num_chunks=3)

def construct(self, x, hx):
_check_batch_size_equal(x.shape[0], hx.shape[0], self.cls_name)

# FIX: make sure the weight and bias dtype is same as the data type from x
# prevent the input type inconsistent error from P.MatMul operator
weight_ih = P.cast(self.weight_ih, x.dtype)
Expand Down