Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,21 +1,102 @@
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
# Инициализация модели
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
-
#
|
| 13 |
iface = gr.Interface(
|
| 14 |
fn=generate_text,
|
| 15 |
inputs=gr.Textbox(lines=2, placeholder="Введите начало текста..."),
|
| 16 |
outputs="text",
|
| 17 |
-
title="
|
| 18 |
-
description="Введите
|
| 19 |
)
|
| 20 |
|
| 21 |
# Запуск интерфейса
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
import gradio as gr
|
| 4 |
+
from torch.nn import TransformerDecoder, TransformerDecoderLayer
|
| 5 |
+
from torchtext.data.utils import get_tokenizer
|
| 6 |
+
from torchtext.vocab import build_vocab_from_iterator
|
| 7 |
+
import math
|
| 8 |
+
|
| 9 |
+
# Параметры модели
|
| 10 |
+
VOCAB_SIZE = 10000 # Размер словаря
|
| 11 |
+
EMBED_SIZE = 256 # Размер эмбеддингов
|
| 12 |
+
NUM_HEADS = 8 # Количество голов в трансформере
|
| 13 |
+
NUM_LAYERS = 6 # Количество слоев
|
| 14 |
+
FFN_DIM = 512 # Размер скрытого слоя в FFN
|
| 15 |
+
DROPOUT = 0.1
|
| 16 |
+
|
| 17 |
+
# Определение модели
|
| 18 |
+
class TransformerModel(nn.Module):
|
| 19 |
+
def __init__(self, vocab_size, embed_size, num_heads, num_layers, ffn_dim, dropout):
|
| 20 |
+
super(TransformerModel, self).__init__()
|
| 21 |
+
self.embedding = nn.Embedding(vocab_size, embed_size)
|
| 22 |
+
self.pos_encoder = PositionalEncoding(embed_size, dropout)
|
| 23 |
+
decoder_layer = TransformerDecoderLayer(embed_size, num_heads, ffn_dim, dropout)
|
| 24 |
+
self.transformer_decoder = TransformerDecoder(decoder_layer, num_layers)
|
| 25 |
+
self.fc_out = nn.Linear(embed_size, vocab_size)
|
| 26 |
+
self.embed_size = embed_size
|
| 27 |
+
|
| 28 |
+
def forward(self, src, src_mask=None):
|
| 29 |
+
src = self.embedding(src) * math.sqrt(self.embed_size)
|
| 30 |
+
src = self.pos_encoder(src)
|
| 31 |
+
output = self.transformer_decoder(src, memory=None, tgt_mask=src_mask)
|
| 32 |
+
output = self.fc_out(output)
|
| 33 |
+
return output
|
| 34 |
+
|
| 35 |
+
class PositionalEncoding(nn.Module):
|
| 36 |
+
def __init__(self, embed_size, dropout, max_len=5000):
|
| 37 |
+
super(PositionalEncoding, self).__init__()
|
| 38 |
+
self.dropout = nn.Dropout(p=dropout)
|
| 39 |
+
pe = torch.zeros(max_len, embed_size)
|
| 40 |
+
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
|
| 41 |
+
div_term = torch.exp(torch.arange(0, embed_size, 2).float() * (-math.log(10000.0) / embed_size))
|
| 42 |
+
pe[:, 0::2] = torch.sin(position * div_term)
|
| 43 |
+
pe[:, 1::2] = torch.cos(position * div_term)
|
| 44 |
+
pe = pe.unsqueeze(0)
|
| 45 |
+
self.register_buffer('pe', pe)
|
| 46 |
+
|
| 47 |
+
def forward(self, x):
|
| 48 |
+
x = x + self.pe[:, :x.size(1)]
|
| 49 |
+
return self.dropout(x)
|
| 50 |
+
|
| 51 |
+
# Подсчет параметров
|
| 52 |
+
def count_parameters(model):
|
| 53 |
+
return sum(p.numel() for p in model.parameters() if p.requires_grad)
|
| 54 |
+
|
| 55 |
+
# Токенизатор и словарь
|
| 56 |
+
tokenizer = get_tokenizer('basic_english')
|
| 57 |
+
def yield_tokens(data_iter):
|
| 58 |
+
for text in data_iter:
|
| 59 |
+
yield tokenizer(text)
|
| 60 |
+
|
| 61 |
+
# Пример данных (замените на свой датасет)
|
| 62 |
+
sample_data = ["Hello world", "This is a test", "Build a neural network"] * 1000
|
| 63 |
+
vocab = build_vocab_from_iterator(yield_tokens(sample_data), specials=['<unk>', '<pad>'])
|
| 64 |
+
vocab.set_default_index(vocab['<unk>'])
|
| 65 |
|
| 66 |
# Инициализация модели
|
| 67 |
+
model = TransformerModel(
|
| 68 |
+
vocab_size=VOCAB_SIZE,
|
| 69 |
+
embed_size=EMBED_SIZE,
|
| 70 |
+
num_heads=NUM_HEADS,
|
| 71 |
+
num_layers=NUM_LAYERS,
|
| 72 |
+
ffn_dim=FFN_DIM,
|
| 73 |
+
dropout=DROPOUT
|
| 74 |
+
)
|
| 75 |
+
print(f"Количество параметров модели: {count_parameters(model)}")
|
| 76 |
|
| 77 |
+
# Функция генерации текста
|
| 78 |
+
def generate_text(prompt, max_length=50):
|
| 79 |
+
model.eval()
|
| 80 |
+
tokens = tokenizer(prompt)
|
| 81 |
+
indices = [vocab[token] for token in tokens]
|
| 82 |
+
src = torch.tensor(indices, dtype=torch.long).unsqueeze(0)
|
| 83 |
+
for _ in range(max_length):
|
| 84 |
+
with torch.no_grad():
|
| 85 |
+
output = model(src)
|
| 86 |
+
next_token = output[:, -1, :].argmax(-1).item()
|
| 87 |
+
src = torch.cat([src, torch.tensor([[next_token]], dtype=torch.long)], dim=-1)
|
| 88 |
+
if next_token == vocab['<pad>']:
|
| 89 |
+
break
|
| 90 |
+
generated = [vocab.get_itos()[idx] for idx in src.squeeze().tolist()]
|
| 91 |
+
return ' '.join(generated)
|
| 92 |
|
| 93 |
+
# Интерфейс Gradio
|
| 94 |
iface = gr.Interface(
|
| 95 |
fn=generate_text,
|
| 96 |
inputs=gr.Textbox(lines=2, placeholder="Введите начало текста..."),
|
| 97 |
outputs="text",
|
| 98 |
+
title="Моя нейросеть (~10M параметров)",
|
| 99 |
+
description="Введите текст, и модель продолжит его."
|
| 100 |
)
|
| 101 |
|
| 102 |
# Запуск интерфейса
|