rec_multi_head.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. import math
  18. import paddle
  19. from paddle import ParamAttr
  20. import paddle.nn as nn
  21. import paddle.nn.functional as F
  22. from ppocr.modeling.necks.rnn import Im2Seq, EncoderWithRNN, EncoderWithFC, SequenceEncoder, EncoderWithSVTR
  23. from .rec_ctc_head import CTCHead
  24. from .rec_sar_head import SARHead
  25. class MultiHead(nn.Layer):
  26. def __init__(self, in_channels, out_channels_list, **kwargs):
  27. super().__init__()
  28. self.head_list = kwargs.pop('head_list')
  29. self.gtc_head = 'sar'
  30. assert len(self.head_list) >= 2
  31. for idx, head_name in enumerate(self.head_list):
  32. name = list(head_name)[0]
  33. if name == 'SARHead':
  34. # sar head
  35. sar_args = self.head_list[idx][name]
  36. self.sar_head = eval(name)(in_channels=in_channels, \
  37. out_channels=out_channels_list['SARLabelDecode'], **sar_args)
  38. elif name == 'CTCHead':
  39. # ctc neck
  40. self.encoder_reshape = Im2Seq(in_channels)
  41. neck_args = self.head_list[idx][name]['Neck']
  42. encoder_type = neck_args.pop('name')
  43. self.encoder = encoder_type
  44. self.ctc_encoder = SequenceEncoder(in_channels=in_channels, \
  45. encoder_type=encoder_type, **neck_args)
  46. # ctc head
  47. head_args = self.head_list[idx][name]['Head']
  48. self.ctc_head = eval(name)(in_channels=self.ctc_encoder.out_channels, \
  49. out_channels=out_channels_list['CTCLabelDecode'], **head_args)
  50. else:
  51. raise NotImplementedError(
  52. '{} is not supported in MultiHead yet'.format(name))
  53. def forward(self, x, targets=None):
  54. ctc_encoder = self.ctc_encoder(x)
  55. ctc_out = self.ctc_head(ctc_encoder, targets)
  56. head_out = dict()
  57. head_out['ctc'] = ctc_out
  58. head_out['ctc_neck'] = ctc_encoder
  59. # eval mode
  60. if not self.training:
  61. return ctc_out
  62. if self.gtc_head == 'sar':
  63. sar_out = self.sar_head(x, targets[1:])
  64. head_out['sar'] = sar_out
  65. return head_out
  66. else:
  67. return head_out