There are two ways to clip a gradient and they're often treated as the same thing. Take the gradient (0.3, 0.4, 12). Its length is 12.01 and nearly all of that is in the last entry. If you clip each value to 1 you get (0.3, 0.4, 1), which points 24.2 degrees away from where you started. If you clip the norm to 1 you get (0.025, 0.033, 0.999), and the angle is zero.
import numpy as np
def clip_value ( g , c ) : return np . clip ( g , - c , c ) def clip_norm ( g , c ) : return g * min ( 1.0 , c / np . linalg . norm ( g ) )
g = np . array ( [ 0.3 , 0.4 , 12.0 ] ) for f in ( clip_value , clip_norm ) : h = f ( g , 1.0 ) cos = h @ g / np . linalg . norm ( h ) / np . linalg . norm ( g ) print ( f . __name__ , h . round ( 4 ) , np . degrees ( np . arccos ( min ( 1 , cos ) ) ) . round ( 1 ) )
Enter fullscreen mode
Exit fullscreen mode
When you clip the norm you're taking a shorter step the same way.…