rec_multi_loss.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 paddle
  18. from paddle import nn
  19. from .rec_ctc_loss import CTCLoss
  20. from .rec_sar_loss import SARLoss
  21. class MultiLoss(nn.Layer):
  22. def __init__(self, **kwargs):
  23. super().__init__()
  24. self.loss_funcs = {}
  25. self.loss_list = kwargs.pop('loss_config_list')
  26. self.weight_1 = kwargs.get('weight_1', 1.0)
  27. self.weight_2 = kwargs.get('weight_2', 1.0)
  28. self.gtc_loss = kwargs.get('gtc_loss', 'sar')
  29. for loss_info in self.loss_list:
  30. for name, param in loss_info.items():
  31. if param is not None:
  32. kwargs.update(param)
  33. loss = eval(name)(**kwargs)
  34. self.loss_funcs[name] = loss
  35. def forward(self, predicts, batch):
  36. self.total_loss = {}
  37. total_loss = 0.0
  38. # batch [image, label_ctc, label_sar, length, valid_ratio]
  39. for name, loss_func in self.loss_funcs.items():
  40. if name == 'CTCLoss':
  41. loss = loss_func(predicts['ctc'],
  42. batch[:2] + batch[3:])['loss'] * self.weight_1
  43. elif name == 'SARLoss':
  44. loss = loss_func(predicts['sar'],
  45. batch[:1] + batch[2:])['loss'] * self.weight_2
  46. else:
  47. raise NotImplementedError(
  48. '{} is not supported in MultiLoss yet'.format(name))
  49. self.total_loss[name] = loss
  50. total_loss += loss
  51. self.total_loss['loss'] = total_loss
  52. return self.total_loss