File size: 9,334 Bytes
7e2b18f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import math
from dataclasses import dataclass
from typing import Optional, Tuple

import torch
import torch.nn as nn
import torch.nn.functional as F


@dataclass
class MarsLMConfig:
    vocab_size: int = 32000
    hidden_size: int = 768
    intermediate_size: int = 2048
    num_hidden_layers: int = 12
    num_attention_heads: int = 12
    max_position_embeddings: int = 2048
    dropout: float = 0.0
    layer_norm_eps: float = 1e-5
    rope_theta: float = 10000.0
    use_cache: bool = True

    @property
    def head_dim(self) -> int:
        return self.hidden_size // self.num_attention_heads


class RMSNorm(nn.Module):
    def __init__(self, dim: int, eps: float = 1e-5):
        super().__init__()
        self.eps = eps
        self.weight = nn.Parameter(torch.ones(dim))

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        rms = x.pow(2).mean(-1, keepdim=True).add(self.eps).sqrt()
        return self.weight * (x / rms)


def _build_rotary_cache(positions: torch.Tensor, head_dim: int, theta: float, device: torch.device) -> Tuple[torch.Tensor, torch.Tensor]:
    if head_dim % 2 != 0:
        raise ValueError("head_dim must be even for rotary embeddings")
    inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2, device=device, dtype=torch.float32) / head_dim))
    freqs = torch.einsum("bt,d->btd", positions.to(torch.float32), inv_freq)
    cos = torch.cos(freqs)
    sin = torch.sin(freqs)
    return cos, sin


def _apply_rotary(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
    x = x.to(torch.float32)
    x_even = x[..., 0::2]
    x_odd = x[..., 1::2]
    x_pairs = torch.stack((x_even, x_odd), dim=-1)
    rotated = torch.stack((-x_pairs[..., 1], x_pairs[..., 0]), dim=-1)
    cos = cos.unsqueeze(-1)
    sin = sin.unsqueeze(-1)
    out = x_pairs * cos + rotated * sin
    return out.flatten(-2).to(dtype=x.dtype)


class CausalSelfAttention(nn.Module):
    def __init__(self, config: MarsLMConfig):
        super().__init__()
        if config.hidden_size % config.num_attention_heads != 0:
            raise ValueError("hidden_size must be divisible by num_attention_heads")
        self.config = config
        self.num_heads = config.num_attention_heads
        self.head_dim = config.head_dim
        self.q_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
        self.k_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
        self.v_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
        self.o_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
        self.attn_dropout = nn.Dropout(config.dropout)
        self.resid_dropout = nn.Dropout(config.dropout)

    def _build_causal_mask(self, q_len: int, kv_len: int, device: torch.device) -> Optional[torch.Tensor]:
        if q_len == 1 and kv_len == 1:
            return None
        mask = torch.ones((1, 1, q_len, kv_len), device=device, dtype=torch.bool)
        for qi in range(q_len):
            mask[:, :, qi, qi + 1:] = False
        return mask

    def forward(
        self,
        x: torch.Tensor,
        attention_mask: Optional[torch.Tensor] = None,
        past_key_value: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
        use_cache: bool = False,
        position_ids: Optional[torch.Tensor] = None,
    ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
        batch_size, seq_len, _ = x.size()
        q = self.q_proj(x).view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
        k = self.k_proj(x).view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
        v = self.v_proj(x).view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)

        if position_ids is None:
            position_ids = torch.arange(seq_len, device=x.device).unsqueeze(0).expand(batch_size, -1)
        cos, sin = _build_rotary_cache(position_ids, self.head_dim, self.config.rope_theta, x.device)
        cos = cos.unsqueeze(1)
        sin = sin.unsqueeze(1)
        q = _apply_rotary(q, cos, sin)
        k = _apply_rotary(k, cos, sin)

        if past_key_value is not None:
            prev_k, prev_v = past_key_value
            k = torch.cat([prev_k, k], dim=2)
            v = torch.cat([prev_v, v], dim=2)
        present_key_value = (k, v) if use_cache else None

        if attention_mask is not None:
            attn_mask = attention_mask.to(dtype=torch.bool, device=x.device)
            if attn_mask.dim() == 2:
                attn_mask = attn_mask[:, None, None, :]
        else:
            attn_mask = self._build_causal_mask(seq_len, k.size(2), x.device)

        scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
        if attn_mask is not None:
            scores = scores.masked_fill(~attn_mask, torch.finfo(scores.dtype).min)
        probs = torch.softmax(scores, dim=-1)
        attn_output = torch.matmul(probs, v)

        attn_output = attn_output.transpose(1, 2).contiguous().view(batch_size, seq_len, self.config.hidden_size)
        attn_output = self.o_proj(attn_output)
        attn_output = self.resid_dropout(attn_output)
        return attn_output, present_key_value


class MLP(nn.Module):
    def __init__(self, config: MarsLMConfig):
        super().__init__()
        self.c_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
        self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
        self.out_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
        self.dropout = nn.Dropout(config.dropout)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        hidden = F.silu(self.c_proj(x)) * self.gate_proj(x)
        hidden = self.out_proj(hidden)
        return self.dropout(hidden)


class TransformerBlock(nn.Module):
    def __init__(self, config: MarsLMConfig):
        super().__init__()
        self.attn_norm = RMSNorm(config.hidden_size, eps=config.layer_norm_eps)
        self.ffn_norm = RMSNorm(config.hidden_size, eps=config.layer_norm_eps)
        self.attn = CausalSelfAttention(config)
        self.mlp = MLP(config)

    def forward(
        self,
        x: torch.Tensor,
        attention_mask: Optional[torch.Tensor] = None,
        past_key_value: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
        use_cache: bool = False,
        position_ids: Optional[torch.Tensor] = None,
    ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
        attn_input = self.attn_norm(x)
        attn_output, present = self.attn(attn_input, attention_mask, past_key_value, use_cache, position_ids)
        x = x + attn_output
        ffn_input = self.ffn_norm(x)
        x = x + self.mlp(ffn_input)
        return x, present


class MarsLMModel(nn.Module):
    def __init__(self, config: MarsLMConfig):
        super().__init__()
        self.config = config
        self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
        self.layers = nn.ModuleList([TransformerBlock(config) for _ in range(config.num_hidden_layers)])
        self.norm = RMSNorm(config.hidden_size, eps=config.layer_norm_eps)

    def forward(
        self,
        input_ids: torch.Tensor,
        attention_mask: Optional[torch.Tensor] = None,
        past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
        use_cache: bool = False,
        position_ids: Optional[torch.Tensor] = None,
    ) -> Tuple[torch.Tensor, Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]]]:
        hidden_states = self.embed_tokens(input_ids)
        present = [] if use_cache else None
        if past_key_values is None:
            past_key_values = [None] * len(self.layers)
        for idx, layer in enumerate(self.layers):
            hidden_states, layer_present = layer(
                hidden_states,
                attention_mask,
                past_key_values[idx],
                use_cache=use_cache,
                position_ids=position_ids,
            )
            if use_cache:
                present.append(layer_present)
        hidden_states = self.norm(hidden_states)
        return hidden_states, tuple(present) if use_cache else None


class MarsLMForCausalLM(nn.Module):
    def __init__(self, config: MarsLMConfig):
        super().__init__()
        self.config = config
        self.model = MarsLMModel(config)
        self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)

    def forward(
        self,
        input_ids: torch.Tensor,
        attention_mask: Optional[torch.Tensor] = None,
        past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
        use_cache: bool = False,
        position_ids: Optional[torch.Tensor] = None,
    ) -> Tuple[torch.Tensor, Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]]]:
        hidden_states, present = self.model(
            input_ids=input_ids,
            attention_mask=attention_mask,
            past_key_values=past_key_values,
            use_cache=use_cache,
            position_ids=position_ids,
        )
        logits = self.lm_head(hidden_states)
        return logits, present


def build_model_from_config(config: MarsLMConfig) -> MarsLMForCausalLM:
    return MarsLMForCausalLM(config)