Spaces:
Sleeping
Sleeping
Delete model_smol2.py
Browse files- model_smol2.py +0 -260
model_smol2.py
DELETED
@@ -1,260 +0,0 @@
|
|
1 |
-
import torch
|
2 |
-
import torch.nn as nn
|
3 |
-
import torch.nn.functional as F
|
4 |
-
|
5 |
-
|
6 |
-
# Configuration as provided
|
7 |
-
config_model = {
|
8 |
-
"bos_token_id": 0,
|
9 |
-
"eos_token_id": 0,
|
10 |
-
"hidden_act": "silu",
|
11 |
-
"hidden_size": 576,
|
12 |
-
"initializer_range": 0.041666666666666664,
|
13 |
-
"intermediate_size": 1536,
|
14 |
-
"is_llama_config": True,
|
15 |
-
"max_position_embeddings": 2048,
|
16 |
-
"num_attention_heads": 9,
|
17 |
-
"num_hidden_layers": 30,
|
18 |
-
"num_key_value_heads": 3,
|
19 |
-
"pad_token_id": None,
|
20 |
-
"pretraining_tp": 1,
|
21 |
-
"rms_norm_eps": 1.0e-05,
|
22 |
-
"rope_interleaved": False,
|
23 |
-
"rope_scaling": None,
|
24 |
-
"rope_theta": 10000.0,
|
25 |
-
"tie_word_embeddings": True,
|
26 |
-
"use_cache": True,
|
27 |
-
"vocab_size": 49152
|
28 |
-
}
|
29 |
-
|
30 |
-
# 1. Rotary Embedding
|
31 |
-
class LlamaRotaryEmbedding(nn.Module):
|
32 |
-
def __init__(self, dim: int, theta: float = 10000.0):
|
33 |
-
super().__init__()
|
34 |
-
self.dim = dim
|
35 |
-
self.theta = theta
|
36 |
-
|
37 |
-
def forward(self, x):
|
38 |
-
batch_size, seq_len, _ = x.size()
|
39 |
-
device = x.device
|
40 |
-
|
41 |
-
# Create the position indices
|
42 |
-
position = torch.arange(seq_len, dtype=torch.float32, device=device).unsqueeze(1) # Shape: (seq_len, 1)
|
43 |
-
freqs = torch.pow(self.theta, -torch.arange(0, self.dim, 2, dtype=torch.float32, device=device) / self.dim) # Shape: (dim/2,)
|
44 |
-
|
45 |
-
# Reshape freqs for einsum: Shape (dim/2, 1) -> (dim/2, 1) broadcasting with position
|
46 |
-
freqs = freqs.unsqueeze(1) # Shape: (dim/2, 1)
|
47 |
-
|
48 |
-
# Calculate sinusoidal embeddings
|
49 |
-
sinusoidal_embeddings = torch.einsum('i,j->ij', position.squeeze(), freqs.squeeze()) # Shape: (seq_len, dim/2)
|
50 |
-
|
51 |
-
# Sinusoidal encoding
|
52 |
-
sin = sinusoidal_embeddings.sin().unsqueeze(0) # Shape: (1, seq_len, dim/2)
|
53 |
-
cos = sinusoidal_embeddings.cos().unsqueeze(0) # Shape: (1, seq_len, dim/2)
|
54 |
-
|
55 |
-
# Concatenate the sin and cos values to create the final embedding
|
56 |
-
rotary_embeddings = torch.cat([sin, cos], dim=-1).unsqueeze(0) # Shape: (1, seq_len, dim)
|
57 |
-
|
58 |
-
# Remove the extra leading dimension (1) to match input tensor shape
|
59 |
-
return rotary_embeddings.squeeze(0) # Shape: (seq_len, dim)
|
60 |
-
'''
|
61 |
-
# Testing LlamaRotaryEmbedding again with the modified code
|
62 |
-
rotary_emb = LlamaRotaryEmbedding(dim=576, theta=10000.0)
|
63 |
-
input_tensor = torch.randn(2, 10, 576) # (batch_size, seq_len, hidden_size)
|
64 |
-
rotary_output = rotary_emb(input_tensor)
|
65 |
-
print(f"Rotary embedding output shape: {rotary_output.shape}")
|
66 |
-
'''
|
67 |
-
|
68 |
-
|
69 |
-
# 2. Attention Layer
|
70 |
-
class LlamaAttention(nn.Module):
|
71 |
-
def __init__(self, config):
|
72 |
-
super().__init__()
|
73 |
-
self.q_proj = nn.Linear(config['hidden_size'], config['hidden_size'], bias=False)
|
74 |
-
self.k_proj = nn.Linear(config['hidden_size'], config['hidden_size'] // 3, bias=False)
|
75 |
-
self.v_proj = nn.Linear(config['hidden_size'], config['hidden_size'] // 3, bias=False)
|
76 |
-
self.o_proj = nn.Linear(config['hidden_size'] // 3, config['hidden_size'], bias=False) # Adjust output projection size
|
77 |
-
self.rope_emb = LlamaRotaryEmbedding(config['hidden_size'])
|
78 |
-
|
79 |
-
def forward(self, x):
|
80 |
-
batch_size, seq_len, _ = x.size() # Get the batch size and sequence length
|
81 |
-
q = self.q_proj(x) # Shape: (batch_size, seq_len, hidden_size)
|
82 |
-
k = self.k_proj(x) # Shape: (batch_size, seq_len, hidden_size // 3)
|
83 |
-
v = self.v_proj(x) # Shape: (batch_size, seq_len, hidden_size // 3)
|
84 |
-
|
85 |
-
# Apply rotary embeddings (positional encoding)
|
86 |
-
q, k = self.rope_emb(q), self.rope_emb(k)
|
87 |
-
|
88 |
-
# Calculate attention weights (scaled dot-product attention)
|
89 |
-
attn_weights = torch.matmul(q, k.transpose(-2, -1)) # Shape: (batch_size, seq_len, seq_len)
|
90 |
-
attn_probs = torch.nn.functional.softmax(attn_weights, dim=-1) # Shape: (batch_size, seq_len, seq_len)
|
91 |
-
|
92 |
-
# Apply attention to values
|
93 |
-
attn_output = torch.matmul(attn_probs, v) # Shape: (batch_size, seq_len, hidden_size // 3)
|
94 |
-
|
95 |
-
# Output projection (adjusted to match hidden_size)
|
96 |
-
out = self.o_proj(attn_output) # Shape: (batch_size, seq_len, hidden_size)
|
97 |
-
|
98 |
-
return out
|
99 |
-
'''
|
100 |
-
# Testing LlamaAttention again
|
101 |
-
attention_layer = LlamaAttention(config)
|
102 |
-
input_tensor = torch.randn(2, 10, 576) # (batch_size, seq_len, hidden_size)
|
103 |
-
attention_output = attention_layer(input_tensor)
|
104 |
-
print(f"Attention output shape: {attention_output.shape}")
|
105 |
-
'''
|
106 |
-
|
107 |
-
# 3. MLP Layer
|
108 |
-
class LlamaMLP(nn.Module):
|
109 |
-
def __init__(self, config):
|
110 |
-
super().__init__()
|
111 |
-
self.gate_proj = nn.Linear(config['hidden_size'], config['intermediate_size'], bias=False) # Hidden size to intermediate size
|
112 |
-
self.up_proj = nn.Linear(config['intermediate_size'], config['intermediate_size'], bias=False) # Intermediate size to intermediate size
|
113 |
-
self.down_proj = nn.Linear(config['intermediate_size'], config['hidden_size'], bias=False) # Intermediate size to hidden size
|
114 |
-
self.act_fn = torch.nn.SiLU() # Activation function
|
115 |
-
|
116 |
-
def forward(self, x):
|
117 |
-
batch_size, seq_len, _ = x.size()
|
118 |
-
|
119 |
-
# Flatten input to (batch_size * seq_len, hidden_size) for projection
|
120 |
-
x = x.view(batch_size * seq_len, -1) # Shape: (batch_size * seq_len, hidden_size)
|
121 |
-
|
122 |
-
# Apply gate projection
|
123 |
-
x = self.gate_proj(x) # Shape: (batch_size * seq_len, intermediate_size)
|
124 |
-
x = self.act_fn(x) # Apply activation
|
125 |
-
|
126 |
-
# Apply up projection
|
127 |
-
x = self.up_proj(x) # Shape: (batch_size * seq_len, intermediate_size)
|
128 |
-
|
129 |
-
# Apply down projection
|
130 |
-
x = self.down_proj(x) # Shape: (batch_size * seq_len, hidden_size)
|
131 |
-
|
132 |
-
# Reshape back to (batch_size, seq_len, hidden_size)
|
133 |
-
x = x.view(batch_size, seq_len, -1) # Shape: (batch_size, seq_len, hidden_size)
|
134 |
-
|
135 |
-
return x
|
136 |
-
'''
|
137 |
-
# Test the MLP again
|
138 |
-
mlp_layer = LlamaMLP(config)
|
139 |
-
input_tensor = torch.randn(2, 10, 576) # (batch_size, seq_len, hidden_size)
|
140 |
-
mlp_output = mlp_layer(input_tensor)
|
141 |
-
print(f"MLP output shape: {mlp_output.shape}")
|
142 |
-
'''
|
143 |
-
|
144 |
-
|
145 |
-
# 4. Decoder Layer
|
146 |
-
class LlamaDecoderLayer(nn.Module):
|
147 |
-
def __init__(self, config):
|
148 |
-
super().__init__()
|
149 |
-
self.self_attn = LlamaAttention(config)
|
150 |
-
self.mlp = LlamaMLP(config)
|
151 |
-
self.input_layernorm = nn.LayerNorm(config['hidden_size'], eps=config['rms_norm_eps'])
|
152 |
-
self.post_attention_layernorm = nn.LayerNorm(config['hidden_size'], eps=config['rms_norm_eps'])
|
153 |
-
|
154 |
-
def forward(self, x):
|
155 |
-
# Apply input normalization
|
156 |
-
x = self.input_layernorm(x)
|
157 |
-
|
158 |
-
# Attention
|
159 |
-
attn_output = self.self_attn(x)
|
160 |
-
x = x + attn_output # Residual connection
|
161 |
-
|
162 |
-
# Apply post-attention layer normalization
|
163 |
-
x = self.post_attention_layernorm(x)
|
164 |
-
|
165 |
-
# Apply MLP
|
166 |
-
mlp_output = self.mlp(x)
|
167 |
-
x = x + mlp_output # Residual connection
|
168 |
-
return x
|
169 |
-
'''
|
170 |
-
# Testing LlamaDecoderLayer
|
171 |
-
decoder_layer = LlamaDecoderLayer(config)
|
172 |
-
input_tensor = torch.randn(10, 2, 576) # (seq_len, batch_size, hidden_size)
|
173 |
-
decoder_output = decoder_layer(input_tensor)
|
174 |
-
print(f"Decoder layer output shape: {decoder_output.shape}")
|
175 |
-
|
176 |
-
# 5. Model
|
177 |
-
class LlamaModel(nn.Module):
|
178 |
-
def __init__(self, config):
|
179 |
-
super().__init__()
|
180 |
-
self.embed_tokens = nn.Embedding(config['vocab_size'], config['hidden_size'])
|
181 |
-
|
182 |
-
# Partially shared decoder layers
|
183 |
-
self.layers = nn.ModuleList([LlamaDecoderLayer(config) for _ in range(config['num_hidden_layers'])])
|
184 |
-
|
185 |
-
# Separate adapters for each layer (adds more parameters)
|
186 |
-
self.adapters = nn.ModuleList([
|
187 |
-
nn.Linear(config['hidden_size'], config['hidden_size'], bias=False)
|
188 |
-
for _ in range(config['num_hidden_layers'])
|
189 |
-
])
|
190 |
-
|
191 |
-
self.norm = nn.LayerNorm(config['hidden_size'], eps=config['rms_norm_eps'])
|
192 |
-
|
193 |
-
def forward(self, input_ids):
|
194 |
-
# Initial embedding lookup
|
195 |
-
x = self.embed_tokens(input_ids)
|
196 |
-
|
197 |
-
# Pass through transformer layers with unique adapters per layer
|
198 |
-
for i, layer in enumerate(self.layers):
|
199 |
-
x = layer(x) # Apply the i-th decoder layer
|
200 |
-
x = x + self.adapters[i](x) # Add per-layer adapter
|
201 |
-
|
202 |
-
# Apply the final layer normalization
|
203 |
-
x = self.norm(x)
|
204 |
-
return x
|
205 |
-
|
206 |
-
|
207 |
-
'''
|
208 |
-
class LlamaModel(nn.Module):
|
209 |
-
def __init__(self, config):
|
210 |
-
super().__init__()
|
211 |
-
self.embed_tokens = nn.Embedding(config['vocab_size'], config['hidden_size'])
|
212 |
-
self.layers = nn.ModuleList([LlamaDecoderLayer(config) for _ in range(config['num_hidden_layers'])])
|
213 |
-
self.norm = nn.LayerNorm(config['hidden_size'], eps=config['rms_norm_eps'])
|
214 |
-
self.rotary_emb = LlamaRotaryEmbedding(config['hidden_size'])
|
215 |
-
|
216 |
-
def forward(self, input_ids):
|
217 |
-
# Initial embedding lookup
|
218 |
-
x = self.embed_tokens(input_ids)
|
219 |
-
|
220 |
-
# Pass through the transformer layers
|
221 |
-
for layer in self.layers:
|
222 |
-
x = layer(x)
|
223 |
-
|
224 |
-
# Apply the final layer normalization
|
225 |
-
x = self.norm(x)
|
226 |
-
return x
|
227 |
-
'''
|
228 |
-
# Testing LlamaModel
|
229 |
-
model = LlamaModel(config)
|
230 |
-
input_ids = torch.randint(0, config['vocab_size'], (10, 2)) # (seq_len, batch_size)
|
231 |
-
model_output = model(input_ids)
|
232 |
-
print(f"Model output shape: {model_output.shape}")
|
233 |
-
'''
|
234 |
-
# 6. Causal Language Model (Final Model)
|
235 |
-
class LlamaForCausalLM(nn.Module):
|
236 |
-
def __init__(self, config):
|
237 |
-
super().__init__()
|
238 |
-
self.model = LlamaModel(config)
|
239 |
-
# Share weights between the embedding and output layers
|
240 |
-
#self.lm_head = self.model.embed_tokens
|
241 |
-
|
242 |
-
self.lm_head= nn.Linear(config['hidden_size'], config['vocab_size'], bias=False)
|
243 |
-
|
244 |
-
def forward(self, input_ids):
|
245 |
-
hidden_states = self.model(input_ids)
|
246 |
-
logits = self.lm_head(hidden_states)
|
247 |
-
return logits
|
248 |
-
|
249 |
-
# Testing LlamaForCausalLM
|
250 |
-
'''
|
251 |
-
causal_lm_model = LlamaForCausalLM(config_model)
|
252 |
-
print(causal_lm_model)
|
253 |
-
from torchinfo import summary
|
254 |
-
summary( causal_lm_model )
|
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