class paddle.fluid.clip.GradientClipByGlobalNorm(clip_norm, group_name='default_group')[source]

Clips values of multiple tensors by the ratio of the sum of their norms.

Given a list of tensors t_list , and a clipping ratio clip_norm, this operation returns a instance of this class as first parameter of set_gradient_clip method, second parameter of set_gradient_clip is used to compute clipped tensors list list_clipped (default value is None, compute global norm global_norm based in all tensors). global norm (global_norm) of all tensors in t_list.

To perform the clipping, the values \(t\_list[i]\) are set to:

\[t\_list[i] = t\_list[i] * \frac{clip\_norm}{\max(global\_norm, clip\_norm)}\]


\[global\_norm = \sqrt{\sum_{i=0}^{N-1}(l2norm(t\_list[i]))^2}\]

If \(clip\_norm > global\_norm\) then the entries in t_list remain as they are, otherwise they’re all shrunk by the global ratio.

  • clip_norm (float) – The maximum norm value

  • group_name (str, optional) – The group name for this clip.


import paddle.fluid as fluid
import paddle.fluid.core as core
import paddle

place = core.CPUPlace()
prog = fluid.framework.Program()
startup_program = fluid.framework.Program()
with fluid.program_guard(
        main_program=prog, startup_program=startup_program):
    image =
        name='x', shape=[784], dtype='float32')
    label ='y', shape=[1], dtype='int64')
    hidden1 = fluid.layers.fc(input=image, size=128, act='relu')
    hidden2 = fluid.layers.fc(input=hidden1, size=64, act='relu')
    predict = fluid.layers.fc(
        input=hidden2, size=10, act='softmax')
    cost = fluid.layers.cross_entropy(input=predict, label=label)
    avg_cost = fluid.layers.mean(cost)

prog_clip = prog.clone()
avg_cost_clip = prog_clip.block(0).var(

p_g = fluid.backward.append_backward(loss=avg_cost)
p_g_clip = fluid.backward.append_backward(loss=avg_cost_clip)

with fluid.program_guard(main_program=prog_clip, startup_program=startup_program):
    p_g_clip = fluid.clip.append_gradient_clip_ops(p_g_clip)

grad_list = [elem[1] for elem in p_g]
grad_clip_list = [elem[1] for elem in p_g_clip]

train_reader = paddle.batch(
        paddle.dataset.mnist.train(), buf_size=8192),

exe = fluid.Executor(place)
feeder = fluid.DataFeeder(feed_list=[image, label], place=place)

count = 0
for data in train_reader():
    count += 1
    print("count:%s" % count)
    if count > 5:
    out =, feed=feeder.feed(
        data), fetch_list=grad_list)
    out_clip =,