"""Feed-forward blocks for encoder models.""" from __future__ import annotations import torch import torch.nn as nn import triton import triton.language as tl from ..L1.gelu import GELU from ..L1.layer_norm import LayerNorm from ..L1.linear import Linear @triton.jit def _residual_layer_norm_kernel( projected_ptr, residual_ptr, weight_ptr, bias_ptr, out_ptr, M: tl.constexpr, N: tl.constexpr, EPS: tl.constexpr, ): row = tl.program_id(0) cols = tl.arange(0, N) offsets = row * N + cols projected = tl.load(projected_ptr + offsets) residual = tl.load(residual_ptr + offsets) x = (projected + residual).to(tl.float16).to(tl.float32) mean = tl.sum(x, axis=0) / N centered = x - mean variance = tl.sum(centered * centered, axis=0) / N normalized = centered * tl.rsqrt(variance + EPS) weight = tl.load(weight_ptr + cols).to(tl.float32) bias = tl.load(bias_ptr + cols).to(tl.float32) tl.store(out_ptr + offsets, normalized * weight + bias) def _residual_layer_norm( projected: torch.Tensor, residual: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor, eps: float, ) -> torch.Tensor: m, n = projected.shape out = torch.empty_like(projected) if m == 64 else projected _residual_layer_norm_kernel[(m,)]( projected, residual, weight, bias, out, M=m, N=n, EPS=eps, num_warps=4 if m == 64 else 2, ) return out class EncoderIntermediate(nn.Module): def __init__(self, config): super().__init__() self.dense = Linear(config.hidden_size, config.intermediate_size, bias=True) self.intermediate_act_fn = GELU() def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: return self.intermediate_act_fn(self.dense(hidden_states)) class EncoderOutput(nn.Module): def __init__(self, config): super().__init__() self.dense = Linear(config.intermediate_size, config.hidden_size, bias=True) # promote_fp32=False: vLLM's bert.py / roberta.py use a plain # nn.LayerNorm here (see encoder_embeddings for the full rationale). self.LayerNorm = LayerNorm(config.hidden_size, eps=config.layer_norm_eps, promote_fp32=False) def forward( self, hidden_states: torch.Tensor, input_tensor: torch.Tensor, ) -> torch.Tensor: if ( hidden_states.is_cuda and hidden_states.dtype == torch.float16 and hidden_states.is_contiguous() and input_tensor.dtype == torch.float16 and input_tensor.is_contiguous() and input_tensor.device == hidden_states.device and hidden_states.ndim == 2 and hidden_states.shape[1] == 4096 and input_tensor.shape == (hidden_states.shape[0], 1024) and self.dense.weight.shape == (1024, 4096) and self.LayerNorm.weight is not None and self.LayerNorm.bias is not None ): projected = self.dense(hidden_states) return _residual_layer_norm( projected, input_tensor, self.LayerNorm.weight, self.LayerNorm.bias, self.LayerNorm.eps, ) return self.LayerNorm(self.dense(hidden_states) + input_tensor)