Delete Example_Loader.py
Browse files- Example_Loader.py +0 -141
Example_Loader.py
DELETED
|
@@ -1,141 +0,0 @@
|
|
| 1 |
-
import torch
|
| 2 |
-
import torch.nn as nn
|
| 3 |
-
import json
|
| 4 |
-
import random
|
| 5 |
-
from collections import deque
|
| 6 |
-
|
| 7 |
-
# ============ КЛАСС МОДЕЛИ (ДОЛЖЕН СОВПАДАТЬ) ============
|
| 8 |
-
class AndreyBot(nn.Module):
|
| 9 |
-
def __init__(self, vocab_size=89, hidden_size=256, num_layers=2, embedding_dim=64):
|
| 10 |
-
super().__init__()
|
| 11 |
-
self.vocab_size = vocab_size
|
| 12 |
-
self.hidden_size = hidden_size
|
| 13 |
-
self.num_layers = num_layers
|
| 14 |
-
self.embedding_dim = embedding_dim
|
| 15 |
-
self.embedding = nn.Embedding(vocab_size, embedding_dim)
|
| 16 |
-
self.lstm = nn.LSTM(embedding_dim, hidden_size, batch_first=True, num_layers=num_layers, dropout=0.2)
|
| 17 |
-
self.fc = nn.Linear(hidden_size, vocab_size)
|
| 18 |
-
self.dropout = nn.Dropout(0.2)
|
| 19 |
-
|
| 20 |
-
def forward(self, x):
|
| 21 |
-
if x.dim() == 1:
|
| 22 |
-
x = x.unsqueeze(0)
|
| 23 |
-
emb = self.embedding(x)
|
| 24 |
-
out, _ = self.lstm(emb)
|
| 25 |
-
out = self.dropout(out)
|
| 26 |
-
out = out[:, -1, :]
|
| 27 |
-
return self.fc(out)
|
| 28 |
-
|
| 29 |
-
# ============ ЗАГРУЗЧИК ============
|
| 30 |
-
class AndreyLoader:
|
| 31 |
-
def __init__(self, model_path='andrey_full.pt'):
|
| 32 |
-
print("🤖 Загрузка Андрея...")
|
| 33 |
-
|
| 34 |
-
# Загружаем чекпоинт
|
| 35 |
-
checkpoint = torch.load(model_path, map_location='cpu')
|
| 36 |
-
|
| 37 |
-
# Создаём модель
|
| 38 |
-
self.model = AndreyBot(
|
| 39 |
-
vocab_size=checkpoint['vocab_size'],
|
| 40 |
-
hidden_size=checkpoint['hidden_size'],
|
| 41 |
-
num_layers=checkpoint['num_layers'],
|
| 42 |
-
embedding_dim=checkpoint['embedding_dim']
|
| 43 |
-
)
|
| 44 |
-
self.model.load_state_dict(checkpoint['model_state_dict'])
|
| 45 |
-
self.model.eval()
|
| 46 |
-
|
| 47 |
-
# Загружаем словари
|
| 48 |
-
self.word_to_idx = checkpoint['word_to_idx']
|
| 49 |
-
self.idx_to_word = {int(k): v for k, v in checkpoint['idx_to_word'].items()}
|
| 50 |
-
|
| 51 |
-
# Параметры
|
| 52 |
-
self.vocab_size = checkpoint['vocab_size']
|
| 53 |
-
self.epoch = checkpoint['epoch']
|
| 54 |
-
|
| 55 |
-
# Константы
|
| 56 |
-
self.PAD = 0
|
| 57 |
-
self.UNK = 1
|
| 58 |
-
|
| 59 |
-
print(f"✅ Андрей загружен!")
|
| 60 |
-
print(f" 📚 Словарь: {self.vocab_size} слов")
|
| 61 |
-
print(f" 🧠 Обучен: {self.epoch} эпох")
|
| 62 |
-
|
| 63 |
-
def tokenize(self, text):
|
| 64 |
-
"""Текст → список токенов"""
|
| 65 |
-
words = text.lower().split()
|
| 66 |
-
return [self.word_to_idx.get(w, self.UNK) for w in words if w in self.word_to_idx]
|
| 67 |
-
|
| 68 |
-
def detokenize(self, tokens):
|
| 69 |
-
"""Токены → текст"""
|
| 70 |
-
words = []
|
| 71 |
-
for t in tokens:
|
| 72 |
-
if t not in [self.PAD, self.UNK]:
|
| 73 |
-
words.append(self.idx_to_word.get(t, '?'))
|
| 74 |
-
return ' '.join(words)
|
| 75 |
-
|
| 76 |
-
def generate(self, question, temperature=0.85, max_length=12):
|
| 77 |
-
"""Генерация ответа"""
|
| 78 |
-
tokens = self.tokenize(question)
|
| 79 |
-
|
| 80 |
-
if not tokens:
|
| 81 |
-
return "..."
|
| 82 |
-
|
| 83 |
-
current = tokens[0]
|
| 84 |
-
response_tokens = []
|
| 85 |
-
|
| 86 |
-
with torch.no_grad():
|
| 87 |
-
for _ in range(max_length):
|
| 88 |
-
# Получаем логиты от модели
|
| 89 |
-
logits = self.model(torch.tensor([[current]]))
|
| 90 |
-
|
| 91 |
-
# Применяем температуру
|
| 92 |
-
probs = torch.softmax(logits[0] / temperature, dim=-1)
|
| 93 |
-
|
| 94 |
-
# Top-K выбор
|
| 95 |
-
top_k = min(5, self.vocab_size)
|
| 96 |
-
top_probs, top_idx = torch.topk(probs, top_k)
|
| 97 |
-
probs = top_probs / top_probs.sum()
|
| 98 |
-
current = top_idx[torch.multinomial(probs, 1)].item()
|
| 99 |
-
|
| 100 |
-
# Пропускаем спецтокены
|
| 101 |
-
if current in [self.PAD, self.UNK]:
|
| 102 |
-
continue
|
| 103 |
-
|
| 104 |
-
response_tokens.append(current)
|
| 105 |
-
|
| 106 |
-
# Останавливаемся при длине
|
| 107 |
-
if len(response_tokens) >= max_length - 2:
|
| 108 |
-
break
|
| 109 |
-
|
| 110 |
-
if not response_tokens:
|
| 111 |
-
return "..."
|
| 112 |
-
|
| 113 |
-
return self.detokenize(response_tokens)
|
| 114 |
-
|
| 115 |
-
def chat(self):
|
| 116 |
-
"""Запуск чата"""
|
| 117 |
-
print("\n" + "="*50)
|
| 118 |
-
print("🤖 АНДРЕЙ")
|
| 119 |
-
print(" Скажи 'пока' для выхода")
|
| 120 |
-
print("="*50 + "\n")
|
| 121 |
-
|
| 122 |
-
while True:
|
| 123 |
-
user = input("👤 Вы: ").strip().lower()
|
| 124 |
-
|
| 125 |
-
if user in ['пока', 'выход', 'exit', 'quit']:
|
| 126 |
-
print("🤖 Андрей: Пока! 👋")
|
| 127 |
-
break
|
| 128 |
-
|
| 129 |
-
if user == '':
|
| 130 |
-
continue
|
| 131 |
-
|
| 132 |
-
answer = self.generate(user)
|
| 133 |
-
print(f"🤖 Андрей: {answer}\n")
|
| 134 |
-
|
| 135 |
-
# ============ ЗАПУСК ============
|
| 136 |
-
if __name__ == "__main__":
|
| 137 |
-
# Загружаем Андрея
|
| 138 |
-
andrey = AndreyLoader('andrey_full.pt')
|
| 139 |
-
|
| 140 |
-
# Запускаем чат
|
| 141 |
-
andrey.chat()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|