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 F.clip_grad_by_norm in the case of small norm #572

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
6 changes: 3 additions & 3 deletions python/test/function/test_clip_grad_by_norm.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ def ref_clip_grad_by_norm(x, clip_norm, axes):

def ref_grad_clip_by_norm(x, dy, clip_norm, axes):
dx = np.copy(dy)
dx = clip_norm * dy / \
np.broadcast_to(
np.sqrt(np.sum(dy**2, axis=axes, keepdims=True)), dy.shape)
norm = np.sqrt(np.sum(dy**2, axis=axes, keepdims=True))
norm[norm < clip_norm] = clip_norm
dx = clip_norm * dy / np.broadcast_to(norm, dy.shape)
return dx.flatten()


Expand Down
2 changes: 1 addition & 1 deletion src/nbla/function/generic/clip_grad_by_norm.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ template <typename T, bool accum>
void clip_grad_by_norm_backward_cpu(int size, T clip_norm_grad, T *dx,
const T *dy, const T *m) {
for (int s = 0; s < size; ++s) {
T _dx = clip_norm_grad * dy[s] / std::sqrt(m[s]);
T _dx = clip_norm_grad * dy[s] / std::max(std::sqrt(m[s]), clip_norm_grad);
accum ? dx[s] += _dx : dx[s] = _dx;
}
}
Expand Down