File size: 9,903 Bytes
fc1b627
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
"""
model.py - GromGPT, kien truc kieu LLaMA de ho tro NGU CANH DAI.

So voi ban cu (learned absolute position + nn.TransformerEncoder):
  - RoPE thay cho pos_emb hoc duoc -> khong con tran cung theo block_size,
    co the train/fine-tune o do dai lon hon ma khong doi tham so.
  - Attention dung F.scaled_dot_product_attention (Flash/mem-efficient) voi
    is_causal=True -> khong tao mask LxL, bo nho tang tuyen tinh theo L thay vi
    binh phuong. Day la dieu kien de train block 4096-32768 tren H100.
  - RMSNorm + SwiGLU, khong bias (giong LLaMA; llama.cpp ho tro san kien truc nay).
  - KV-cache cho sinh van ban: moi token moi chi tinh 1 vi tri thay vi ca chuoi.
  - Gradient checkpointing tuy chon (cat bo nho activation ~ n_layer lan).
  - Loss trung binh tren target hop le: batch bi mask hoan toan cho loss=0, khong NaN.

API giu nguyen: GromGPT(vocab, block_size, n_embd, n_head, n_layer, dropout, vision)
forward(idx, targets=None, images=None) -> (logits, loss).
"""
import math

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.checkpoint import checkpoint

from vision import ImageEncoder

ARCH = "llama_rope_v2"


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

    def forward(self, x):
        xf = x.float()
        out = xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + self.eps)
        return out.to(x.dtype) * self.weight


def rope_cos_sin(head_dim, offset, length, theta, device):
    """cos/sin [length, head_dim/2] cho cac vi tri offset..offset+length-1 (tinh fp32)."""
    inv = 1.0 / (theta ** (torch.arange(0, head_dim, 2, device=device, dtype=torch.float32) / head_dim))
    pos = torch.arange(offset, offset + length, device=device, dtype=torch.float32)
    freqs = torch.outer(pos, inv)
    return freqs.cos(), freqs.sin()


def apply_rope(x, cos, sin):
    """x [B,H,T,hd]. Xoay trong fp32 roi tra ve dtype cu (bf16 o vi tri lon se mat do chinh xac)."""
    half = x.size(-1) // 2
    xf = x.float()
    x1, x2 = xf[..., :half], xf[..., half:]
    out = torch.cat((x1 * cos - x2 * sin, x1 * sin + x2 * cos), dim=-1)
    return out.to(x.dtype)


class Attention(nn.Module):
    def __init__(self, n_embd, n_head, dropout):
        super().__init__()
        assert n_embd % n_head == 0, "n_embd phai chia het cho n_head"
        self.n_head = n_head
        self.head_dim = n_embd // n_head
        assert self.head_dim % 2 == 0, "head_dim phai chan de dung RoPE"
        self.qkv = nn.Linear(n_embd, 3 * n_embd, bias=False)
        self.proj = nn.Linear(n_embd, n_embd, bias=False)
        self.dropout = dropout

    def forward(self, x, cos, sin, attn_mask=None, is_causal=False, past=None, use_cache=False):
        B, T, C = x.shape
        q, k, v = self.qkv(x).view(B, T, 3, self.n_head, self.head_dim).unbind(2)
        q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)   # [B,H,T,hd]
        q = apply_rope(q, cos, sin)
        k = apply_rope(k, cos, sin)
        if past is not None:
            k = torch.cat([past[0], k], dim=2)
            v = torch.cat([past[1], v], dim=2)
        present = (k, v) if use_cache else None
        y = F.scaled_dot_product_attention(
            q, k, v, attn_mask=attn_mask,
            dropout_p=self.dropout if self.training else 0.0,
            is_causal=is_causal,
        )
        y = y.transpose(1, 2).reshape(B, T, C)
        return self.proj(y), present


class SwiGLU(nn.Module):
    def __init__(self, dim, hidden):
        super().__init__()
        self.w1 = nn.Linear(dim, hidden, bias=False)
        self.w3 = nn.Linear(dim, hidden, bias=False)
        self.w2 = nn.Linear(hidden, dim, bias=False)

    def forward(self, x):
        return self.w2(F.silu(self.w1(x)) * self.w3(x))


class Block(nn.Module):
    def __init__(self, n_embd, n_head, dropout):
        super().__init__()
        hidden = ((int(8 * n_embd / 3) + 63) // 64) * 64
        self.attn_norm = RMSNorm(n_embd)
        self.attn = Attention(n_embd, n_head, dropout)
        self.ffn_norm = RMSNorm(n_embd)
        self.ffn = SwiGLU(n_embd, hidden)
        self.drop = nn.Dropout(dropout)

    def forward(self, x, cos, sin, attn_mask=None, is_causal=False, past=None, use_cache=False):
        a, present = self.attn(self.attn_norm(x), cos, sin, attn_mask, is_causal, past, use_cache)
        x = x + self.drop(a)
        x = x + self.drop(self.ffn(self.ffn_norm(x)))
        return x, present


def _block_fwd(blk, x, cos, sin, attn_mask, is_causal):
    return blk(x, cos, sin, attn_mask, is_causal)[0]


class GromGPT(nn.Module):
    arch = ARCH

    def __init__(
        self,
        vocab_size,
        block_size=192,
        n_embd=192,
        n_head=6,
        n_layer=5,
        dropout=0.05,
        vision=None,
        rope_theta=10000.0,
        gradient_checkpointing=False,
    ):
        super().__init__()
        self.block_size = block_size
        self.n_embd = n_embd
        self.n_head = n_head
        self.n_layer = n_layer
        self.head_dim = n_embd // n_head
        self.rope_theta = float(rope_theta)
        self.grad_ckpt = bool(gradient_checkpointing)
        self.token_emb = nn.Embedding(vocab_size, n_embd)
        self.drop = nn.Dropout(dropout)
        self.blocks = nn.ModuleList([Block(n_embd, n_head, dropout) for _ in range(n_layer)])
        self.norm = RMSNorm(n_embd)
        self.head = nn.Linear(n_embd, vocab_size, bias=False)
        self.head.weight = self.token_emb.weight
        # Nhanh anh (tuy chon). vision=None -> model chi xu ly van ban.
        self.vision_cfg = dict(vision) if vision else None
        self.n_img_tokens = int(vision.get("n_img_tokens", 16)) if vision else 0
        self.image_encoder = ImageEncoder(n_embd, dropout=dropout, **vision) if vision else None
        self.apply(self._init_weights)
        # Khoi tao residual-projection nho hon (GPT-2/LLaMA) de on dinh khi sau 24+ lop.
        res_std = 0.02 / math.sqrt(2 * n_layer)
        for blk in self.blocks:
            nn.init.normal_(blk.attn.proj.weight, mean=0.0, std=res_std)
            nn.init.normal_(blk.ffn.w2.weight, mean=0.0, std=res_std)

    def _init_weights(self, module):
        if isinstance(module, (nn.Linear, nn.Embedding)):
            nn.init.normal_(module.weight, mean=0.0, std=0.02)
            if isinstance(module, nn.Linear) and module.bias is not None:
                nn.init.zeros_(module.bias)

    def encode_image(self, images):
        """[B,3,S,S] -> [B, n_img_tokens, n_embd]."""
        if self.image_encoder is None:
            raise RuntimeError("Model nay duoc tao khong co nhanh anh (vision=None).")
        return self.image_encoder(images)

    def forward(self, idx, targets=None, images=None, past_kv=None, use_cache=False):
        """idx [B,T]. images [B,3,S,S] hoac None.

        Train / prefill: past_kv=None. Co images -> chuoi la [token anh | token van ban],
        token anh nhin nhau (khong nhan qua), van ban nhin moi anh. Loss chi tren van ban,
        logits tra ve chi gom vi tri van ban.
        Decode: truyen past_kv (tu lan goi truoc voi use_cache=True) va idx [B,1].
        use_cache=True tra ve (logits, loss, present_kv).
        """
        B, T = idx.shape
        n_img = 0
        img_tok = None
        if past_kv is not None:
            if images is not None:
                raise ValueError("images chi dung o buoc prefill (past_kv=None).")
            if T != 1:
                raise ValueError("Co past_kv thi moi lan chi nap dung 1 token.")
            past_len = past_kv[0][0].size(2)
        else:
            past_len = 0
            if images is not None:
                img_tok = self.encode_image(images)
                n_img = img_tok.size(1)
            text_max = self.block_size - n_img
            if text_max < 1:
                raise ValueError(f"n_img_tokens={n_img} >= block_size={self.block_size}")
            if T > text_max:
                idx = idx[:, -text_max:]
                T = text_max
                if targets is not None:
                    targets = targets[:, -text_max:]

        tok = self.token_emb(idx)
        if img_tok is not None:
            tok = torch.cat([img_tok.to(tok.dtype), tok], dim=1)
        x = self.drop(tok)
        L = n_img + T
        cos, sin = rope_cos_sin(self.head_dim, past_len, L, self.rope_theta, idx.device)

        attn_mask, is_causal = None, False
        if past_kv is None:
            if n_img:
                attn_mask = torch.ones(L, L, dtype=torch.bool, device=idx.device).tril()
                attn_mask[:n_img, :n_img] = True
            else:
                is_causal = True

        presents = [] if use_cache else None
        use_ckpt = self.grad_ckpt and self.training and not use_cache and torch.is_grad_enabled()
        for i, blk in enumerate(self.blocks):
            if use_ckpt:
                x = checkpoint(_block_fwd, blk, x, cos, sin, attn_mask, is_causal, use_reentrant=False)
            else:
                x, pres = blk(x, cos, sin, attn_mask, is_causal,
                              past_kv[i] if past_kv is not None else None, use_cache)
                if use_cache:
                    presents.append(pres)
        x = self.norm(x)
        if n_img:
            x = x[:, n_img:, :]
        logits = self.head(x)
        loss = None
        if targets is not None:
            # Trung binh tren target hop le (!= -100). Batch bi mask het -> loss=0, khong NaN.
            flat_t = targets.reshape(-1)
            n_valid = (flat_t != -100).sum().clamp(min=1)
            loss = F.cross_entropy(
                logits.reshape(-1, logits.size(-1)), flat_t,
                ignore_index=-100, reduction="sum",
            ) / n_valid
        if use_cache:
            return logits, loss, presents
        return logits, loss