MouseBill commited on
Commit
e85601b
·
verified ·
1 Parent(s): 33f0973

Upload model.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. model.py +191 -74
model.py CHANGED
@@ -1,121 +1,238 @@
1
  """
2
- CSE 251B — Example model.py
3
-
4
- This is a minimal example showing the required interface for your submission.
5
- Your model.py must contain a load_model() function with this signature.
6
-
7
- This example implements a tiny 2-layer Transformer (~1M params) for demonstration.
8
- It will have terrible perplexity — it's just to show the required structure.
 
 
 
9
  """
10
 
 
11
  import torch
12
  import torch.nn as nn
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
 
 
 
 
14
 
15
- # --- Your model definition (replace with your architecture) ---
16
 
17
- class TinyGPT(nn.Module):
18
- """A minimal GPT for demonstration purposes."""
19
 
20
- def __init__(self, vocab_size=50257, n_embd=128, n_head=4, n_layer=6, block_size=1024):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  super().__init__()
22
  self.block_size = block_size
 
23
  self.token_emb = nn.Embedding(vocab_size, n_embd)
24
- self.pos_emb = nn.Embedding(block_size, n_embd)
25
- self.blocks = nn.ModuleList([
26
- nn.TransformerEncoderLayer(
27
- d_model=n_embd, nhead=n_head,
28
- dim_feedforward=4 * n_embd, dropout=0.1,
29
- activation="gelu", batch_first=True,
30
- )
31
- for _ in range(n_layer)
32
- ])
33
- self.ln_f = nn.LayerNorm(n_embd)
34
- self.lm_head = nn.Linear(n_embd, vocab_size, bias=False)
35
 
36
- def forward(self, input_ids):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  """
38
  Args:
39
- input_ids: LongTensor of shape (batch_size, seq_len)
40
  Returns:
41
- logits: FloatTensor of shape (batch_size, seq_len, 50257)
42
  """
43
  B, T = input_ids.shape
44
- tok_emb = self.token_emb(input_ids)
45
- pos_emb = self.pos_emb(torch.arange(T, device=input_ids.device))
46
- x = tok_emb + pos_emb
47
 
48
- # Causal mask
49
- mask = torch.triu(torch.ones(T, T, device=input_ids.device), diagonal=1).bool()
 
 
50
 
51
  for block in self.blocks:
52
- x = block(x, src_mask=mask, is_causal=True)
53
 
54
- x = self.ln_f(x)
55
- logits = self.lm_head(x)
56
- return logits
57
 
58
 
59
- # --- Required: load_model function ---
60
 
61
  def load_model(checkpoint_path: str, device: str = "cuda") -> torch.nn.Module:
62
  """
63
- Load your trained model from a checkpoint.
64
-
65
- This function is called by evaluate.py. It must return a model where:
66
- model(input_ids) -> logits
67
- - input_ids: LongTensor of shape (batch, seq_len)
68
- - logits: FloatTensor of shape (batch, seq_len, 50257)
69
-
70
- Args:
71
- checkpoint_path: Path to your checkpoint.pt file
72
- device: Device to load onto ("cuda" or "cpu")
73
 
74
- Returns:
75
- model: nn.Module in eval mode
 
76
  """
77
- # Load checkpoint
78
  checkpoint = torch.load(checkpoint_path, map_location=device, weights_only=True)
79
 
80
- # Supports two formats:
81
- # 1) raw state_dict
82
- # 2) {"model_state_dict": ..., "config": {...}}
83
  if isinstance(checkpoint, dict) and "model_state_dict" in checkpoint:
84
  state_dict = checkpoint["model_state_dict"]
85
  config = checkpoint.get("config", {})
86
- model = TinyGPT(**config)
87
  else:
88
  state_dict = checkpoint
89
- model = TinyGPT()
90
 
91
- unwanted_prefix = '_orig_mod.'
92
- for k, v in list(state_dict.items()):
 
93
  if k.startswith(unwanted_prefix):
94
  state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k)
95
-
96
- model.load_state_dict(state_dict)
97
 
 
98
  model.to(device)
99
  model.eval()
100
  return model
101
 
102
 
103
- # --- Optional: quick sanity check ---
104
 
105
  if __name__ == "__main__":
106
- print("Creating example model...")
107
- model = TinyGPT()
108
- n_params = sum(p.numel() for p in model.parameters())
109
- print(f"Parameters: {n_params:,}")
110
-
111
- # Test forward pass
112
- dummy_input = torch.randint(0, 50257, (2, 1024))
113
- logits = model(dummy_input)
114
- print(f"Input shape: {dummy_input.shape}")
115
- print(f"Output shape: {logits.shape}")
116
- assert logits.shape == (2, 1024, 50257), "Output shape mismatch!"
117
- print("Interface check passed.")
118
-
119
- # Save example checkpoint
120
- torch.save(model.state_dict(), "checkpoint.pt")
121
- print("Saved example checkpoint.pt")
 
1
  """
2
+ DeepGPT — 竞争性 GPT 架构,约 98.8M 参数(满足 ≤100M 要求)
3
+
4
+ 相比 gpt2-opt 的核心改进:
5
+ 1. head_dim: 12 → 64(Flash Attention 标准尺寸,注意力质量显著提升)
6
+ 2. GELU MLP → SwiGLU(门控机制,语言建模更优)
7
+ 3. LayerNorm → RMSNorm(无均值偏移,计算更高效)
8
+ 4. n_embd: 384 → 768(更大表示容量,embedding 质量更高)
9
+ 5. dropout: 0.1 → 0.0(大数据预训练标准做法)
10
+ 6. RoPE theta: 10000 → 500000(更好的长序列外推能力)
11
+ 7. 残差投影缩放初始化(深网络训练更稳定)
12
  """
13
 
14
+ import math
15
  import torch
16
  import torch.nn as nn
17
+ import torch.nn.functional as F
18
+
19
+
20
+ def precompute_freqs(head_dim: int, seq_len: int, theta: float = 500000.0):
21
+ """预计算 RoPE 旋转频率,使用 LLaMA-3 风格的大 theta 以支持长序列外推。"""
22
+ inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2, dtype=torch.float32) / head_dim))
23
+ t = torch.arange(seq_len, dtype=torch.float32)
24
+ freqs = torch.outer(t, inv_freq) # (seq_len, head_dim//2)
25
+ cos = torch.cat([freqs.cos(), freqs.cos()], dim=-1) # (seq_len, head_dim)
26
+ sin = torch.cat([freqs.sin(), freqs.sin()], dim=-1)
27
+ return cos, sin
28
+
29
+
30
+ def rotate_half(x: torch.Tensor) -> torch.Tensor:
31
+ x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]
32
+ return torch.cat((-x2, x1), dim=-1)
33
+
34
+
35
+ def apply_rope(q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor):
36
+ cos = cos.unsqueeze(0).unsqueeze(0) # (1, 1, T, head_dim)
37
+ sin = sin.unsqueeze(0).unsqueeze(0)
38
+ q = q * cos + rotate_half(q) * sin
39
+ k = k * cos + rotate_half(k) * sin
40
+ return q, k
41
+
42
+
43
+ class RMSNorm(nn.Module):
44
+ """RMS 层归一化:无均值偏移,比 LayerNorm 更快,效果相当。"""
45
+
46
+ def __init__(self, dim: int, eps: float = 1e-6):
47
+ super().__init__()
48
+ self.eps = eps
49
+ self.weight = nn.Parameter(torch.ones(dim))
50
 
51
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
52
+ # 在 float32 下计算防止低精度下溢
53
+ norm = x.float().pow(2).mean(-1, keepdim=True).add(self.eps).rsqrt()
54
+ return (x.float() * norm * self.weight).type_as(x)
55
 
 
56
 
57
+ class CausalSelfAttention(nn.Module):
58
+ """多头因果自注意力:head_dim=64,融合 QKV 投影,使用 RoPE + PyTorch FlashAttention。"""
59
 
60
+ def __init__(self, n_embd: int, n_head: int):
61
+ super().__init__()
62
+ assert n_embd % n_head == 0, f"n_embd={n_embd} 必须能被 n_head={n_head} 整除"
63
+ self.n_head = n_head
64
+ self.head_dim = n_embd // n_head
65
+
66
+ # 融合 Q/K/V 投影,减少 kernel 启动开销
67
+ self.c_attn = nn.Linear(n_embd, 3 * n_embd, bias=False)
68
+ self.c_proj = nn.Linear(n_embd, n_embd, bias=False)
69
+
70
+ def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
71
+ B, T, C = x.shape
72
+ # 分割 QKV:(B, T, 3*C) → (3, B, n_head, T, head_dim)
73
+ qkv = self.c_attn(x).view(B, T, 3, self.n_head, self.head_dim).permute(2, 0, 3, 1, 4)
74
+ q, k, v = qkv[0], qkv[1], qkv[2]
75
+
76
+ q, k = apply_rope(q, k, cos[:T], sin[:T])
77
+
78
+ # PyTorch 2.0+ 自动选用 FlashAttention 内核
79
+ y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
80
+ return self.c_proj(y.transpose(1, 2).contiguous().view(B, T, C))
81
+
82
+
83
+ class SwiGLU(nn.Module):
84
+ """SwiGLU 前馈网络:SiLU(xW_gate) ⊙ xW_up → down。
85
+
86
+ 门控机制让模型动态过滤中间特征,在多项 LM benchmark 上优于 GELU-MLP。
87
+ """
88
+
89
+ def __init__(self, n_embd: int, hidden_dim: int):
90
+ super().__init__()
91
+ self.gate_proj = nn.Linear(n_embd, hidden_dim, bias=False)
92
+ self.up_proj = nn.Linear(n_embd, hidden_dim, bias=False)
93
+ self.down_proj = nn.Linear(hidden_dim, n_embd, bias=False)
94
+
95
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
96
+ return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
97
+
98
+
99
+ class Block(nn.Module):
100
+ """Pre-norm Transformer block:RMSNorm → 注意力 + RMSNorm → SwiGLU,残差连接。"""
101
+
102
+ def __init__(self, n_embd: int, n_head: int, hidden_dim: int):
103
+ super().__init__()
104
+ self.norm1 = RMSNorm(n_embd)
105
+ self.attn = CausalSelfAttention(n_embd, n_head)
106
+ self.norm2 = RMSNorm(n_embd)
107
+ self.ffn = SwiGLU(n_embd, hidden_dim)
108
+
109
+ def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
110
+ x = x + self.attn(self.norm1(x), cos, sin)
111
+ x = x + self.ffn(self.norm2(x))
112
+ return x
113
+
114
+
115
+ class DeepGPT(nn.Module):
116
+ """
117
+ 竞争性 GPT 模型,约 98.8M 参数(满足 ≤100M 约束)。
118
+
119
+ 默认超参数:
120
+ n_embd=768, n_head=12 (head_dim=64), n_layer=12, hidden_dim=1152
121
+ """
122
+
123
+ # 声明 buffer 类型,方便 torch.compile 推断
124
+ cos: torch.Tensor
125
+ sin: torch.Tensor
126
+
127
+ def __init__(
128
+ self,
129
+ vocab_size: int = 50257,
130
+ n_embd: int = 768,
131
+ n_head: int = 12,
132
+ n_layer: int = 12,
133
+ block_size: int = 1024,
134
+ hidden_dim: int = 1152,
135
+ rope_theta: float = 500000.0,
136
+ ):
137
  super().__init__()
138
  self.block_size = block_size
139
+
140
  self.token_emb = nn.Embedding(vocab_size, n_embd)
 
 
 
 
 
 
 
 
 
 
 
141
 
142
+ head_dim = n_embd // n_head
143
+ cos, sin = precompute_freqs(head_dim, block_size, theta=rope_theta)
144
+ self.register_buffer("cos", cos, persistent=False)
145
+ self.register_buffer("sin", sin, persistent=False)
146
+
147
+ self.blocks = nn.ModuleList([Block(n_embd, n_head, hidden_dim) for _ in range(n_layer)])
148
+ self.norm_f = RMSNorm(n_embd)
149
+
150
+ self.lm_head = nn.Linear(n_embd, vocab_size, bias=False)
151
+ # 权重绑定:lm_head 与 token_emb 共享权重,节省参数并提升 token 表示一致性
152
+ self.lm_head.weight = self.token_emb.weight
153
+
154
+ self._init_weights(n_layer)
155
+
156
+ def _init_weights(self, n_layer: int):
157
+ """标准 GPT-2 权重初始化 + 残差投影缩放。"""
158
+ for module in self.modules():
159
+ if isinstance(module, nn.Linear):
160
+ nn.init.normal_(module.weight, mean=0.0, std=0.02)
161
+ elif isinstance(module, nn.Embedding):
162
+ nn.init.normal_(module.weight, mean=0.0, std=0.02)
163
+ # 残差流出口(c_proj/down_proj)按深度缩放,防止残差累积导致梯度爆炸
164
+ for name, p in self.named_parameters():
165
+ if name.endswith(("c_proj.weight", "down_proj.weight")):
166
+ nn.init.normal_(p, mean=0.0, std=0.02 / math.sqrt(2 * n_layer))
167
+
168
+ def forward(self, input_ids: torch.Tensor) -> torch.Tensor:
169
  """
170
  Args:
171
+ input_ids: LongTensor (B, T)
172
  Returns:
173
+ logits: FloatTensor (B, T, 50257)
174
  """
175
  B, T = input_ids.shape
176
+ assert T <= self.block_size, f"序列长度 {T} 超过 block_size {self.block_size}"
 
 
177
 
178
+ x = self.token_emb(input_ids)
179
+
180
+ cos = self.cos[:T]
181
+ sin = self.sin[:T]
182
 
183
  for block in self.blocks:
184
+ x = block(x, cos, sin)
185
 
186
+ x = self.norm_f(x)
187
+ return self.lm_head(x)
 
188
 
189
 
190
+ # --- 必须实现的接口 ---
191
 
192
  def load_model(checkpoint_path: str, device: str = "cuda") -> torch.nn.Module:
193
  """
194
+ 从 checkpoint 加载 DeepGPT 模型。
 
 
 
 
 
 
 
 
 
195
 
196
+ 支持两种格式:
197
+ 1) 纯 state_dict
198
+ 2) {"model_state_dict": ..., "config": {...}}
199
  """
 
200
  checkpoint = torch.load(checkpoint_path, map_location=device, weights_only=True)
201
 
 
 
 
202
  if isinstance(checkpoint, dict) and "model_state_dict" in checkpoint:
203
  state_dict = checkpoint["model_state_dict"]
204
  config = checkpoint.get("config", {})
205
+ model = DeepGPT(**config)
206
  else:
207
  state_dict = checkpoint
208
+ model = DeepGPT()
209
 
210
+ # 去除 torch.compile 添加的 '_orig_mod.' 前缀
211
+ unwanted_prefix = "_orig_mod."
212
+ for k in list(state_dict.keys()):
213
  if k.startswith(unwanted_prefix):
214
  state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k)
 
 
215
 
216
+ model.load_state_dict(state_dict)
217
  model.to(device)
218
  model.eval()
219
  return model
220
 
221
 
222
+ # --- 快速完整性检查 ---
223
 
224
  if __name__ == "__main__":
225
+ model = DeepGPT()
226
+
227
+ # 统计唯一参数(weight tying 下 lm_head.weight 不重复计)
228
+ unique_params = sum(p.numel() for p in set(model.parameters()))
229
+ all_params = sum(p.numel() for p in model.parameters())
230
+ print(f"唯一参数量: {unique_params:,} ({unique_params/1e6:.1f}M)")
231
+ print(f"参数量统计: {all_params:,} ({all_params/1e6:.1f}M) ← model.parameters() 统计")
232
+
233
+ dummy = torch.randint(0, 50257, (2, 1024))
234
+ logits = model(dummy)
235
+ print(f"输入 shape: {dummy.shape}")
236
+ print(f"输出 shape: {logits.shape}")
237
+ assert logits.shape == (2, 1024, 50257), "输出形状错误!"
238
+ print("接口检查通过。")