Spaces:
Sleeping
Sleeping
Upload 3 files
Browse files- app.py +92 -0
- model_smol2.py +260 -0
- requirements.txt +4 -0
app.py
ADDED
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import gradio as gr
|
3 |
+
from transformers import AutoTokenizer
|
4 |
+
from model_smol2 import LlamaForCausalLM, config_model
|
5 |
+
|
6 |
+
# Instantiate the model
|
7 |
+
model = LlamaForCausalLM(config_model)
|
8 |
+
|
9 |
+
# Load the checkpoint
|
10 |
+
checkpoint_path = "/Users/shriti/Downloads/Assign13_ERAV3/deply/final_checkpoint.pt"
|
11 |
+
checkpoint = torch.load(checkpoint_path, map_location="cpu")
|
12 |
+
model.load_state_dict(checkpoint['model_state_dict'])
|
13 |
+
model.eval()
|
14 |
+
|
15 |
+
# Load tokenizer (replace with the appropriate tokenizer if you're using a custom one)
|
16 |
+
# Load the tokenizer
|
17 |
+
TOKENIZER_PATH = "HuggingFaceTB/cosmo2-tokenizer"
|
18 |
+
tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_PATH)
|
19 |
+
if tokenizer.pad_token is None:
|
20 |
+
tokenizer.pad_token = tokenizer.eos_token if tokenizer.eos_token else "[PAD]"
|
21 |
+
|
22 |
+
|
23 |
+
# Text generation function
|
24 |
+
def generate_text(
|
25 |
+
prompt, max_length=50, temperature=0.7, top_k=50, repetition_penalty=1.2, n_gram_block=2
|
26 |
+
):
|
27 |
+
input_ids = tokenizer.encode(prompt, return_tensors="pt")
|
28 |
+
generated_tokens = input_ids[0].tolist()
|
29 |
+
|
30 |
+
with torch.no_grad():
|
31 |
+
for _ in range(max_length):
|
32 |
+
outputs = model(input_ids) # model outputs
|
33 |
+
|
34 |
+
# Check if the output is a dictionary with logits
|
35 |
+
if isinstance(outputs, dict) and 'logits' in outputs:
|
36 |
+
logits = outputs['logits'][:, -1, :]
|
37 |
+
else:
|
38 |
+
# If not, treat the output as a plain tensor
|
39 |
+
logits = outputs[:, -1, :]
|
40 |
+
|
41 |
+
# Repetition penalty
|
42 |
+
for token_id in set(generated_tokens):
|
43 |
+
logits[:, token_id] /= repetition_penalty
|
44 |
+
|
45 |
+
# n-gram blocking
|
46 |
+
if len(generated_tokens) >= n_gram_block:
|
47 |
+
n_gram = tuple(generated_tokens[-n_gram_block:])
|
48 |
+
for token_id in set(generated_tokens):
|
49 |
+
if generated_tokens[-n_gram_block:] == list(n_gram):
|
50 |
+
logits[:, token_id] -= 1e9
|
51 |
+
|
52 |
+
logits /= temperature
|
53 |
+
top_k_logits, top_k_indices = torch.topk(logits, top_k, dim=-1)
|
54 |
+
probs = torch.softmax(top_k_logits, dim=-1)
|
55 |
+
|
56 |
+
next_token_idx = torch.multinomial(probs, num_samples=1)
|
57 |
+
next_token = top_k_indices[0, next_token_idx[0]]
|
58 |
+
|
59 |
+
generated_tokens.append(next_token.item())
|
60 |
+
input_ids = torch.cat([input_ids, next_token.unsqueeze(0)], dim=1)
|
61 |
+
|
62 |
+
if next_token.item() == tokenizer.eos_token_id:
|
63 |
+
break
|
64 |
+
|
65 |
+
return tokenizer.decode(generated_tokens, skip_special_tokens=True)
|
66 |
+
|
67 |
+
|
68 |
+
# Gradio UI
|
69 |
+
def generate_response(prompt, max_length, temperature, top_k, repetition_penalty, n_gram_block):
|
70 |
+
return generate_text(prompt, max_length, temperature, top_k, repetition_penalty, n_gram_block)
|
71 |
+
|
72 |
+
with gr.Blocks() as demo:
|
73 |
+
gr.Markdown("# Smol2 Text Generator")
|
74 |
+
with gr.Row():
|
75 |
+
with gr.Column():
|
76 |
+
prompt_input = gr.Textbox(label="Input Prompt", placeholder="Enter your text prompt here...")
|
77 |
+
max_length = gr.Slider(label="Max Length", minimum=10, maximum=200, value=50)
|
78 |
+
temperature = gr.Slider(label="Temperature", minimum=0.1, maximum=1.5, value=0.7, step=0.1)
|
79 |
+
top_k = gr.Slider(label="Top K", minimum=10, maximum=100, value=50, step=1)
|
80 |
+
repetition_penalty = gr.Slider(label="Repetition Penalty", minimum=1.0, maximum=2.0, value=1.2, step=0.1)
|
81 |
+
n_gram_block = gr.Slider(label="N-Gram Blocking", minimum=1, maximum=5, value=2, step=1)
|
82 |
+
generate_button = gr.Button("Generate Text")
|
83 |
+
with gr.Column():
|
84 |
+
output_text = gr.Textbox(label="Generated Text", lines=10)
|
85 |
+
|
86 |
+
generate_button.click(
|
87 |
+
generate_response,
|
88 |
+
inputs=[prompt_input, max_length, temperature, top_k, repetition_penalty, n_gram_block],
|
89 |
+
outputs=[output_text],
|
90 |
+
)
|
91 |
+
|
92 |
+
demo.launch()
|
model_smol2.py
ADDED
@@ -0,0 +1,260 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 )
|
255 |
+
input_ids = torch.randint(0, config_model['vocab_size'], (10, 2)) # (seq_len, batch_size)
|
256 |
+
logits = causal_lm_model(input_ids)
|
257 |
+
print(f"Logits shape: {logits.shape}")
|
258 |
+
'''
|
259 |
+
|
260 |
+
|
requirements.txt
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
transformers
|
2 |
+
torch
|
3 |
+
datasets
|
4 |
+
gradio
|