完整题目
请手动实现Layer Normalization(层归一化)的前向传播过程,要求使用Python和NumPy编写代码,不调用高级框架API,并解释其实现细节和数值稳定性处理方法。
NumPy 实现
import numpy as np
class LayerNorm:
def __init__(self, normalized_shape, eps=1e-5):
self.normalized_shape = tuple(
normalized_shape if isinstance(normalized_shape, (tuple, list))
else (normalized_shape,)
)
self.eps = eps
self.gamma = np.ones(self.normalized_shape, dtype=np.float32)
self.beta = np.zeros(self.normalized_shape, dtype=np.float32)
def forward(self, x):
if tuple(x.shape[-len(self.normalized_shape):]) != self.normalized_shape:
raise ValueError("input tail shape does not match normalized_shape")
axes = tuple(range(x.ndim - len(self.normalized_shape), x.ndim))
input_dtype = x.dtype
input_is_bfloat16 = input_dtype.name == "bfloat16"
input_is_float = input_is_bfloat16 or np.issubdtype(
input_dtype, np.floating
)
low_precision = input_dtype == np.float16 or input_is_bfloat16
if low_precision or not input_is_float:
work = x.astype(np.float32)
else:
work = x
mean = np.mean(work, axis=axes, keepdims=True)
var = np.mean((work - mean) ** 2, axis=axes, keepdims=True)
x_hat = (work - mean) / np.sqrt(var + self.eps)
gamma = self.gamma.astype(work.dtype, copy=False)
beta = self.beta.astype(work.dtype, copy=False)
out = x_hat * gamma + beta
return out.astype(input_dtype, copy=False) if input_is_float else out关键点
PyTorch LayerNorm 对最后 len(normalized_shape) 个维度共同求均值和方差,不只是最后一维;gamma/beta 的 shape 与 normalized_shape 相同,并通过广播作用于前导 batch 维。使用 mean((x-mean)^2) 比 E[x^2]-E[x]^2 更不易遭受消减误差。epsilon 加在方差后、开根前,用来避免极小方差造成除零或过大缩放;不是因为 sqrt(var) 自己会产生负数。低精度浮点输入可用 FP32 累积统计量后转回输入 dtype;float64 输入不应无条件降为 float32。