Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix BatchNorm for fp16 #36376

Merged
merged 2 commits into from
Oct 13, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions python/paddle/nn/layer/norm.py
Original file line number Diff line number Diff line change
Expand Up @@ -564,32 +564,42 @@ def __init__(self,
self._use_global_stats = use_global_stats

if get_default_dtype() == 'float16':
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这样的话default type是fp16的话,不是还是强制改成了fp32嘛?

Copy link
Contributor Author

@GuoxiaWang GuoxiaWang Oct 13, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

是必须强制改成fp32,因为精度问题,batchnorm 是明确要求参数不能是fp16的,一般fp16输入都是用fp32的来表达参数,输入可以是fp16,区别在于 set_default_dtype,这个会改变全局的 dtype,而这个位置应该只是改变当前层的 dtype,所以应该只改变局部dtype,而不是全局 dtype

set_default_dtype('float32')
self._dtype = 'float32'
else:
self._dtype = get_default_dtype()

param_shape = [num_features]

# create parameter
if weight_attr == False:
self.weight = self.create_parameter(
attr=None, shape=param_shape, default_initializer=Constant(1.0))
attr=None,
shape=param_shape,
dtype=self._dtype,
default_initializer=Constant(1.0))
self.weight.stop_gradient = True
else:
self.weight = self.create_parameter(
attr=self._weight_attr,
shape=param_shape,
dtype=self._dtype,
default_initializer=Constant(1.0))
self.weight.stop_gradient = self._weight_attr != None and self._weight_attr.learning_rate == 0.

if bias_attr == False:
self.bias = self.create_parameter(
attr=None,
shape=param_shape,
dtype=self._dtype,
default_initializer=Constant(0.0),
is_bias=True)
self.bias.stop_gradient = True
else:
self.bias = self.create_parameter(
attr=self._bias_attr, shape=param_shape, is_bias=True)
attr=self._bias_attr,
shape=param_shape,
dtype=self._dtype,
is_bias=True)
self.bias.stop_gradient = self._bias_attr != None and self._bias_attr.learning_rate == 0.

moving_mean_name = None
Expand All @@ -600,6 +610,7 @@ def __init__(self,
moving_variance_name = name + "_variance"

self._mean = self.create_parameter(
dtype=self._dtype,
attr=ParamAttr(
name=moving_mean_name,
initializer=Constant(0.0),
Expand All @@ -609,6 +620,7 @@ def __init__(self,
self._mean.stop_gradient = True

self._variance = self.create_parameter(
dtype=self._dtype,
attr=ParamAttr(
name=moving_variance_name,
initializer=Constant(1.0),
Expand Down