Skip to content

refine amax/amin example #38525

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

Merged
merged 1 commit into from
Dec 28, 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
26 changes: 26 additions & 0 deletions python/paddle/tensor/math.py
Original file line number Diff line number Diff line change
Expand Up @@ -1802,11 +1802,24 @@ def amax(x, axis=None, keepdim=False, name=None):
x = paddle.to_tensor([[0.1, 0.9, 0.9, 0.9],
[0.9, 0.9, 0.6, 0.7]],
dtype='float64', stop_gradient=False)
# There are 5 maximum elements:
# 1) amax evenly distributes gradient between these equal values,
# thus the corresponding gradients are 1/5=0.2;
# 2) while max propagates gradient to all of them,
# thus the corresponding gradient are 1.
result1 = paddle.amax(x)
result1.backward()
print(result1, x.grad)
#[0.9], [[0., 0.2, 0.2, 0.2], [0.2, 0.2, 0., 0.]]

x.clear_grad()
result1_max = paddle.max(x)
result1_max.backward()
print(result1_max, x.grad)
#[0.9], [[0., 1.0, 1.0, 1.0], [1.0, 1.0, 0., 0.]]

###############################

x.clear_grad()
result2 = paddle.amax(x, axis=0)
result2.backward()
Expand Down Expand Up @@ -1901,11 +1914,24 @@ def amin(x, axis=None, keepdim=False, name=None):
x = paddle.to_tensor([[0.2, 0.1, 0.1, 0.1],
[0.1, 0.1, 0.6, 0.7]],
dtype='float64', stop_gradient=False)
# There are 5 minimum elements:
# 1) amin evenly distributes gradient between these equal values,
# thus the corresponding gradients are 1/5=0.2;
# 2) while min propagates gradient to all of them,
# thus the corresponding gradient are 1.
result1 = paddle.amin(x)
result1.backward()
print(result1, x.grad)
#[0.1], [[0., 0.2, 0.2, 0.2], [0.2, 0.2, 0., 0.]]

x.clear_grad()
result1_min = paddle.min(x)
result1_min.backward()
print(result1_min, x.grad)
#[0.1], [[0., 1.0, 1.0, 1.0], [1.0, 1.0, 0., 0.]]

###############################

x.clear_grad()
result2 = paddle.amin(x, axis=0)
result2.backward()
Expand Down