You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

instancenorm.cpp 2.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // Tencent is pleased to support the open source community by making ncnn available.
  2. //
  3. // Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
  4. //
  5. // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
  6. // in compliance with the License. You may obtain a copy of the License at
  7. //
  8. // https://opensource.org/licenses/BSD-3-Clause
  9. //
  10. // Unless required by applicable law or agreed to in writing, software distributed
  11. // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  12. // CONDITIONS OF ANY KIND, either express or implied. See the License for the
  13. // specific language governing permissions and limitations under the License.
  14. #include "instancenorm.h"
  15. #include <math.h>
  16. namespace ncnn {
  17. DEFINE_LAYER_CREATOR(InstanceNorm)
  18. InstanceNorm::InstanceNorm()
  19. {
  20. one_blob_only = true;
  21. support_inplace = true;
  22. }
  23. int InstanceNorm::load_param(const ParamDict& pd)
  24. {
  25. channels = pd.get(0, 0);
  26. eps = pd.get(1, 0.001f);
  27. return 0;
  28. }
  29. int InstanceNorm::load_model(const ModelBin& mb)
  30. {
  31. gamma_data = mb.load(channels, 1);
  32. if (gamma_data.empty())
  33. return -100;
  34. beta_data = mb.load(channels, 1);
  35. if (beta_data.empty())
  36. return -100;
  37. return 0;
  38. }
  39. int InstanceNorm::forward_inplace(Mat& bottom_top_blob, const Option& opt) const
  40. {
  41. // x = (x - mean) / (sqrt(var) + eps) * gamma + beta
  42. int w = bottom_top_blob.w;
  43. int h = bottom_top_blob.h;
  44. int size = w * h;
  45. #pragma omp parallel for num_threads(opt.num_threads)
  46. for (int q=0; q<channels; q++)
  47. {
  48. float* ptr = bottom_top_blob.channel(q);
  49. // mean and var
  50. float sum = 0.f;
  51. float sqsum = 0.f;
  52. for (int i=0; i<size; i++)
  53. {
  54. sum += ptr[i];
  55. //sqsum += ptr[i] * ptr[i];
  56. }
  57. float mean = sum / size;
  58. float tmp = 0.f;
  59. for (int i=0; i<size; i++)
  60. {
  61. tmp = ptr[i] - mean;
  62. sqsum += tmp * tmp;
  63. }
  64. float var = sqsum / size;
  65. // the var maybe minus due to accuracy
  66. //float var = sqsum / size - mean * mean;
  67. float gamma = gamma_data[q];
  68. float beta = beta_data[q];
  69. float a = gamma / (sqrt(var + eps));
  70. float b = - mean * a + beta;
  71. for (int i=0; i<size; i++)
  72. {
  73. ptr[i] = ptr[i] * a + b;
  74. }
  75. }
  76. return 0;
  77. }
  78. } // namespace ncnn