pact.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. # Copyright (c) 2020 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 paddle.fluid as fluid
  16. import numpy as np
  17. from paddle.fluid.layer_helper import LayerHelper
  18. def pact(x, name=None):
  19. helper = LayerHelper("pact", **locals())
  20. dtype = 'float32'
  21. init_thres = 20
  22. u_param_attr = fluid.ParamAttr(
  23. name=x.name + '_pact',
  24. initializer=fluid.initializer.ConstantInitializer(value=init_thres),
  25. regularizer=fluid.regularizer.L2Decay(0.0001),
  26. learning_rate=1)
  27. u_param = helper.create_parameter(attr=u_param_attr, shape=[1], dtype=dtype)
  28. x = fluid.layers.elementwise_sub(
  29. x, fluid.layers.relu(fluid.layers.elementwise_sub(x, u_param)))
  30. x = fluid.layers.elementwise_add(
  31. x, fluid.layers.relu(fluid.layers.elementwise_sub(-u_param, x)))
  32. return x
  33. def get_optimizer():
  34. return fluid.optimizer.MomentumOptimizer(0.0001, 0.9)