File size: 5,408 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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
"""Decoder layer: attention + MLP with RMSNorm residual connections.

Unified across Llama, Qwen2, and Qwen3 architectures:
  - bias:    Qwen2 uses bias=True on QKV projection.
  - qk_norm: Qwen3 applies per-head RMSNorm to Q and K before RoPE.
"""

from __future__ import annotations

import torch
import torch.nn as nn
import triton
import triton.language as tl

from ....infra.cuda_ext import lazy_op
from ..L1.rms_norm import RMSNorm
from ..L2.attention import LlamaAttention
from ..L2.llama_mlp import LlamaMLP


_C = lazy_op("candidate_llama_decoder", "llama_decoder.cu")


@triton.jit
def _rms_norm_kernel(
    x_ptr,
    weight_ptr,
    out_ptr,
    n_cols: tl.constexpr,
    eps: tl.constexpr,
    BLOCK_N: tl.constexpr,
):
    row = tl.program_id(0)
    cols = tl.arange(0, BLOCK_N)
    mask = cols < n_cols
    offsets = row * n_cols + cols

    x = tl.load(x_ptr + offsets, mask=mask, other=0.0).to(tl.float32)
    variance = tl.sum(x * x, axis=0) / n_cols
    normalized = (x * tl.rsqrt(variance + eps)).to(tl.bfloat16)
    weight = tl.load(weight_ptr + cols, mask=mask, other=0.0)
    tl.store(out_ptr + offsets, normalized * weight, mask=mask)


@triton.jit
def _fused_add_rms_norm_kernel(
    x_ptr,
    residual_ptr,
    weight_ptr,
    n_cols: tl.constexpr,
    eps: tl.constexpr,
    BLOCK_N: tl.constexpr,
):
    row = tl.program_id(0)
    cols = tl.arange(0, BLOCK_N)
    mask = cols < n_cols
    offsets = row * n_cols + cols

    x = tl.load(x_ptr + offsets, mask=mask, other=0.0).to(tl.float32)
    residual = tl.load(
        residual_ptr + offsets, mask=mask, other=0.0,
    ).to(tl.float32)
    summed = (x + residual).to(tl.bfloat16)
    tl.store(residual_ptr + offsets, summed, mask=mask)

    summed_f32 = summed.to(tl.float32)
    variance = tl.sum(summed_f32 * summed_f32, axis=0) / n_cols
    normalized = (
        summed_f32 * tl.rsqrt(variance + eps)
    ).to(tl.bfloat16)
    weight = tl.load(weight_ptr + cols, mask=mask, other=0.0)
    tl.store(x_ptr + offsets, normalized * weight, mask=mask)


class LlamaDecoderLayer(nn.Module):
    def __init__(self, config, rotary_emb: nn.Module | None = None,
                 bias: bool = False, qk_norm: bool = False,
                 quant_config: dict | None = None):
        super().__init__()
        self.self_attn = LlamaAttention(
            config.hidden_size, config.num_attention_heads,
            config.num_key_value_heads, config.head_dim,
            rotary_emb=rotary_emb,
            bias=bias, qk_norm=qk_norm,
            rms_norm_eps=config.rms_norm_eps,
            quant_config=quant_config,
        )
        self.mlp = LlamaMLP(config, quant_config=quant_config)
        self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
        self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)

    @staticmethod
    def _norm(layer, hidden_states, residual=None):
        n_cols = hidden_states.shape[-1]
        n_rows = hidden_states.numel() // n_cols
        block_n = triton.next_power_of_2(n_cols)
        if residual is None:
            out = torch.empty_like(hidden_states)
            _rms_norm_kernel[(n_rows,)](
                hidden_states, layer.weight, out, n_cols, layer.eps,
                BLOCK_N=block_n, num_warps=8,
            )
            return out

        if (
            hidden_states.is_cuda
            and hidden_states.dtype == torch.bfloat16
            and hidden_states.is_contiguous()
            and residual.is_contiguous()
            and n_cols == 4096
        ):
            _C.fused_add_rms_norm_bf16(
                hidden_states, residual, layer.weight, layer.eps
            )
            return hidden_states, residual

        _fused_add_rms_norm_kernel[(n_rows,)](
            hidden_states, residual, layer.weight, n_cols, layer.eps,
            BLOCK_N=block_n, num_warps=8,
        )
        return hidden_states, residual

    def _mlp(self, hidden_states):
        gate_up = self.mlp.gate_up_proj
        down = self.mlp.down_proj
        if (
            hidden_states.is_cuda
            and hidden_states.dtype == torch.bfloat16
            and not gate_up.use_fp8
            and not down.use_fp8
            and down.tp_size == 1
        ):
            projected = torch._C._nn.linear(
                hidden_states, gate_up.weight, gate_up.bias
            )
            activated = torch.empty(
                (*projected.shape[:-1], projected.shape[-1] // 2),
                dtype=projected.dtype,
                device=projected.device,
            )
            _C.silu_and_mul_bf16(projected, activated)
            return torch._C._nn.linear(
                activated, down.weight, down.bias
            )
        return self.mlp(hidden_states)

    def forward(self, positions, hidden_states, residual):
        if residual is None:
            hidden_states, residual = (
                self._norm(self.input_layernorm, hidden_states), hidden_states
            )
        else:
            hidden_states, residual = self._norm(
                self.input_layernorm, hidden_states, residual
            )
        hidden_states = self.self_attn(positions, hidden_states)
        hidden_states, residual = self._norm(
            self.post_attention_layernorm, hidden_states, residual
        )
        hidden_states = self._mlp(hidden_states)
        return hidden_states, residual