Deep Neural Representations & Normalization Mathematics
Universal Approximation Theorem, tensor backprop, and scale-invariance of LayerNorm and RMSNorm.
💡 1. Core Intuition & Concepts
Deep neural networks transform non-linear input manifolds through successive affine and activation layers. Normalization techniques enforce scale-invariance and variance bounds, preventing internal covariate shift and vanishing/exploding gradients across hundreds of residual layers.
📐 2. Mathematical Formulations & Derivations
• Let y_i = RMSNorm(x)_i = (x_i / RMS(x)) * gamma_i, where RMS(x) = ((1/D) * sum_{k=1}^D x_k^2 + eps)^(1/2).
• Compute partial derivative ∂RMS(x)/∂x_i = (1 / (2 RMS(x))) * (2 x_i / D) = x_i / (D * RMS(x)).
• By the multivariable chain rule: ∂L/∂x_i = sum_{j=1}^D (∂L/∂y_j) * (∂y_j/∂x_i).
• Differentiating y_j: ∂y_j/∂x_i = (gamma_j / RMS(x)) * delta_{ij} - (x_j gamma_j / RMS(x)^2) * (∂RMS(x)/∂x_i) = (gamma_i delta_{ij} / RMS(x)) - (x_j gamma_j x_i / (D RMS(x)^3)).
• Substitute and factor: ∂L/∂x_i = (gamma_i / RMS(x)) * (∂L/∂y_i) - (x_i / (D RMS(x)^3)) * sum_{j=1}^D (∂L/∂y_j * gamma_j x_j). Q.E.D.
⚙️ 3. Step-by-Step Computational Mechanism
💻 4. Code from Scratch (python)
import numpy as np
# Exact Vectorized RMSNorm Forward & Backward Implementation
class RMSNormScratch:
def __init__(self, dim: int, eps: float = 1e-6):
self.eps = eps
self.gamma = np.ones(dim)
def forward(self, x: np.ndarray) -> np.ndarray:
self.x = x
self.rms = np.sqrt(np.mean(x**2, axis=-1, keepdims=True) + self.eps)
self.x_norm = x / self.rms
return self.x_norm * self.gamma
def backward(self, dout: np.ndarray) -> np.ndarray:
D = self.x.shape[-1]
# dL/dgamma
self.dgamma = np.sum(dout * self.x_norm, axis=0)
# Analytical dL/dx
sum_term = np.sum(dout * self.gamma * self.x, axis=-1, keepdims=True)
dx = (dout * self.gamma / self.rms) - (self.x / (D * self.rms**3)) * sum_term
return dx
if __name__ == "__main__":
layer = RMSNormScratch(dim=4)
x = np.array([[1.0, 2.0, 3.0, 4.0]])
out = layer.forward(x)
dx = layer.backward(np.ones_like(out))
print("Forward output: ", np.round(out, 4))
print("Backward grad dx:", np.round(dx, 4))🧠 5. Comprehension Checkpoint
In the catalog
Finished this chapter?