File size: 3,429 Bytes
3087568
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
"""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)