241. 按全局范数裁剪梯度列表
大模型训练中会裁剪梯度,以防止单个异常 batch 导致权重爆炸。标准做法是将所有梯度视为一个长向量来测量其总范数,并按相同的比例缩放每个 tensor,从而保持更新方向不变。
编写 clip_by_global_norm(grads, max_norm),其中 grads 是一个包含任意形状数组的列表。
- total = sqrt(每个数组中每个元素的平方和)。
- 如果 total > max_norm,则将每个数组乘以 max_norm / total。否则保持不变。
返回 (clipped_list, total),其中 total 是裁剪前的范数,类型为 float。
def clip_by_global_norm(grads, max_norm)示例 1
输入: grads [[3.0], [4.0]] with max_norm 1.0
输出: total 5.0 and clipped [[0.6], [0.8]]
示例 2
输入: grads = [[0.1, 0.2], [0.2]], max_norm = 1.0
输出: ([[0.1, 0.2], [0.2]], 0.3)
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
提示 1
Treat all gradient arrays as one long vector: one norm for everything and one shared scale factor, so the direction does not change.
提示 2
Sum the squares of every entry of every array, take the square root to get total, and if total is above max_norm multiply each array by max_norm / total.
提示 3
Return the total from before clipping as a float, and leave the arrays untouched when total <= max_norm, so the scale is only applied in the strict total > max_norm case.
常见错误
- 错误的实现版本按每个 tensor 自身的范数进行裁剪。
理解思路
梯度裁剪是权重更新的速度限制。Global norm clipping 将每个梯度 tensor 视为一个长向量的一部分,测量其总长度,如果长度过大,则按相同的比例缩小所有 tensor。由于每个部分都按相同比例缩放,更新方向得以保持,仅大小发生变化。
grads [[1, 2], [2]] 且 max_norm 为 1.5。Total = sqrt(1 + 4 + 4) = 3。由于 3 > 1.5,scale = 1.5 / 3 = 0.5,结果为 [[0.5, 1.0], [1.0]]。新的 total 正好是 1.5。如果 max_norm 为 5,则不会发生变化。
total = 每个 tensor 中每个元素平方和的平方根;如果 total > max_norm,则将每个 tensor 乘以 max_norm / total;返回裁剪后的 tensor 和原始 total。在此处按每个 tensor 自身的范数进行裁剪是另一种错误的方法。该方法几乎用于所有的 LLM 训练任务中,通常 max_norm = 1.0。