Andrewstivan commited on
Commit
cfee7b8
·
verified ·
1 Parent(s): dfddc07

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +115 -247
app.py CHANGED
@@ -1,270 +1,138 @@
1
- import json
 
 
 
2
  import torch
3
- import torch.nn as nn
4
  import torch.nn.functional as F
5
- import sys
6
- import os
7
- from huggingface_hub import HfApi
8
- from safetensors.torch import save_file
9
- import gc
10
- from tqdm import tqdm
11
- from safetensors import safe_open
12
  from huggingface_hub import hf_hub_download
 
 
13
 
 
14
  sys.path.append('.')
15
  from bdh import BDH, BDHConfig
16
 
17
- # ------------------------------------------------------------
18
- # Пластичность (исправленная)
19
- # ------------------------------------------------------------
20
- class Plasticity:
21
- def __init__(self, n_neurons):
22
- self.n_neurons = n_neurons
23
- self.w = torch.zeros(n_neurons, n_neurons)
24
- self.long_term_w = torch.zeros(n_neurons, n_neurons)
25
- self.lr = 0.01
26
- self.consolidation_rate = 0.01
27
- self.forget_rate = 0.1
28
- self.acc_pre = torch.zeros(n_neurons)
29
- self.acc_post = torch.zeros(n_neurons)
30
- self.threshold = 0.5
31
- self.bcm_theta = torch.zeros(n_neurons)
32
- self.lr_bcm = 0.001
33
- self.target_activity = 0.5
34
- self.step_count = 0
35
-
36
- def adapt_weights(self, weight_matrix):
37
- """Адаптирует матрицу весов через пластичность."""
38
- original_shape = weight_matrix.shape
39
-
40
- # Приводим к 2D
41
- if weight_matrix.dim() == 3:
42
- wm_2d = weight_matrix.reshape(-1, weight_matrix.shape[-1])
43
- else:
44
- wm_2d = weight_matrix
45
-
46
- # Вычисляем a_pre и a_post
47
- a_pre_raw = wm_2d.mean(dim=1)
48
- a_post_raw = wm_2d.mean(dim=0)
49
-
50
- # Приведение a_pre к n_neurons
51
- if a_pre_raw.shape[0] > self.n_neurons:
52
- a_pre = a_pre_raw[:self.n_neurons]
53
- elif a_pre_raw.shape[0] < self.n_neurons:
54
- repeat_factor = (self.n_neurons + a_pre_raw.shape[0] - 1) // a_pre_raw.shape[0]
55
- a_pre = a_pre_raw.repeat(repeat_factor)[:self.n_neurons]
56
- else:
57
- a_pre = a_pre_raw
58
-
59
- # Приведение a_post к n_neurons
60
- if a_post_raw.shape[0] > self.n_neurons:
61
- a_post = a_post_raw[:self.n_neurons]
62
- elif a_post_raw.shape[0] < self.n_neurons:
63
- repeat_factor = (self.n_neurons + a_post_raw.shape[0] - 1) // a_post_raw.shape[0]
64
- a_post = a_post_raw.repeat(repeat_factor)[:self.n_neurons]
65
- else:
66
- a_post = a_post_raw
67
-
68
- # Псевдоспайки
69
- self.acc_pre += a_pre
70
- self.acc_post += a_post
71
-
72
- spike_pre = (self.acc_pre >= self.threshold).float()
73
- spike_post = (self.acc_post >= self.threshold).float()
74
-
75
- self.acc_pre -= spike_pre * self.threshold
76
- self.acc_post -= spike_post * self.threshold
77
-
78
- # Хеббовское обновление
79
- delta = self.lr * torch.outer(spike_pre, spike_post)
80
- self.w += delta
81
-
82
- # Применяем адаптацию к ИСХОДНОЙ матрице
83
- with torch.no_grad():
84
- # БЕРЁМ СРЕЗ ОТ self.w
85
- update_slice = self.w[:wm_2d.shape[0], :wm_2d.shape[1]]
86
-
87
- # ЕСЛИ СРЕЗ МЕНЬШЕ, ЧЕМ НУЖНО, ПОВТОРЯЕМ ЕГО
88
- if update_slice.shape[0] < wm_2d.shape[0] or update_slice.shape[1] < wm_2d.shape[1]:
89
- repeat_rows = (wm_2d.shape[0] + update_slice.shape[0] - 1) // update_slice.shape[0]
90
- repeat_cols = (wm_2d.shape[1] + update_slice.shape[1] - 1) // update_slice.shape[1]
91
- update = update_slice.repeat(repeat_rows, repeat_cols)[:wm_2d.shape[0], :wm_2d.shape[1]]
92
- else:
93
- update = update_slice
94
-
95
- update = update * 0.01
96
-
97
- if weight_matrix.dim() == 3:
98
- update = update.reshape(original_shape)
99
- weight_matrix = weight_matrix + update
100
-
101
- self.step_count += 1
102
- if self.step_count % 10 == 0:
103
- self.consolidate()
104
-
105
- return weight_matrix
106
-
107
- def consolidate(self):
108
- self.long_term_w += self.consolidation_rate * self.w
109
- self.w = self.w * (1 - self.forget_rate)
110
-
111
- # ------------------------------------------------------------
112
- # Загрузка shard'ов
113
- # ------------------------------------------------------------
114
- class ShardCache:
115
- def __init__(self, repo_id, weight_map):
116
- self.repo_id = repo_id
117
- self.weight_map = weight_map
118
- self.cached_shards = {}
119
-
120
- def get_layer_weights(self, layer_idx):
121
- prefix = f"model.layers.{layer_idx}."
122
- layer_tensors = {n: s for n, s in self.weight_map.items() if n.startswith(prefix)}
123
- if not layer_tensors:
124
- return {}
125
-
126
- for shard_file in set(layer_tensors.values()):
127
- if shard_file not in self.cached_shards:
128
- shard_path = hf_hub_download(repo_id=self.repo_id, filename=shard_file)
129
- self.cached_shards[shard_file] = safe_open(shard_path, framework="pt", device="cpu")
130
-
131
- weights = {}
132
- for name, shard_file in layer_tensors.items():
133
- param_name = name.split('.')[-2]
134
- weights[param_name] = self.cached_shards[shard_file].get_tensor(name)
135
- return weights
136
-
137
- def close(self):
138
- for s in self.cached_shards.values():
139
- s.__exit__(None, None, None)
140
-
141
- # ------------------------------------------------------------
142
- # Основной процесс
143
- # ------------------------------------------------------------
144
  print("=" * 60)
145
- print("🧠 ЗАБИРАЕМ ВЕСА AURA ЧЕРЕЗ ПЛАСТИЧНОСТЬ (ПОЛНОРАЗМЕРНЫЕ)")
146
  print("=" * 60)
147
 
148
- repo_id = "ResplendentAI/Aura_v3_7B"
149
- index_path = hf_hub_download(repo_id=repo_id, filename="model.safetensors.index.json")
150
- with open(index_path, 'r') as f:
151
- weight_map = json.load(f)['weight_map']
152
 
153
- cache = ShardCache(repo_id, weight_map)
 
 
 
 
 
 
 
154
 
155
- # Конфиг BDH - ПОЛНОРАЗМЕРНЫЙ
156
  config = BDHConfig(
157
- n_layer=6,
158
- n_embd=4096,
159
- n_head=32,
160
- mlp_internal_dim_multiplier=1,
161
- vocab_size=256,
162
- dropout=0.1
163
  )
164
- D = config.n_embd
165
- nh = config.n_head
166
- N = config.mlp_internal_dim_multiplier * D // nh
167
-
168
- print(f"\n📐 Конфиг BDH: D={D}, nh={nh}, N={N}")
169
-
170
- # Создаём пластичность
171
- plasticity_enc = Plasticity(n_neurons=D)
172
- plasticity_enc_v = Plasticity(n_neurons=D)
173
- plasticity_dec = Plasticity(n_neurons=D)
174
 
175
- # Начинаем с весов первого слоя
176
- print("\n🔄 Забираем веса из 32 слоёв Aura...")
177
- layer0 = cache.get_layer_weights(0)
178
 
179
- # Инициализируем веса BDH из первого слоя
180
- q_proj_0 = layer0['q_proj'].float()
181
- v_proj_0 = layer0['v_proj'].float()
182
- o_proj_0 = layer0['o_proj'].float()
183
-
184
- encoder = q_proj_0[:D, :N].unsqueeze(0).repeat(nh, 1, 1)
185
- encoder_v = v_proj_0[:D, :N].unsqueeze(0).repeat(nh, 1, 1)
186
- decoder = o_proj_0[:nh * N, :D]
187
-
188
- print(f" Начальный encoder: {encoder.shape}")
189
- print(f" Начальный encoder_v: {encoder_v.shape}")
190
- print(f" Начальный decoder: {decoder.shape}")
191
-
192
- # Адаптируем через остальные слои
193
- for layer_idx in tqdm(range(1, 32)):
194
- w = cache.get_layer_weights(layer_idx)
195
- if not w:
196
- continue
197
-
198
- q_proj = w['q_proj'].float()[:D, :N].unsqueeze(0).repeat(nh, 1, 1)
199
- v_proj = w['v_proj'].float()[:D, :N].unsqueeze(0).repeat(nh, 1, 1)
200
- o_proj = w['o_proj'].float()[:nh * N, :D]
201
-
202
- encoder = plasticity_enc.adapt_weights(encoder + q_proj * 0.1)
203
- encoder_v = plasticity_enc_v.adapt_weights(encoder_v + v_proj * 0.1)
204
- decoder = plasticity_dec.adapt_weights(decoder + o_proj * 0.1)
205
-
206
- del w, q_proj, v_proj, o_proj
207
- gc.collect()
208
-
209
- # Финальная консолидация
210
- plasticity_enc.consolidate()
211
- plasticity_enc_v.consolidate()
212
- plasticity_dec.consolidate()
213
-
214
- # Формируем итоговые веса
215
- bdh_weights = {
216
- 'encoder': encoder,
217
- 'encoder_v': encoder_v,
218
- 'decoder': decoder,
219
- 'lm_head': torch.randn(D, 256) * 0.02
220
- }
221
-
222
- print(f"\n✅ Итоговые размеры:")
223
- print(f" encoder: {bdh_weights['encoder'].shape}")
224
- print(f" encoder_v: {bdh_weights['encoder_v'].shape}")
225
- print(f" decoder: {bdh_weights['decoder'].shape}")
226
-
227
- print("\n📤 Сохраняем веса в репозиторий Andrewstivan/AURA...")
228
 
229
- # Создаём временную папку
230
- os.makedirs("bdh_weights_upload", exist_ok=True)
231
 
232
- # Сохраняем веса в формате safetensors
233
- bdh_weights_safe = {k: v.cpu() for k, v in bdh_weights.items()}
234
- save_file(bdh_weights_safe, "bdh_weights_upload/bdh_plasticity.safetensors")
235
 
236
- # Сохраняем конфиг BDH
237
- config_dict = {
238
- "model_type": "bdh",
239
- "n_layer": config.n_layer,
240
- "n_embd": config.n_embd,
241
- "n_head": config.n_head,
242
- "mlp_internal_dim_multiplier": config.mlp_internal_dim_multiplier,
243
- "vocab_size": config.vocab_size,
244
- "dropout": config.dropout
245
- }
246
- with open("bdh_weights_upload/bdh_config.json", "w") as f:
247
- json.dump(config_dict, f, indent=2)
248
 
249
- # Загружаем в существующий репозиторий Andrewstivan/AURA
250
- token = os.environ.get('HF_TOKEN')
251
- if token:
252
- api = HfApi(token=token)
253
- repo_id = "Andrewstivan/AURA" # <-- Ваш существующий репозиторий
254
 
255
- api.upload_folder(
256
- folder_path="bdh_weights_upload",
257
- repo_id=repo_id,
258
- repo_type="model",
259
- path_in_repo="bdh_plasticity", # Файлы будут в папке bdh_plasticity/
260
- commit_message="🧠 Добавлены веса BDH, полученные через пластичность из Aura"
261
- )
262
 
263
- print("✅ Веса загружены в Andrewstivan/AURA/bdh_plasticity/")
264
- print(" - bdh_plasticity.safetensors")
265
- print(" - bdh_config.json")
266
- else:
267
- print("⚠️ HF_TOKEN не найден! Файлы сохранены локально в папке 'bdh_weights_upload'")
268
- print(" Загрузите их вручную в репозиторий Andrewstivan/AURA")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
269
 
270
- 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
 
12
+ # Подключаем BDH
13
  sys.path.append('.')
14
  from bdh import BDH, BDHConfig
15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  print("=" * 60)
17
+ print("🧪 ТЕСТИРОВАНИЕ BDH С ВЕСАМИ ИЗ AURA")
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",
29
+ repo_type="model"
30
+ )
31
+ with open(config_path, 'r') as f:
32
+ config_dict = json.load(f)
33
 
 
34
  config = BDHConfig(
35
+ n_layer=config_dict['n_layer'],
36
+ n_embd=config_dict['n_embd'],
37
+ n_head=config_dict['n_head'],
38
+ mlp_internal_dim_multiplier=config_dict['mlp_internal_dim_multiplier'],
39
+ vocab_size=config_dict['vocab_size'],
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
 
47
+ # Загружаем веса
48
+ weights_path = hf_hub_download(
49
+ repo_id="Andrewstivan/AURA",
50
+ filename="bdh_plasticity/bdh_plasticity.safetensors",
51
+ repo_type="model"
52
+ )
53
+ weights = load_file(weights_path)
54
+
55
+ # Применяем веса
56
+ with torch.no_grad():
57
+ bdh_model.encoder.weight_fp32.data = weights['encoder'].to(device)
58
+ bdh_model.encoder_v.weight_fp32.data = weights['encoder_v'].to(device)
59
+ bdh_model.decoder.weight_fp32.data = weights['decoder'].to(device)
60
+ bdh_model.lm_head.weight_fp32.data = weights['lm_head'].to(device)
61
+
62
+ # Обновляем тернарные веса
63
+ bdh_model.encoder.update_ternary_weights()
64
+ bdh_model.encoder_v.update_ternary_weights()
65
+ bdh_model.decoder.update_ternary_weights()
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)
 
 
 
 
 
 
 
78
 
79
+ def generate(prompt, max_len=50, temperature=0.8):
80
+ bytes_tensor = text_to_bytes(prompt)
 
 
 
81
 
82
+ with torch.no_grad():
83
+ for _ in range(max_len):
84
+ logits, _ = bdh_model(bytes_tensor)
85
+ probs = F.softmax(logits[:, -1, :] / temperature, dim=-1)
86
+ next_byte = torch.multinomial(probs, num_samples=1)
87
+ bytes_tensor = torch.cat([bytes_tensor, next_byte], dim=1)
 
88
 
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("📊 ТЕСТ 2: Статистика весов")
123
+ print("=" * 60)
124
 
125
+ for name, param in [
126
+ ('encoder', bdh_model.encoder.weight_ternary),
127
+ ('encoder_v', bdh_model.encoder_v.weight_ternary),
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("🎉 ТЕСТИРОВАНИЕ ЗАВЕРШЕНО!")