Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
# ============================================================================
|
| 2 |
-
#
|
| 3 |
# ============================================================================
|
| 4 |
|
| 5 |
import torch
|
|
@@ -8,20 +8,17 @@ from safetensors.torch import load_file
|
|
| 8 |
from huggingface_hub import hf_hub_download
|
| 9 |
import json
|
| 10 |
import sys
|
| 11 |
-
from tqdm import tqdm
|
| 12 |
|
| 13 |
sys.path.append('.')
|
| 14 |
from bdh import BDH, BDHConfig
|
| 15 |
|
| 16 |
print("=" * 60)
|
| 17 |
-
print("🧪
|
| 18 |
print("=" * 60)
|
| 19 |
|
| 20 |
-
# -----------------------------------------------------------------------------
|
| 21 |
-
# 1. Загрузка модели (как раньше)
|
| 22 |
-
# -----------------------------------------------------------------------------
|
| 23 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 24 |
|
|
|
|
| 25 |
config_path = hf_hub_download(
|
| 26 |
repo_id="Andrewstivan/AURA",
|
| 27 |
filename="bdh_plasticity/bdh_config.json",
|
|
@@ -71,69 +68,26 @@ with torch.no_grad():
|
|
| 71 |
copy_1 = min(dec_w.shape[1], target_dec[1])
|
| 72 |
fixed_dec[:copy_0, :copy_1] = dec_w[:copy_0, :copy_1]
|
| 73 |
|
| 74 |
-
#
|
|
|
|
|
|
|
| 75 |
bdh_model.encoder.weight_fp32.data = enc_w
|
| 76 |
bdh_model.encoder_v.weight_fp32.data = fixed_encv
|
| 77 |
bdh_model.decoder.weight_fp32.data = fixed_dec
|
|
|
|
| 78 |
|
| 79 |
bdh_model.encoder.update_ternary_weights()
|
| 80 |
bdh_model.encoder_v.update_ternary_weights()
|
| 81 |
bdh_model.decoder.update_ternary_weights()
|
|
|
|
| 82 |
|
|
|
|
| 83 |
print("✅ Модель загружена")
|
| 84 |
|
| 85 |
-
#
|
| 86 |
-
# 2. Дообучение lm_head (исправленное)
|
| 87 |
-
# -----------------------------------------------------------------------------
|
| 88 |
-
print("\n📚 Дообучение lm_head...")
|
| 89 |
-
|
| 90 |
-
# Замораживаем ВСЁ кроме lm_head.weight_fp32
|
| 91 |
-
for name, param in bdh_model.named_parameters():
|
| 92 |
-
if 'lm_head.weight_fp32' not in name:
|
| 93 |
-
param.requires_grad = False
|
| 94 |
-
else:
|
| 95 |
-
param.requires_grad = True
|
| 96 |
-
print(f"✅ Обучается: {name}")
|
| 97 |
-
|
| 98 |
-
# Проверяем, что есть обучаемые параметры
|
| 99 |
-
trainable = [n for n, p in bdh_model.named_parameters() if p.requires_grad]
|
| 100 |
-
print(f"Обучаемых параметров: {trainable}")
|
| 101 |
-
|
| 102 |
-
optimizer = torch.optim.AdamW(filter(lambda p: p.requires_grad, bdh_model.parameters()), lr=1e-4)
|
| 103 |
-
|
| 104 |
def text_to_bytes(text):
|
| 105 |
return torch.tensor(list(text.encode('utf-8')), dtype=torch.long).to(device)
|
| 106 |
|
| 107 |
-
train_texts = [
|
| 108 |
-
"The meaning of life is to be happy and useful to others.",
|
| 109 |
-
"To be or not to be, that is the question of existence.",
|
| 110 |
-
"Artificial intelligence will transform the world in many ways.",
|
| 111 |
-
"Machine learning requires careful evaluation and testing.",
|
| 112 |
-
] * 30
|
| 113 |
-
|
| 114 |
-
bdh_model.train()
|
| 115 |
-
for text in tqdm(train_texts, desc="Training"):
|
| 116 |
-
bytes_tensor = text_to_bytes(text)
|
| 117 |
-
inputs = bytes_tensor[:-1].unsqueeze(0)
|
| 118 |
-
targets = bytes_tensor[1:].unsqueeze(0)
|
| 119 |
-
|
| 120 |
-
logits, _ = bdh_model(inputs)
|
| 121 |
-
loss = F.cross_entropy(logits.view(-1, 256), targets.view(-1))
|
| 122 |
-
|
| 123 |
-
optimizer.zero_grad()
|
| 124 |
-
loss.backward()
|
| 125 |
-
optimizer.step()
|
| 126 |
-
|
| 127 |
-
# Обновляем тернарные веса lm_head
|
| 128 |
-
bdh_model.lm_head.update_ternary_weights()
|
| 129 |
-
|
| 130 |
-
print("✅ Дообучение завершено")
|
| 131 |
-
|
| 132 |
-
# -----------------------------------------------------------------------------
|
| 133 |
-
# 3. Генерация
|
| 134 |
-
# -----------------------------------------------------------------------------
|
| 135 |
-
bdh_model.eval()
|
| 136 |
-
|
| 137 |
def generate(prompt, max_len=50, temperature=0.8):
|
| 138 |
bytes_tensor = text_to_bytes(prompt).unsqueeze(0)
|
| 139 |
with torch.no_grad():
|
|
@@ -144,12 +98,9 @@ def generate(prompt, max_len=50, temperature=0.8):
|
|
| 144 |
bytes_tensor = torch.cat([bytes_tensor, next_byte], dim=1)
|
| 145 |
return bytes(bytes_tensor.squeeze().cpu().tolist()).decode('utf-8', errors='replace')
|
| 146 |
|
| 147 |
-
print("\n
|
| 148 |
-
print("📊 ГЕНЕРАЦИЯ")
|
| 149 |
print("=" * 60)
|
| 150 |
|
| 151 |
-
for prompt in ["The
|
| 152 |
print(f"\n📝 {prompt}")
|
| 153 |
-
print(f"🐉 {generate(prompt, max_len=
|
| 154 |
-
|
| 155 |
-
print("\n🎉 ГОТОВО!")
|
|
|
|
| 1 |
# ============================================================================
|
| 2 |
+
# ПРОСТОЙ ТЕСТ БЕЗ ДООБУЧЕНИЯ
|
| 3 |
# ============================================================================
|
| 4 |
|
| 5 |
import torch
|
|
|
|
| 8 |
from huggingface_hub import hf_hub_download
|
| 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 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 20 |
|
| 21 |
+
# Загружаем модель
|
| 22 |
config_path = hf_hub_download(
|
| 23 |
repo_id="Andrewstivan/AURA",
|
| 24 |
filename="bdh_plasticity/bdh_config.json",
|
|
|
|
| 68 |
copy_1 = min(dec_w.shape[1], target_dec[1])
|
| 69 |
fixed_dec[:copy_0, :copy_1] = dec_w[:copy_0, :copy_1]
|
| 70 |
|
| 71 |
+
# lm_head - случайный
|
| 72 |
+
lm_w = torch.randn(target_dec[1], 256, device=device) * 0.02
|
| 73 |
+
|
| 74 |
bdh_model.encoder.weight_fp32.data = enc_w
|
| 75 |
bdh_model.encoder_v.weight_fp32.data = fixed_encv
|
| 76 |
bdh_model.decoder.weight_fp32.data = fixed_dec
|
| 77 |
+
bdh_model.lm_head.weight_fp32.data = lm_w
|
| 78 |
|
| 79 |
bdh_model.encoder.update_ternary_weights()
|
| 80 |
bdh_model.encoder_v.update_ternary_weights()
|
| 81 |
bdh_model.decoder.update_ternary_weights()
|
| 82 |
+
bdh_model.lm_head.update_ternary_weights()
|
| 83 |
|
| 84 |
+
bdh_model.eval()
|
| 85 |
print("✅ Модель загружена")
|
| 86 |
|
| 87 |
+
# Генерация
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
def text_to_bytes(text):
|
| 89 |
return torch.tensor(list(text.encode('utf-8')), dtype=torch.long).to(device)
|
| 90 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
def generate(prompt, max_len=50, temperature=0.8):
|
| 92 |
bytes_tensor = text_to_bytes(prompt).unsqueeze(0)
|
| 93 |
with torch.no_grad():
|
|
|
|
| 98 |
bytes_tensor = torch.cat([bytes_tensor, next_byte], dim=1)
|
| 99 |
return bytes(bytes_tensor.squeeze().cpu().tolist()).decode('utf-8', errors='replace')
|
| 100 |
|
| 101 |
+
print("\n📊 ГЕНЕРАЦИЯ (lm_head случайный):")
|
|
|
|
| 102 |
print("=" * 60)
|
| 103 |
|
| 104 |
+
for prompt in ["The", "Hello", "Artificial"]:
|
| 105 |
print(f"\n📝 {prompt}")
|
| 106 |
+
print(f"🐉 {generate(prompt, max_len=30)}")
|
|
|
|
|
|