Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
# ============================================================================
|
| 2 |
-
#
|
| 3 |
# ============================================================================
|
| 4 |
|
| 5 |
import torch
|
|
@@ -9,20 +9,16 @@ from huggingface_hub import hf_hub_download
|
|
| 9 |
import json
|
| 10 |
import sys
|
| 11 |
|
| 12 |
-
# Подключаем BDH
|
| 13 |
sys.path.append('.')
|
| 14 |
from bdh import BDH, BDHConfig
|
| 15 |
|
| 16 |
print("=" * 60)
|
| 17 |
-
print("🧪 ТЕСТИРОВАНИЕ BDH
|
| 18 |
print("=" * 60)
|
| 19 |
|
| 20 |
# -----------------------------------------------------------------------------
|
| 21 |
# 1. Загружаем конфиг и веса
|
| 22 |
# -----------------------------------------------------------------------------
|
| 23 |
-
print("\n📥 Загрузка модели...")
|
| 24 |
-
|
| 25 |
-
# Загружаем конфиг
|
| 26 |
config_path = hf_hub_download(
|
| 27 |
repo_id="Andrewstivan/AURA",
|
| 28 |
filename="bdh_plasticity/bdh_config.json",
|
|
@@ -40,7 +36,6 @@ config = BDHConfig(
|
|
| 40 |
dropout=config_dict['dropout']
|
| 41 |
)
|
| 42 |
|
| 43 |
-
# Создаём модель
|
| 44 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 45 |
bdh_model = BDH(config).to(device)
|
| 46 |
|
|
@@ -52,12 +47,30 @@ weights_path = hf_hub_download(
|
|
| 52 |
)
|
| 53 |
weights = load_file(weights_path)
|
| 54 |
|
| 55 |
-
# При
|
| 56 |
with torch.no_grad():
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
# Обновляем тернарные веса
|
| 63 |
bdh_model.encoder.update_ternary_weights()
|
|
@@ -66,12 +79,10 @@ with torch.no_grad():
|
|
| 66 |
bdh_model.lm_head.update_ternary_weights()
|
| 67 |
|
| 68 |
bdh_model.eval()
|
| 69 |
-
|
| 70 |
-
print(f"✅ Модель загружена на {device}")
|
| 71 |
-
print(f" Параметров: {sum(p.numel() for p in bdh_model.parameters()):,}")
|
| 72 |
|
| 73 |
# -----------------------------------------------------------------------------
|
| 74 |
-
# 2.
|
| 75 |
# -----------------------------------------------------------------------------
|
| 76 |
def text_to_bytes(text):
|
| 77 |
return torch.tensor(list(text.encode('utf-8')), dtype=torch.long).unsqueeze(0).to(device)
|
|
@@ -89,50 +100,10 @@ def generate(prompt, max_len=50, temperature=0.8):
|
|
| 89 |
generated_bytes = bytes_tensor.squeeze().cpu().tolist()
|
| 90 |
return bytes(generated_bytes).decode('utf-8', errors='replace')
|
| 91 |
|
| 92 |
-
def get_hidden_state(text):
|
| 93 |
-
bytes_tensor = text_to_bytes(text)
|
| 94 |
-
with torch.no_grad():
|
| 95 |
-
_, states = bdh_model.forward_with_states(bytes_tensor)
|
| 96 |
-
return states[-1].mean(dim=1) # Последний слой, усреднённый по токенам
|
| 97 |
-
|
| 98 |
-
# -----------------------------------------------------------------------------
|
| 99 |
-
# 3. Тесты
|
| 100 |
-
# -----------------------------------------------------------------------------
|
| 101 |
-
print("\n" + "=" * 60)
|
| 102 |
-
print("📊 ТЕСТ 1: Генерация текста")
|
| 103 |
-
print("=" * 60)
|
| 104 |
-
|
| 105 |
-
prompts = [
|
| 106 |
-
"The meaning of life is",
|
| 107 |
-
"Artificial intelligence",
|
| 108 |
-
"To be or not to be",
|
| 109 |
-
"The future of humanity",
|
| 110 |
-
"In the beginning",
|
| 111 |
-
]
|
| 112 |
-
|
| 113 |
-
for prompt in prompts:
|
| 114 |
-
print(f"\n📝 Промпт: {prompt}")
|
| 115 |
-
generated = generate(prompt, max_len=40, temperature=0.8)
|
| 116 |
-
print(f"🐉 BDH: {generated}")
|
| 117 |
-
|
| 118 |
-
# -----------------------------------------------------------------------------
|
| 119 |
-
# 4. Сравнение с оригиналом
|
| 120 |
-
# -----------------------------------------------------------------------------
|
| 121 |
print("\n" + "=" * 60)
|
| 122 |
-
print("📊 ТЕСТ
|
| 123 |
print("=" * 60)
|
| 124 |
|
| 125 |
-
for
|
| 126 |
-
(
|
| 127 |
-
(
|
| 128 |
-
('decoder', bdh_model.decoder.weight_ternary),
|
| 129 |
-
]:
|
| 130 |
-
unique_vals = param.unique().cpu().tolist()
|
| 131 |
-
print(f"\n{name}:")
|
| 132 |
-
print(f" Уникальные значения: {unique_vals}")
|
| 133 |
-
print(f" -1: {(param == -1).sum().item() / param.numel():.2%}")
|
| 134 |
-
print(f" 0: {(param == 0).sum().item() / param.numel():.2%}")
|
| 135 |
-
print(f" +1: {(param == 1).sum().item() / param.numel():.2%}")
|
| 136 |
-
|
| 137 |
-
print("\n" + "=" * 60)
|
| 138 |
-
print("🎉 ТЕСТИРОВАНИЕ ЗАВЕРШЕНО!")
|
|
|
|
| 1 |
# ============================================================================
|
| 2 |
+
# ИСПРАВЛЕННАЯ ЗАГРУЗКА И ТЕСТ
|
| 3 |
# ============================================================================
|
| 4 |
|
| 5 |
import torch
|
|
|
|
| 9 |
import json
|
| 10 |
import sys
|
| 11 |
|
|
|
|
| 12 |
sys.path.append('.')
|
| 13 |
from bdh import BDH, BDHConfig
|
| 14 |
|
| 15 |
print("=" * 60)
|
| 16 |
+
print("🧪 ИСПРАВЛЕННОЕ ТЕСТИРОВАНИЕ BDH")
|
| 17 |
print("=" * 60)
|
| 18 |
|
| 19 |
# -----------------------------------------------------------------------------
|
| 20 |
# 1. Загружаем конфиг и веса
|
| 21 |
# -----------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
| 22 |
config_path = hf_hub_download(
|
| 23 |
repo_id="Andrewstivan/AURA",
|
| 24 |
filename="bdh_plasticity/bdh_config.json",
|
|
|
|
| 36 |
dropout=config_dict['dropout']
|
| 37 |
)
|
| 38 |
|
|
|
|
| 39 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 40 |
bdh_model = BDH(config).to(device)
|
| 41 |
|
|
|
|
| 47 |
)
|
| 48 |
weights = load_file(weights_path)
|
| 49 |
|
| 50 |
+
# ИСПРАВЛЕНИЕ: транспонируем если нужно
|
| 51 |
with torch.no_grad():
|
| 52 |
+
encoder_w = weights['encoder'].to(device)
|
| 53 |
+
encoder_v_w = weights['encoder_v'].to(device)
|
| 54 |
+
decoder_w = weights['decoder'].to(device)
|
| 55 |
+
lm_head_w = weights['lm_head'].to(device)
|
| 56 |
+
|
| 57 |
+
# Проверяем и исправляем размерности
|
| 58 |
+
print(f"\n📐 Проверка размерностей:")
|
| 59 |
+
print(f" encoder загружен: {encoder_w.shape}")
|
| 60 |
+
print(f" encoder ожидает: {bdh_model.encoder.weight_fp32.shape}")
|
| 61 |
+
|
| 62 |
+
# BDH encoder ожидает [nh, N, D] = [32, 128, 4096]
|
| 63 |
+
if encoder_w.shape != bdh_model.encoder.weight_fp32.shape:
|
| 64 |
+
print(" ⚠️ Транспонируем encoder...")
|
| 65 |
+
if encoder_w.shape == (32, 4096, 128):
|
| 66 |
+
encoder_w = encoder_w.transpose(1, 2) # [32, 128, 4096]
|
| 67 |
+
if encoder_v_w.shape == (32, 4096, 128):
|
| 68 |
+
encoder_v_w = encoder_v_w.transpose(1, 2)
|
| 69 |
+
|
| 70 |
+
bdh_model.encoder.weight_fp32.data = encoder_w
|
| 71 |
+
bdh_model.encoder_v.weight_fp32.data = encoder_v_w
|
| 72 |
+
bdh_model.decoder.weight_fp32.data = decoder_w
|
| 73 |
+
bdh_model.lm_head.weight_fp32.data = lm_head_w
|
| 74 |
|
| 75 |
# Обновляем тернарные веса
|
| 76 |
bdh_model.encoder.update_ternary_weights()
|
|
|
|
| 79 |
bdh_model.lm_head.update_ternary_weights()
|
| 80 |
|
| 81 |
bdh_model.eval()
|
| 82 |
+
print(f"\n✅ Модель готова! Параметров: {sum(p.numel() for p in bdh_model.parameters()):,}")
|
|
|
|
|
|
|
| 83 |
|
| 84 |
# -----------------------------------------------------------------------------
|
| 85 |
+
# 2. Тест генерации
|
| 86 |
# -----------------------------------------------------------------------------
|
| 87 |
def text_to_bytes(text):
|
| 88 |
return torch.tensor(list(text.encode('utf-8')), dtype=torch.long).unsqueeze(0).to(device)
|
|
|
|
| 100 |
generated_bytes = bytes_tensor.squeeze().cpu().tolist()
|
| 101 |
return bytes(generated_bytes).decode('utf-8', errors='replace')
|
| 102 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
print("\n" + "=" * 60)
|
| 104 |
+
print("📊 ГЕНЕРАЦИЯ ТЕКСТА")
|
| 105 |
print("=" * 60)
|
| 106 |
|
| 107 |
+
for prompt in ["The meaning of life is", "Artificial intelligence", "To be or not to be"]:
|
| 108 |
+
print(f"\n📝 {prompt}")
|
| 109 |
+
print(f"🐉 {generate(prompt, max_len=40)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|