anjikum commited on
Commit
2c7c575
·
verified ·
1 Parent(s): 90ff75a

Upload 3 files

Browse files
Files changed (1) hide show
  1. app.py +177 -11
app.py CHANGED
@@ -1,28 +1,199 @@
1
  import torch
 
 
 
 
2
  from transformers import AutoTokenizer
3
- from model import SmolLM2, SmolLM2Config
4
  import gradio as gr
5
  import zipfile
6
  import io
7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  # Initialize model and tokenizer
9
  device = 'cuda' if torch.cuda.is_available() else 'cpu'
10
  tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/cosmo2-tokenizer")
11
  model = SmolLM2(SmolLM2Config())
12
 
13
  # Load trained weights
14
-
15
- checkpoint = torch.load('checkpoint_step_5000.pt', map_location=device) # Adjust path as needed
16
  model.load_state_dict(checkpoint['model_state_dict'])
17
  model.to(device)
18
  model.eval()
19
 
20
  def generate_text(prompt, max_length=100, temperature=0.7, top_k=50):
21
  """Generate text from a prompt"""
22
- # Tokenize the prompt
23
  input_ids = tokenizer.encode(prompt, return_tensors='pt').to(device)
24
 
25
- # Generate
26
  with torch.no_grad():
27
  output_ids = model.generate(
28
  input_ids,
@@ -31,9 +202,7 @@ def generate_text(prompt, max_length=100, temperature=0.7, top_k=50):
31
  top_k=top_k
32
  )
33
 
34
- # Decode and return the generated text
35
- generated_text = tokenizer.decode(output_ids[0], skip_special_tokens=True)
36
- return generated_text
37
 
38
  # Gradio interface
39
  def gradio_interface(prompt, max_length, temperature, top_k):
@@ -52,8 +221,5 @@ iface = gr.Interface(
52
  description="Generate text using the SmolLM2 model"
53
  )
54
 
55
- # For Hugging Face deployment
56
- app = gr.mount_gradio_app(app, iface)
57
-
58
  if __name__ == "__main__":
59
  iface.launch()
 
1
  import torch
2
+ import torch.nn as nn
3
+ from torch.nn import functional as F
4
+ import math
5
+ from dataclasses import dataclass
6
  from transformers import AutoTokenizer
 
7
  import gradio as gr
8
  import zipfile
9
  import io
10
 
11
+ # Copy all model classes here
12
+ class LlamaRMSNorm(nn.Module):
13
+ def __init__(self, hidden_size, eps=1e-6):
14
+ super().__init__()
15
+ self.weight = nn.Parameter(torch.ones(hidden_size))
16
+ self.eps = eps
17
+
18
+ def forward(self, x):
19
+ rms = torch.sqrt(torch.mean(x * x, dim=-1, keepdim=True) + self.eps)
20
+ x_norm = x / rms
21
+ return self.weight * x_norm
22
+
23
+ class LlamaRotaryEmbedding(nn.Module):
24
+ def __init__(self, dim, max_position_embeddings=2048, base=10000):
25
+ super().__init__()
26
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
27
+ self.register_buffer("inv_freq", inv_freq)
28
+ self.max_position_embeddings = max_position_embeddings
29
+ self.dim = dim
30
+
31
+ def forward(self, x, seq_len):
32
+ t = torch.arange(seq_len, device=x.device).type_as(self.inv_freq)
33
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
34
+ emb = torch.cat((freqs, freqs), dim=-1)
35
+ return emb
36
+
37
+ def rotate_half(x):
38
+ x1, x2 = x[..., :x.shape[-1]//2], x[..., x.shape[-1]//2:]
39
+ return torch.cat((-x2, x1), dim=-1)
40
+
41
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
42
+ cos = cos.unsqueeze(0).unsqueeze(0)
43
+ sin = sin.unsqueeze(0).unsqueeze(0)
44
+ cos = cos.expand(q.shape[0], q.shape[1], -1, -1)
45
+ sin = sin.expand(k.shape[0], k.shape[1], -1, -1)
46
+ q_embed = (q * cos) + (rotate_half(q) * sin)
47
+ k_embed = (k * cos) + (rotate_half(k) * sin)
48
+ return q_embed, k_embed
49
+
50
+ class LlamaSdpaAttention(nn.Module):
51
+ def __init__(self, config):
52
+ super().__init__()
53
+ self.hidden_size = config.n_embd
54
+ self.num_heads = config.n_head
55
+ self.head_dim = config.n_embd // config.n_head
56
+ self.num_key_value_heads = config.n_head // 3
57
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
58
+
59
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
60
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
61
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
62
+ self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
63
+ self.rotary_emb = LlamaRotaryEmbedding(self.head_dim)
64
+
65
+ def forward(self, x, attention_mask=None):
66
+ B, T, C = x.size()
67
+ q = self.q_proj(x).view(B, T, self.num_heads, self.head_dim)
68
+ k = self.k_proj(x).view(B, T, self.num_key_value_heads, self.head_dim)
69
+ v = self.v_proj(x).view(B, T, self.num_key_value_heads, self.head_dim)
70
+
71
+ k = k.repeat_interleave(self.num_key_value_groups, dim=2)
72
+ v = v.repeat_interleave(self.num_key_value_groups, dim=2)
73
+
74
+ q = q.transpose(1, 2)
75
+ k = k.transpose(1, 2)
76
+ v = v.transpose(1, 2)
77
+
78
+ rotary_emb = self.rotary_emb(x, T)
79
+ cos, sin = rotary_emb.cos(), rotary_emb.sin()
80
+ q, k = apply_rotary_pos_emb(q, k, cos, sin, None)
81
+
82
+ out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
83
+ out = out.transpose(1, 2).contiguous().view(B, T, C)
84
+ return self.o_proj(out)
85
+
86
+ class LlamaMLP(nn.Module):
87
+ def __init__(self, config):
88
+ super().__init__()
89
+ self.gate_proj = nn.Linear(config.n_embd, config.intermediate_size, bias=False)
90
+ self.up_proj = nn.Linear(config.n_embd, config.intermediate_size, bias=False)
91
+ self.down_proj = nn.Linear(config.intermediate_size, config.n_embd, bias=False)
92
+ self.act_fn = nn.SiLU()
93
+
94
+ def forward(self, x):
95
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
96
+
97
+ class LlamaDecoderLayer(nn.Module):
98
+ def __init__(self, config):
99
+ super().__init__()
100
+ self.input_layernorm = LlamaRMSNorm(config.n_embd)
101
+ self.self_attn = LlamaSdpaAttention(config)
102
+ self.post_attention_layernorm = LlamaRMSNorm(config.n_embd)
103
+ self.mlp = LlamaMLP(config)
104
+
105
+ def forward(self, x):
106
+ residual = x
107
+ x = self.input_layernorm(x)
108
+ x = self.self_attn(x)
109
+ x = residual + x
110
+
111
+ residual = x
112
+ x = self.post_attention_layernorm(x)
113
+ x = self.mlp(x)
114
+ x = residual + x
115
+ return x
116
+
117
+ @dataclass
118
+ class SmolLM2Config:
119
+ block_size: int = 2048
120
+ vocab_size: int = 49152
121
+ n_layer: int = 30
122
+ n_head: int = 9
123
+ n_embd: int = 576
124
+ intermediate_size: int = 1536
125
+ num_key_value_heads: int = 3
126
+ rms_norm_eps: float = 1e-5
127
+ rope_theta: float = 10000.0
128
+ initializer_range: float = 0.041666666666666664
129
+ use_cache: bool = True
130
+
131
+ class SmolLM2(nn.Module):
132
+ def __init__(self, config):
133
+ super().__init__()
134
+ self.config = config
135
+
136
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.n_embd)
137
+ self.layers = nn.ModuleList([LlamaDecoderLayer(config) for _ in range(config.n_layer)])
138
+ self.norm = LlamaRMSNorm(config.n_embd, eps=config.rms_norm_eps)
139
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
140
+ self.embed_tokens.weight = self.lm_head.weight
141
+ self.apply(self._init_weights)
142
+
143
+ def _init_weights(self, module):
144
+ if isinstance(module, nn.Linear):
145
+ torch.nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
146
+ if module.bias is not None:
147
+ torch.nn.init.zeros_(module.bias)
148
+ elif isinstance(module, nn.Embedding):
149
+ torch.nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
150
+
151
+ def forward(self, idx, targets=None):
152
+ B, T = idx.size()
153
+ x = self.embed_tokens(idx)
154
+
155
+ for layer in self.layers:
156
+ x = layer(x)
157
+
158
+ x = self.norm(x)
159
+ logits = self.lm_head(x)
160
+
161
+ loss = None
162
+ if targets is not None:
163
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
164
+
165
+ return logits, loss
166
+
167
+ def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None):
168
+ for _ in range(max_new_tokens):
169
+ idx_cond = idx[:, -self.config.block_size:]
170
+ logits, _ = self(idx_cond)
171
+ logits = logits[:, -1, :] / temperature
172
+
173
+ if top_k is not None:
174
+ v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
175
+ logits[logits < v[:, [-1]]] = float('-inf')
176
+
177
+ probs = F.softmax(logits, dim=-1)
178
+ idx_next = torch.multinomial(probs, num_samples=1)
179
+ idx = torch.cat((idx, idx_next), dim=1)
180
+ return idx
181
+
182
  # Initialize model and tokenizer
183
  device = 'cuda' if torch.cuda.is_available() else 'cpu'
184
  tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/cosmo2-tokenizer")
185
  model = SmolLM2(SmolLM2Config())
186
 
187
  # Load trained weights
188
+ checkpoint = torch.load('checkpoint_step_5000.pt', map_location=device)
 
189
  model.load_state_dict(checkpoint['model_state_dict'])
190
  model.to(device)
191
  model.eval()
192
 
193
  def generate_text(prompt, max_length=100, temperature=0.7, top_k=50):
194
  """Generate text from a prompt"""
 
195
  input_ids = tokenizer.encode(prompt, return_tensors='pt').to(device)
196
 
 
197
  with torch.no_grad():
198
  output_ids = model.generate(
199
  input_ids,
 
202
  top_k=top_k
203
  )
204
 
205
+ return tokenizer.decode(output_ids[0], skip_special_tokens=True)
 
 
206
 
207
  # Gradio interface
208
  def gradio_interface(prompt, max_length, temperature, top_k):
 
221
  description="Generate text using the SmolLM2 model"
222
  )
223
 
 
 
 
224
  if __name__ == "__main__":
225
  iface.launch()