Skip to content

Bugfix for crnn when amp_level is O0 #688

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 1 commit into from
Apr 7, 2024
Merged
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
17 changes: 15 additions & 2 deletions mindocr/models/necks/rnn.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

import numpy as np

from mindspore import Tensor, nn, ops
import mindspore.ops.functional as F
from mindspore import Tensor, nn, ops, version
from mindspore.common import dtype

__all__ = ['RNNEncoder']

Expand Down Expand Up @@ -37,6 +39,11 @@ def __init__(self, in_channels: int, hidden_size: int = 512, batch_size: Option
has_bias=True,
dropout=0.,
bidirectional=True)
self.encoder_cast_to_fp16 = False
if version.__version__ >= "2.3":
# Adapted to MindSpore r2.3, nn.LSTM has bugs when input is FP32.
self.seq_encoder.to_float(dtype.float16)
self.encoder_cast_to_fp16 = True

self.hx = None
if batch_size is not None:
Expand All @@ -49,9 +56,15 @@ def construct(self, features: List[Tensor]) -> Tensor:
x = ops.squeeze(x, axis=2) # [N, C, W]
x = ops.transpose(x, (2, 0, 1)) # [W, N, C]

if self.encoder_cast_to_fp16 and self._amp_level == "O0":
x = F.cast(x, dtype.float16)

if self.hx is None:
x, _ = self.seq_encoder(x)
else:
x, _ = self.seq_encoder(x, self.hx)

return x
if self.encoder_cast_to_fp16 and self._amp_level == "O0":
return F.cast(x, dtype.float32)
else:
return x