cosmargin.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
  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. import paddle
  15. import math
  16. import paddle.nn as nn
  17. class CosMargin(paddle.nn.Layer):
  18. def __init__(self, embedding_size, class_num, margin=0.35, scale=64.0):
  19. super(CosMargin, self).__init__()
  20. self.scale = scale
  21. self.margin = margin
  22. self.embedding_size = embedding_size
  23. self.class_num = class_num
  24. self.weight = self.create_parameter(
  25. shape=[self.embedding_size, self.class_num],
  26. is_bias=False,
  27. default_initializer=paddle.nn.initializer.XavierNormal())
  28. def forward(self, input, label):
  29. label.stop_gradient = True
  30. input_norm = paddle.sqrt(
  31. paddle.sum(paddle.square(input), axis=1, keepdim=True))
  32. input = paddle.divide(input, input_norm)
  33. weight_norm = paddle.sqrt(
  34. paddle.sum(paddle.square(self.weight), axis=0, keepdim=True))
  35. weight = paddle.divide(self.weight, weight_norm)
  36. cos = paddle.matmul(input, weight)
  37. if not self.training or label is None:
  38. return cos
  39. cos_m = cos - self.margin
  40. one_hot = paddle.nn.functional.one_hot(label, self.class_num)
  41. one_hot = paddle.squeeze(one_hot, axis=[1])
  42. output = paddle.multiply(one_hot, cos_m) + paddle.multiply(
  43. (1.0 - one_hot), cos)
  44. output = output * self.scale
  45. return output