File size: 8,656 Bytes
dfeab58 | 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 | import math
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
@dataclass
class GPTConfig:
vocab_size: int = 12 # 0-9, PAD, EOS
pad_id: int = 10
eos_id: int = 11
d_model: int = 256
n_layers: int = 6
n_heads: int = 4
d_ff: int = 1024
dropout: float = 0.05
bias: bool = False
max_seq_len: int = 64
patch_size: int = 4
img_h: int = 28
img_w: int = 140
class LayerNorm(nn.Module):
def __init__(self, dim: int, bias: bool = False):
super().__init__()
self.weight = nn.Parameter(torch.ones(dim))
self.bias = nn.Parameter(torch.zeros(dim)) if bias else None
def forward(self, x: torch.Tensor) -> torch.Tensor:
return F.layer_norm(x, (x.size(-1),), self.weight, self.bias)
class CausalSelfAttention(nn.Module):
def __init__(self, config: GPTConfig):
super().__init__()
self.n_heads = config.n_heads
self.d_model = config.d_model
self.d_k = config.d_model // config.n_heads
self.dropout_p = config.dropout
self.q_proj = nn.Linear(config.d_model, config.d_model, bias=config.bias)
self.k_proj = nn.Linear(config.d_model, config.d_model, bias=config.bias)
self.v_proj = nn.Linear(config.d_model, config.d_model, bias=config.bias)
self.o_proj = nn.Linear(config.d_model, config.d_model, bias=config.bias)
self.attn_dropout = nn.Dropout(config.dropout)
self.resid_dropout = nn.Dropout(config.dropout)
def forward(self, x: torch.Tensor, attn_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
B, T, C = x.size()
q = self.q_proj(x).view(B, T, self.n_heads, self.d_k).transpose(1, 2)
k = self.k_proj(x).view(B, T, self.n_heads, self.d_k).transpose(1, 2)
v = self.v_proj(x).view(B, T, self.n_heads, self.d_k).transpose(1, 2)
att = (q @ k.transpose(-2, -1)) / math.sqrt(self.d_k)
if attn_mask is not None:
att = att.masked_fill(attn_mask == 0, float("-inf"))
att = F.softmax(att, dim=-1)
att = self.attn_dropout(att)
y = att @ v
y = y.transpose(1, 2).contiguous().view(B, T, C)
y = self.o_proj(y)
y = self.resid_dropout(y)
return y
class MLP(nn.Module):
def __init__(self, config: GPTConfig):
super().__init__()
self.fc1 = nn.Linear(config.d_model, config.d_ff, bias=config.bias)
self.fc2 = nn.Linear(config.d_ff, config.d_model, bias=config.bias)
self.dropout = nn.Dropout(config.dropout)
self.act = nn.GELU()
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.act(self.fc1(x))
x = self.dropout(x)
x = self.fc2(x)
return x
class TransformerBlock(nn.Module):
def __init__(self, config: GPTConfig):
super().__init__()
self.ln1 = LayerNorm(config.d_model, bias=config.bias)
self.attn = CausalSelfAttention(config)
self.ln2 = LayerNorm(config.d_model, bias=config.bias)
self.mlp = MLP(config)
def forward(self, x: torch.Tensor, attn_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
x = x + self.attn(self.ln1(x), attn_mask=attn_mask)
x = x + self.mlp(self.ln2(x))
return x
class PatchEmbed(nn.Module):
def __init__(self, img_h: int, img_w: int, patch_size: int, d_model: int):
super().__init__()
self.img_h = img_h
self.img_w = img_w
self.patch_size = patch_size
self.n_p_h = img_h // patch_size
self.n_p_w = img_w // patch_size
self.n_patches = self.n_p_h * self.n_p_w
self.proj = nn.Linear(patch_size * patch_size, d_model, bias=False)
def forward(self, x: torch.Tensor) -> torch.Tensor:
# x: (B, 1, H, W)
B, C, H, W = x.shape
if (C, H, W) != (1, self.img_h, self.img_w):
raise ValueError(
f"expected input (B, 1, {self.img_h}, {self.img_w}), got ({B}, {C}, {H}, {W}). "
f"Resize or pad the image first (see infer.preprocess_image)."
)
x = x.view(B, self.n_p_h, self.patch_size, self.n_p_w, self.patch_size)
x = x.permute(0, 1, 3, 2, 4).contiguous()
x = x.view(B, self.n_patches, self.patch_size * self.patch_size)
x = self.proj(x)
return x
class DigitGPT(nn.Module):
def __init__(self, config: GPTConfig, img_h: int, img_w: int):
super().__init__()
self.config = config
self.img_h = img_h
self.img_w = img_w
self.patch_embed = PatchEmbed(img_h, img_w, config.patch_size, config.d_model)
n_img_p = self.patch_embed.n_patches
self.tok_embed = nn.Embedding(config.vocab_size, config.d_model, padding_idx=config.pad_id)
self.pos_embed = nn.Parameter(torch.zeros(1, n_img_p + config.max_seq_len, config.d_model))
self.drop = nn.Dropout(config.dropout)
self.blocks = nn.ModuleList([TransformerBlock(config) for _ in range(config.n_layers)])
self.ln_f = LayerNorm(config.d_model, bias=config.bias)
self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
self.register_buffer("attn_mask_cache", None, persistent=False)
self.apply(self._init_weights)
def _init_weights(self, m):
if isinstance(m, nn.Linear):
torch.nn.init.normal_(m.weight, mean=0.0, std=0.02)
if m.bias is not None:
torch.nn.init.zeros_(m.bias)
elif isinstance(m, nn.Embedding):
torch.nn.init.normal_(m.weight, mean=0.0, std=0.02)
if m.padding_idx is not None:
with torch.no_grad():
m.weight[m.padding_idx].zero_()
def _get_causal_mask(self, T: int, device: torch.device) -> torch.Tensor:
mask = torch.tril(torch.ones(T, T, device=device, dtype=torch.bool))
return mask.unsqueeze(0).unsqueeze(0)
def _run_blocks(self, x: torch.Tensor) -> torch.Tensor:
attn_mask = self._get_causal_mask(x.size(1), x.device)
for blk in self.blocks:
x = blk(x, attn_mask=attn_mask)
return x
def forward(self, images: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
# images: (B,1,H,W), targets: (B, L_t) token ids (0-9,PAD,EOS)
B = images.size(0)
img_tokens = self.patch_embed(images) # (B, Np, d)
Np = img_tokens.size(1)
tgt = targets # (B, Lt)
Lt = tgt.size(1)
tok_t = self.tok_embed(tgt) # (B, Lt, d)
x = torch.cat([img_tokens, tok_t], dim=1) # (B, Np+Lt, d)
T_total = x.size(1)
pos = self.pos_embed[:, :T_total, :]
x = self.drop(x + pos)
cache = self.attn_mask_cache
if cache is None or cache.size(-1) != T_total or cache.device != x.device:
cache = self._get_causal_mask(T_total, x.device)
self.attn_mask_cache = cache
attn_mask = cache
for blk in self.blocks:
x = blk(x, attn_mask=attn_mask)
x = self.ln_f(x)
logits = self.lm_head(x) # (B, T_total, V)
logits_seq = logits[:, Np - 1 : T_total - 1, :].contiguous()
return logits_seq
@torch.no_grad()
def generate(
self,
images: torch.Tensor,
max_len: int = 6,
temperature: float = 1.0,
greedy: bool = False,
) -> torch.Tensor:
self.eval()
B = images.size(0)
device = images.device
img_tokens = self.patch_embed(images)
Np = img_tokens.size(1)
prefix = img_tokens + self.pos_embed[:, :Np, :]
token_pos = self.pos_embed[:, Np : Np + max_len, :]
out_tokens = []
cur = self._run_blocks(prefix)
for _ in range(max_len):
lg = self.lm_head(self.ln_f(cur[:, -1:, :]))[:, -1, :]
if greedy:
next_id = lg.argmax(dim=-1, keepdim=True)
else:
probs = F.softmax(lg / max(1e-6, temperature), dim=-1)
next_id = torch.multinomial(probs, num_samples=1)
out_tokens.append(next_id)
emb = self.tok_embed(torch.cat(out_tokens, dim=1)) + token_pos[:, : len(out_tokens), :]
cur = self._run_blocks(torch.cat([prefix, emb], dim=1))
if (next_id == self.config.eos_id).all():
break
seq = torch.cat(out_tokens, dim=1) if out_tokens else torch.empty(B, 0, device=device, dtype=torch.long)
return seq
def count_params(model: nn.Module) -> int:
return sum(p.numel() for p in model.parameters() if p.requires_grad)
|