Skip to content

Commit

Permalink
Fix Bugs (PaddlePaddle#1792)
Browse files Browse the repository at this point in the history
  • Loading branch information
RachelXu7 authored Aug 25, 2023
1 parent 73e1529 commit bb02b10
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 7 deletions.
9 changes: 5 additions & 4 deletions paddleslim/quant/advanced/layerwise_quant_error.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ def __init__(self,
if type(cur_layer) == LayerWiseQuantError:
print(cur_name, cur_layer.losses.mean())
'''
super(LayerWiseQuantError, self).__init__()
self.layer = layer
self.weight = layer.weight
self.weight_bits = weight_bits
Expand All @@ -62,14 +63,13 @@ def __init__(self,
self.act_method = act_quant_method
self.loss_function = loss_function
self.losses = []
self.loss = None

def forward(self, input):
act = input[0] if type(input) == tuple else input
origin_out = paddle.matmul(act, self.weight)
bnt = (1 << (self.weight_bits - 1)) - 1
quant_scale = compute_scales(
self.weight.cast('float32'),
method=self.weight_method).cast(self.weight.dtype)
quant_scale = compute_scales(self.weight, method=self.weight_method)
quant_weight = paddle.clip(
paddle.round(self.weight / quant_scale * bnt), -bnt - 1, bnt)
quant_dequant_weight = quant_weight / bnt * quant_scale
Expand All @@ -80,6 +80,7 @@ def forward(self, input):
paddle.round(act / quant_scale * bnt), -bnt - 1, bnt)
quant_dequant_act = quant_act / bnt * quant_scale
quant_out = paddle.matmul(quant_dequant_act, quant_dequant_weight)
loss = self.loss_function(origin_out, quant_out)
loss = self.loss_function(origin_out, quant_out).cast('float32')
self.losses.append(loss)
self.loss = paddle.to_tensor(self.losses, dtype='float32').mean()
return self.layer(input)
6 changes: 4 additions & 2 deletions paddleslim/quant/advanced/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,10 @@ def compute_scales(x, method='abs_max'):
elif method == 'abs_max_channel_wise':
reduce_axis = tuple([i for i in range(len(x.shape)) if i != 1])
quant_scale = paddle.max(paddle.abs(x), axis=reduce_axis)
quant_scale = paddle.where(quant_scale == np.float32(0.0),
np.float32(1e-8), quant_scale)
quant_scale = paddle.where(quant_scale == paddle.to_tensor(
0, dtype=x.dtype),
paddle.to_tensor(1e-8, dtype=x.dtype),
quant_scale)
return quant_scale


Expand Down
2 changes: 1 addition & 1 deletion paddleslim/quant/advanced/utils_layers.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def __init__(self, layer):
super(ShiftSmoothHelpLayer, self).__init__()
self.weight = layer.weight
shift_shape = self.weight.shape[0]
if hasattr(layer, "bias") or layer.bias is None:
if not hasattr(layer, "bias") or layer.bias is None:
self.bias = paddle.create_parameter(
shape=[self.weight.shape[1]],
dtype=self.weight.dtype,
Expand Down

0 comments on commit bb02b10

Please sign in to comment.