Andrewstivan commited on
Commit
d6e3606
·
verified ·
1 Parent(s): 88d1ab9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +236 -15
app.py CHANGED
@@ -1,24 +1,245 @@
1
  # ============================================================================
2
- # ОЧИСТКА ПАМЯТИ ПЕРЕД ЗАПУСКОМ
3
  # ============================================================================
4
 
5
- import gc
6
  import torch
 
 
 
 
 
 
 
7
 
8
- print("🧹 Очистка памяти...")
 
9
 
10
- # Сбор мусора Python
11
- gc.collect()
 
12
 
13
- # Очистка CUDA если есть
14
- if torch.cuda.is_available():
15
- torch.cuda.empty_cache()
16
- torch.cuda.reset_peak_memory_stats()
17
- torch.cuda.synchronize()
18
- print(f" CUDA память: {torch.cuda.memory_allocated()/1e9:.2f} ГБ")
19
 
20
- # Очистка MPS если есть
21
- if hasattr(torch, 'mps') and torch.mps.is_available():
22
- torch.mps.empty_cache()
 
23
 
24
- print("✅ Память очищена\n")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # ============================================================================
2
+ # БАТАРЕЯ ТЕСТОВ BDH (БЕЗ ЗАГРУЗКИ AURA)
3
  # ============================================================================
4
 
 
5
  import torch
6
+ import torch.nn.functional as F
7
+ from safetensors.torch import load_file
8
+ from huggingface_hub import hf_hub_download
9
+ import json
10
+ import sys
11
+ import numpy as np
12
+ import time
13
 
14
+ sys.path.append('.')
15
+ from bdh import BDH, BDHConfig
16
 
17
+ print("=" * 70)
18
+ print("🧪 БАТАРЕЯ ТЕСТОВ BDH (БЕЗ AURA)")
19
+ print("=" * 70)
20
 
21
+ device = "cuda" if torch.cuda.is_available() else "cpu"
 
 
 
 
 
22
 
23
+ # -----------------------------------------------------------------------------
24
+ # 1. ЗАГРУЗКА BDH
25
+ # -----------------------------------------------------------------------------
26
+ print("\n📥 Загрузка BDH...")
27
 
28
+ config_path = hf_hub_download(
29
+ repo_id="Andrewstivan/AURA",
30
+ filename="bdh_plasticity/bdh_config.json",
31
+ repo_type="model"
32
+ )
33
+ with open(config_path, 'r') as f:
34
+ config_dict = json.load(f)
35
+
36
+ config = BDHConfig(
37
+ n_layer=config_dict['n_layer'],
38
+ n_embd=config_dict['n_embd'],
39
+ n_head=config_dict['n_head'],
40
+ mlp_internal_dim_multiplier=config_dict['mlp_internal_dim_multiplier'],
41
+ vocab_size=config_dict['vocab_size'],
42
+ dropout=config_dict['dropout']
43
+ )
44
+
45
+ bdh_model = BDH(config).to(device)
46
+
47
+ weights_path = hf_hub_download(
48
+ repo_id="Andrewstivan/AURA",
49
+ filename="bdh_plasticity/bdh_plasticity.safetensors",
50
+ repo_type="model"
51
+ )
52
+ weights = load_file(weights_path)
53
+
54
+ with torch.no_grad():
55
+ enc_w = weights['encoder'].to(device)
56
+ if enc_w.shape == (32, 4096, 128):
57
+ enc_w = enc_w.transpose(1, 2).contiguous()
58
+
59
+ encv_w = weights['encoder_v'].to(device)
60
+ target_encv = bdh_model.encoder_v.weight_fp32.shape
61
+ fixed_encv = torch.zeros(target_encv, device=device)
62
+ if encv_w.dim() == 3:
63
+ encv_w = encv_w.transpose(1, 2)
64
+ copy_d = min(encv_w.shape[2], fixed_encv.shape[2])
65
+ fixed_encv[:, :, :copy_d] = encv_w[:, :, :copy_d]
66
+
67
+ dec_w = weights['decoder'].to(device)
68
+ target_dec = bdh_model.decoder.weight_fp32.shape
69
+ fixed_dec = torch.zeros(target_dec, device=device)
70
+ copy_0 = min(dec_w.shape[0], target_dec[0])
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
+ 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
+
78
+ bdh_model.encoder.update_ternary_weights()
79
+ bdh_model.encoder_v.update_ternary_weights()
80
+ bdh_model.decoder.update_ternary_weights()
81
+
82
+ bdh_model.eval()
83
+ print("✅ BDH загружена")
84
+
85
+ # -----------------------------------------------------------------------------
86
+ # 2. ТЕСТОВЫЕ ТЕКСТЫ
87
+ # -----------------------------------------------------------------------------
88
+ test_texts = [
89
+ "The meaning of life is to be happy and useful.",
90
+ "Artificial intelligence will transform the world.",
91
+ "To be or not to be, that is the question.",
92
+ "Machine learning requires careful evaluation.",
93
+ ]
94
+
95
+ # -----------------------------------------------------------------------------
96
+ # 3. ТЕСТ 1: СТАТИСТИКА ВЕСОВ
97
+ # -----------------------------------------------------------------------------
98
+ print("\n" + "=" * 70)
99
+ print("📊 ТЕСТ 1: СТАТИСТИКА ТЕРНАРНЫХ ВЕСОВ")
100
+ print("=" * 70)
101
+
102
+ for name, param in [
103
+ ('encoder', bdh_model.encoder.weight_ternary),
104
+ ('encoder_v', bdh_model.encoder_v.weight_ternary),
105
+ ('decoder', bdh_model.decoder.weight_ternary),
106
+ ]:
107
+ total = param.numel()
108
+ minus1 = (param == -1).sum().item()
109
+ zero = (param == 0).sum().item()
110
+ plus1 = (param == 1).sum().item()
111
+
112
+ print(f"\n{name}:")
113
+ print(f" -1: {minus1/total:.2%} ({minus1:,})")
114
+ print(f" 0: {zero/total:.2%} ({zero:,})")
115
+ print(f" +1: {plus1/total:.2%} ({plus1:,})")
116
+
117
+ # -----------------------------------------------------------------------------
118
+ # 4. ТЕСТ 2: АКТИВАЦИИ
119
+ # -----------------------------------------------------------------------------
120
+ print("\n" + "=" * 70)
121
+ print("📊 ТЕСТ 2: АНАЛИЗ АКТИВАЦИЙ")
122
+ print("=" * 70)
123
+
124
+ def text_to_bytes(text):
125
+ return torch.tensor(list(text.encode('utf-8')), dtype=torch.long).unsqueeze(0).to(device)
126
+
127
+ for text in test_texts[:2]:
128
+ bytes_tensor = text_to_bytes(text)
129
+ with torch.no_grad():
130
+ _, states = bdh_model.forward_with_states(bytes_tensor)
131
+
132
+ print(f"\n📝 {text[:40]}...")
133
+ print(f" Слой | Mean | Std | Sparsity")
134
+ print(f" -----|-------|-------|---------")
135
+ for i, s in enumerate(states):
136
+ s_flat = s.squeeze(0)
137
+ sparsity = (s_flat.abs() < 1e-4).float().mean().item()
138
+ print(f" {i:4d} | {s_flat.mean():5.3f} | {s_flat.std():5.3f} | {sparsity:7.2%}")
139
+
140
+ # -----------------------------------------------------------------------------
141
+ # 5. ТЕСТ 3: СКОРОСТЬ ИНФЕРЕНСА
142
+ # -----------------------------------------------------------------------------
143
+ print("\n" + "=" * 70)
144
+ print("📊 ТЕСТ 3: СКОРОСТЬ ИНФЕРЕНСА")
145
+ print("=" * 70)
146
+
147
+ for text in test_texts:
148
+ bytes_tensor = text_to_bytes(text)
149
+ num_tokens = bytes_tensor.shape[1]
150
+
151
+ # Разогрев
152
+ for _ in range(3):
153
+ _, _ = bdh_model.forward_with_states(bytes_tensor)
154
+
155
+ torch.cuda.synchronize() if device == "cuda" else None
156
+ start = time.time()
157
+ runs = 10
158
+ for _ in range(runs):
159
+ _, _ = bdh_model.forward_with_states(bytes_tensor)
160
+ torch.cuda.synchronize() if device == "cuda" else None
161
+ elapsed = time.time() - start
162
+
163
+ print(f" {num_tokens:3d} токенов: {elapsed/runs*1000:6.2f} мс ({num_tokens*runs/elapsed:.0f} т/с)")
164
+
165
+ # -----------------------------------------------------------------------------
166
+ # 6. ТЕСТ 4: РАЗМЕР МОДЕЛИ
167
+ # -----------------------------------------------------------------------------
168
+ print("\n" + "=" * 70)
169
+ print("📊 ТЕСТ 4: РАЗМЕР МОДЕЛИ")
170
+ print("=" * 70)
171
+
172
+ total_params = sum(p.numel() for p in bdh_model.parameters())
173
+ ternary_params = 0
174
+ for m in bdh_model.modules():
175
+ if hasattr(m, 'weight_ternary'):
176
+ ternary_params += m.weight_ternary.numel()
177
+
178
+ fp32_mb = total_params * 4 / (1024 * 1024)
179
+ ternary_mb = ternary_params * 2 / 8 / (1024 * 1024)
180
+
181
+ print(f" Всего параметров: {total_params:,}")
182
+ print(f" Тернарных параметров: {ternary_params:,}")
183
+ print(f" Размер в FP32: {fp32_mb:.1f} МБ")
184
+ print(f" Размер в 1.58-bit: {ternary_mb:.2f} МБ")
185
+
186
+ # -----------------------------------------------------------------------------
187
+ # 7. ТЕСТ 5: СТАБИЛЬНОСТЬ ВЫХОДА
188
+ # -----------------------------------------------------------------------------
189
+ print("\n" + "=" * 70)
190
+ print("📊 ТЕСТ 5: СТАБИЛЬНОСТЬ ПРИ ПОВТОРНЫХ ЗАПУСКАХ")
191
+ print("=" * 70)
192
+
193
+ text = test_texts[0]
194
+ bytes_tensor = text_to_bytes(text)
195
+
196
+ outputs = []
197
+ for _ in range(5):
198
+ with torch.no_grad():
199
+ _, states = bdh_model.forward_with_states(bytes_tensor)
200
+ outputs.append(states[-1].mean().item())
201
+
202
+ print(f" Среднее: {np.mean(outputs):.6f}")
203
+ print(f" Std: {np.std(outputs):.6f}")
204
+ print(f" Разброс: {np.std(outputs)/np.mean(outputs)*100:.4f}%")
205
+
206
+ # -----------------------------------------------------------------------------
207
+ # 8. ТЕСТ 6: ГЕНЕРАЦИЯ (упрощённая)
208
+ # -----------------------------------------------------------------------------
209
+ print("\n" + "=" * 70)
210
+ print("📊 ТЕСТ 6: ГЕНЕРАЦИЯ ТЕКСТА")
211
+ print("=" * 70)
212
+
213
+ import torch.nn as nn
214
+ bdh_model.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False).to(device)
215
+
216
+ def generate(prompt, max_len=20):
217
+ bytes_tensor = text_to_bytes(prompt)
218
+ with torch.no_grad():
219
+ for _ in range(max_len):
220
+ x = bdh_model.embed(bytes_tensor).unsqueeze(1)
221
+ x = bdh_model.ln(x)
222
+ for _ in range(config.n_layer):
223
+ x_latent = bdh_model.encoder(x)
224
+ x_sparse = F.relu(x_latent)
225
+ yKV = bdh_model.attn(Q=x_sparse, K=x_sparse, V=x)
226
+ yKV = bdh_model.ln(yKV)
227
+ y_latent = bdh_model.encoder_v(yKV)
228
+ y_sparse = F.relu(y_latent)
229
+ xy_sparse = x_sparse * y_sparse
230
+ xy_flat = xy_sparse.transpose(1, 2).reshape(x.size(0), 1, -1, 32*128)
231
+ yMLP = bdh_model.decoder(xy_flat)
232
+ x = bdh_model.ln(x + bdh_model.ln(yMLP))
233
+ logits = bdh_model.lm_head(x.squeeze(1)[:, -1, :])
234
+ probs = F.softmax(logits / 0.8, dim=-1)
235
+ next_byte = torch.multinomial(probs, 1)
236
+ bytes_tensor = torch.cat([bytes_tensor, next_byte], dim=1)
237
+ return bytes(bytes_tensor.squeeze().cpu().tolist()).decode('utf-8', errors='replace')
238
+
239
+ for prompt in ["The", "Hello", "Art"]:
240
+ print(f"\n📝 {prompt}")
241
+ print(f"🐉 {generate(prompt, max_len=20)}")
242
+
243
+ print("\n" + "=" * 70)
244
+ print("🎉 ТЕСТИРОВАНИЕ ЗАВЕРШЕНО!")
245
+ print("=" * 70)