Download xavante_work/flexnet/layer_norm_modules.py from PowerMachine/gru-ring-v13-9-2: direct link, hf CLI and curl.
- Browser
- Download file 3.12 kB
-
https://huggingface.co/PowerMachine/gru-ring-v13-9-2/resolve/main/xavante_work/flexnet/layer_norm_modules.py
- Command line
-
hf download hf://PowerMachine/gru-ring-v13-9-2/xavante_work/flexnet/layer_norm_modules.py
-
curl -L -o layer_norm_modules.py https://huggingface.co/PowerMachine/gru-ring-v13-9-2/resolve/main/xavante_work/flexnet/layer_norm_modules.py
3.12 kB
| """ | |
| layer_norm_modules — Layer Normalization customizado e variantes. | |
| Implementa: | |
| 1) LayerNorm padrão (Ba et al. 2016) — preserva escala, estabiliza treino | |
| 2) RMSNorm (Zhang & Sennrich 2019) — apenas reescala por RMS, sem bias | |
| 3) ConditionalLayerNorm — LayerNorm com gating condicional (para multimodal) | |
| Equações: | |
| LayerNorm: y = γ ⊙ (x - μ) / sqrt(σ² + ε) + β | |
| RMSNorm: y = γ ⊙ x / sqrt(mean(x²) + ε) | |
| Conditional: y = γ(c) ⊙ (x - μ)/σ + β(c), onde γ, β dependem de contexto c | |
| """ | |
| from __future__ import annotations | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| class LayerNorm(nn.Module): | |
| """LayerNorm padrão com inicialização identity-like (γ=1, β=0).""" | |
| def __init__(self, dim: int, eps: float = 1e-5): | |
| super().__init__() | |
| self.gamma = nn.Parameter(torch.ones(dim)) | |
| self.beta = nn.Parameter(torch.zeros(dim)) | |
| self.eps = eps | |
| def forward(self, x: torch.Tensor) -> torch.Tensor: | |
| mean = x.mean(dim=-1, keepdim=True) | |
| var = x.var(dim=-1, keepdim=True, unbiased=False) | |
| x_norm = (x - mean) / torch.sqrt(var + self.eps) | |
| return self.gamma * x_norm + self.beta | |
| class RMSNorm(nn.Module): | |
| """RMSNorm — mais barato que LayerNorm (sem subtração de média, sem bias).""" | |
| def __init__(self, dim: int, eps: float = 1e-6): | |
| super().__init__() | |
| self.gamma = nn.Parameter(torch.ones(dim)) | |
| self.eps = eps | |
| def forward(self, x: torch.Tensor) -> torch.Tensor: | |
| rms = torch.sqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps) | |
| return self.gamma * x / rms | |
| class ConditionalLayerNorm(nn.Module): | |
| """LayerNorm cujos γ, β são gerados a partir de um contexto (modality embedding). | |
| Útil para fusão multimodal: normaliza o hidden state condicionalmente | |
| à modalidade ativa (texto vs imagem vs áudio). | |
| Args: | |
| dim: dimensão do hidden state. | |
| cond_dim: dimensão do vetor de condição (e.g. embedding de modalidade). | |
| """ | |
| def __init__(self, dim: int, cond_dim: int, eps: float = 1e-5): | |
| super().__init__() | |
| self.dim = dim | |
| self.cond_dim = cond_dim | |
| self.eps = eps | |
| # γ e β são produzidos por uma transformação linear do contexto. | |
| self.gamma_proj = nn.Linear(cond_dim, dim) | |
| self.beta_proj = nn.Linear(cond_dim, dim) | |
| # Inicialização: γ_proj bias=1 (identity), β_proj bias=0. | |
| nn.init.zeros_(self.gamma_proj.weight) | |
| nn.init.ones_(self.gamma_proj.bias) | |
| nn.init.zeros_(self.beta_proj.weight) | |
| nn.init.zeros_(self.beta_proj.bias) | |
| def forward(self, x: torch.Tensor, cond: torch.Tensor) -> torch.Tensor: | |
| """ | |
| x: (..., dim) | |
| cond: (..., cond_dim) — mesmo batch dims que x. | |
| """ | |
| mean = x.mean(dim=-1, keepdim=True) | |
| var = x.var(dim=-1, keepdim=True, unbiased=False) | |
| x_norm = (x - mean) / torch.sqrt(var + self.eps) | |
| gamma = self.gamma_proj(cond) # (..., dim) | |
| beta = self.beta_proj(cond) | |
| return gamma * x_norm + beta | |