teszenofficial commited on
Commit
97546db
Β·
verified Β·
1 Parent(s): 9b1dc31

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -187
app.py DELETED
@@ -1,187 +0,0 @@
1
- import gradio as gr
2
- import pickle
3
- import torch
4
- from huggingface_hub import hf_hub_download
5
-
6
- # === CLASES DEL MODELO ===
7
-
8
- class Head(torch.nn.Module):
9
- def __init__(self, head_size, n_embd, block_size):
10
- super().__init__()
11
- self.key = torch.nn.Linear(n_embd, head_size, bias=False)
12
- self.query = torch.nn.Linear(n_embd, head_size, bias=False)
13
- self.value = torch.nn.Linear(n_embd, head_size, bias=False)
14
- self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size)))
15
-
16
- def forward(self, x):
17
- B, T, C = x.shape
18
- k = self.key(x)
19
- q = self.query(x)
20
- wei = q @ k.transpose(-2, -1) * k.shape[-1]**-0.5
21
- wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf'))
22
- wei = torch.softmax(wei, dim=-1)
23
- v = self.value(x)
24
- out = wei @ v
25
- return out
26
-
27
- class MultiHeadAttention(torch.nn.Module):
28
- def __init__(self, num_heads, head_size, n_embd, block_size):
29
- super().__init__()
30
- self.heads = torch.nn.ModuleList([Head(head_size, n_embd, block_size) for _ in range(num_heads)])
31
- self.proj = torch.nn.Linear(n_embd, n_embd)
32
- self.dropout = torch.nn.Dropout(0.1)
33
-
34
- def forward(self, x):
35
- out = torch.cat([h(x) for h in self.heads], dim=-1)
36
- out = self.dropout(self.proj(out))
37
- return out
38
-
39
- class FeedFoward(torch.nn.Module):
40
- def __init__(self, n_embd):
41
- super().__init__()
42
- self.net = torch.nn.Sequential(
43
- torch.nn.Linear(n_embd, 4 * n_embd),
44
- torch.nn.GELU(),
45
- torch.nn.Dropout(0.1),
46
- torch.nn.Linear(4 * n_embd, n_embd),
47
- torch.nn.Dropout(0.1),
48
- )
49
-
50
- def forward(self, x):
51
- return self.net(x)
52
-
53
- class Block(torch.nn.Module):
54
- def __init__(self, n_embd, n_head, block_size):
55
- super().__init__()
56
- head_size = n_embd // n_head
57
- self.sa = MultiHeadAttention(n_head, head_size, n_embd, block_size)
58
- self.ffwd = FeedFoward(n_embd)
59
- self.ln1 = torch.nn.LayerNorm(n_embd)
60
- self.ln2 = torch.nn.LayerNorm(n_embd)
61
-
62
- def forward(self, x):
63
- x = x + self.sa(self.ln1(x))
64
- x = x + self.ffwd(self.ln2(x))
65
- return x
66
-
67
- class MTP(torch.nn.Module):
68
- def __init__(self, vocab_size, n_embd, n_head, n_layer, block_size):
69
- super().__init__()
70
- self.token_embedding_table = torch.nn.Embedding(vocab_size, n_embd)
71
- self.position_embedding_table = torch.nn.Embedding(block_size, n_embd)
72
- self.blocks = torch.nn.Sequential(*[Block(n_embd, n_head, block_size) for _ in range(n_layer)])
73
- self.ln_f = torch.nn.LayerNorm(n_embd)
74
- self.lm_head = torch.nn.Linear(n_embd, vocab_size)
75
- self.dropout = torch.nn.Dropout(0.1)
76
-
77
- def forward(self, idx, targets=None):
78
- B, T = idx.shape
79
- tok_emb = self.token_embedding_table(idx)
80
- pos_emb = self.position_embedding_table(torch.arange(T, device=idx.device))
81
- x = self.dropout(tok_emb + pos_emb)
82
- x = self.blocks(x)
83
- x = self.ln_f(x)
84
- logits = self.lm_head(x)
85
- if targets is not None:
86
- loss = torch.nn.functional.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
87
- return logits, loss
88
- else:
89
- return logits
90
-
91
- # === FUNCIONES DE AYUDA ===
92
-
93
- def encode(s, stoi):
94
- return [stoi[c] for c in s if c in stoi]
95
-
96
- def decode(l, itos):
97
- return ''.join([itos[i] for i in l])
98
-
99
- # === GENERACIΓ“N DE TEXTO ===
100
-
101
- def generate_text(model, start_str, stoi, itos, block_size, max_new_tokens=500, temperature=1.0, top_p=0.9):
102
- encoded = encode(start_str, stoi)
103
- if not encoded:
104
- return "No se pudo procesar la entrada: caracteres desconocidos."
105
- idx = torch.tensor(encoded, dtype=torch.long).unsqueeze(0)
106
- model.eval()
107
- with torch.no_grad():
108
- generated = idx
109
- for _ in range(max_new_tokens):
110
- idx_cond = generated[:, -block_size:]
111
- logits = model(idx_cond)
112
- logits = logits[:, -1, :] / temperature
113
- probs = torch.softmax(logits, dim=-1)
114
-
115
- # NΓΊcleo de muestreo (top_p)
116
- sorted_probs, sorted_indices = torch.sort(probs, descending=True)
117
- cumulative_probs = torch.cumsum(sorted_probs, dim=-1)
118
- sorted_indices_to_remove = cumulative_probs > top_p
119
- sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
120
- sorted_indices_to_remove[..., 0] = 0
121
- indices_to_remove = sorted_indices[sorted_indices_to_remove]
122
- probs.scatter_(1, indices_to_remove, 0)
123
- probs = probs / probs.sum()
124
-
125
- idx_next = torch.multinomial(probs, num_samples=1)
126
- generated = torch.cat((generated, idx_next), dim=1)
127
- return decode(generated[0].tolist(), itos)
128
-
129
- # === CARGAR MODELO DESDE HUGGING FACE ===
130
-
131
- def load_model_from_hub(repo_id, filename):
132
- local_path = hf_hub_download(repo_id=repo_id, filename=filename)
133
- with open(local_path, 'rb') as f:
134
- data = pickle.load(f)
135
-
136
- model_state = data['model_state_dict']
137
- stoi = data['stoi']
138
- itos = data['itos']
139
- vocab_size = data['vocab_size']
140
- block_size = data['block_size']
141
-
142
- # Recrear el modelo con los mismos parΓ‘metros
143
- model = MTP(vocab_size, n_embd=256, n_head=8, n_layer=6, block_size=block_size)
144
- model.load_state_dict(model_state)
145
- model.eval()
146
-
147
- return model, stoi, itos, block_size
148
-
149
- # === CARGAR EL MODELO ===
150
-
151
- model, stoi, itos, block_size = load_model_from_hub("teszenofficial/mtptz", "MTP.pkl")
152
-
153
- def respond(
154
- message,
155
- history: list[dict[str, str]],
156
- system_message,
157
- max_tokens,
158
- temperature,
159
- top_p,
160
- ):
161
- try:
162
- response = generate_text(model, message, stoi, itos, block_size, max_new_tokens=max_tokens, temperature=temperature, top_p=top_p)
163
- response = response[:5000]
164
- yield response
165
- except Exception as e:
166
- yield f"Error: {str(e)}"
167
-
168
- # === INTERFAZ DE CHAT ===
169
-
170
- chatbot = gr.ChatInterface(
171
- respond,
172
- type="messages",
173
- additional_inputs=[
174
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
175
- gr.Slider(minimum=1, maximum=5000, value=500, step=10, label="Max new tokens"),
176
- gr.Slider(minimum=0.1, maximum=2.0, value=1.2, step=0.1, label="Temperature"),
177
- gr.Slider(minimum=0.1, maximum=1.0, value=0.9, step=0.05, label="Top-p (nucleus sampling)"),
178
- ],
179
- )
180
-
181
- with gr.Blocks() as demo:
182
- with gr.Sidebar():
183
- gr.Markdown("## MTP Chat v3")
184
- chatbot.render()
185
-
186
- if __name__ == "__main__":
187
- demo.launch()