Andrewstivan commited on
Commit
e05dcc3
·
verified ·
1 Parent(s): 69537de

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +131 -12
app.py CHANGED
@@ -1,8 +1,101 @@
1
  # ============================================================================
2
- # ДООБУЧЕНИЕ LM_HEAD ДЛЯ ЧИТАЕМОЙ ГЕНЕРАЦИИ
3
  # ============================================================================
4
 
5
- import torch.optim as optim
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
  # Замораживаем всё кроме lm_head
8
  for name, param in bdh_model.named_parameters():
@@ -11,21 +104,23 @@ for name, param in bdh_model.named_parameters():
11
  else:
12
  param.requires_grad = True
13
 
14
- optimizer = optim.AdamW(filter(lambda p: p.requires_grad, bdh_model.parameters()), lr=1e-4)
 
 
 
15
 
16
- # Обучающий текст
17
  train_texts = [
18
  "The meaning of life is to be happy and useful to others.",
19
  "To be or not to be, that is the question of existence.",
20
  "Artificial intelligence will transform the world in many ways.",
21
  "Machine learning requires careful evaluation and testing.",
22
- ] * 50
 
 
23
 
24
- print(f"📚 Дообучение lm_head на {len(train_texts)} примерах...")
25
  bdh_model.train()
26
-
27
- for text in tqdm(train_texts):
28
- bytes_tensor = text_to_bytes(text).squeeze(0)
29
  inputs = bytes_tensor[:-1].unsqueeze(0)
30
  targets = bytes_tensor[1:].unsqueeze(0)
31
 
@@ -36,7 +131,31 @@ for text in tqdm(train_texts):
36
  loss.backward()
37
  optimizer.step()
38
 
39
- print("✅ Дообучение завершено!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
- # Сохраняем
42
- bdh_model.save("bdh_model_trained.pt")
 
1
  # ============================================================================
2
+ # ПОЛНЫЙ СКРИПТ: ЗАГРУЗКА + ДООБУЧЕНИЕ + ГЕНЕРАЦИЯ
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
+ 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",
28
+ repo_type="model"
29
+ )
30
+ with open(config_path, 'r') as f:
31
+ config_dict = json.load(f)
32
+
33
+ config = BDHConfig(
34
+ n_layer=config_dict['n_layer'],
35
+ n_embd=config_dict['n_embd'],
36
+ n_head=config_dict['n_head'],
37
+ mlp_internal_dim_multiplier=config_dict['mlp_internal_dim_multiplier'],
38
+ vocab_size=config_dict['vocab_size'],
39
+ dropout=config_dict['dropout']
40
+ )
41
+
42
+ bdh_model = BDH(config).to(device)
43
+
44
+ weights_path = hf_hub_download(
45
+ repo_id="Andrewstivan/AURA",
46
+ filename="bdh_plasticity/bdh_plasticity.safetensors",
47
+ repo_type="model"
48
+ )
49
+ weights = load_file(weights_path)
50
+
51
+ with torch.no_grad():
52
+ # encoder
53
+ enc_w = weights['encoder'].to(device)
54
+ if enc_w.shape == (32, 4096, 128):
55
+ enc_w = enc_w.transpose(1, 2).contiguous()
56
+
57
+ # encoder_v
58
+ encv_w = weights['encoder_v'].to(device)
59
+ target_encv = bdh_model.encoder_v.weight_fp32.shape
60
+ fixed_encv = torch.zeros(target_encv, device=device)
61
+ if encv_w.dim() == 3:
62
+ encv_w = encv_w.transpose(1, 2)
63
+ copy_d = min(encv_w.shape[2], fixed_encv.shape[2])
64
+ fixed_encv[:, :, :copy_d] = encv_w[:, :, :copy_d]
65
+
66
+ # decoder
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
+ # lm_head
75
+ lm_w = weights['lm_head'].to(device)
76
+ target_lm = bdh_model.lm_head.weight_fp32.shape
77
+ fixed_lm = torch.zeros(target_lm, device=device)
78
+ copy_0 = min(lm_w.shape[0], target_lm[0])
79
+ copy_1 = min(lm_w.shape[1], target_lm[1])
80
+ fixed_lm[:copy_0, :copy_1] = lm_w[:copy_0, :copy_1]
81
+
82
+ # Применяем
83
+ bdh_model.encoder.weight_fp32.data = enc_w
84
+ bdh_model.encoder_v.weight_fp32.data = fixed_encv
85
+ bdh_model.decoder.weight_fp32.data = fixed_dec
86
+ bdh_model.lm_head.weight_fp32.data = fixed_lm
87
+
88
+ bdh_model.encoder.update_ternary_weights()
89
+ bdh_model.encoder_v.update_ternary_weights()
90
+ bdh_model.decoder.update_ternary_weights()
91
+ bdh_model.lm_head.update_ternary_weights()
92
+
93
+ print("✅ Модель загружена")
94
+
95
+ # -----------------------------------------------------------------------------
96
+ # 2. Дообучение lm_head
97
+ # -----------------------------------------------------------------------------
98
+ print("\n📚 Дообучение lm_head...")
99
 
100
  # Замораживаем всё кроме lm_head
101
  for name, param in bdh_model.named_parameters():
 
104
  else:
105
  param.requires_grad = True
106
 
107
+ optimizer = torch.optim.AdamW(filter(lambda p: p.requires_grad, bdh_model.parameters()), lr=1e-4)
108
+
109
+ def text_to_bytes(text):
110
+ return torch.tensor(list(text.encode('utf-8')), dtype=torch.long).to(device)
111
 
 
112
  train_texts = [
113
  "The meaning of life is to be happy and useful to others.",
114
  "To be or not to be, that is the question of existence.",
115
  "Artificial intelligence will transform the world in many ways.",
116
  "Machine learning requires careful evaluation and testing.",
117
+ "The future of humanity depends on our choices today.",
118
+ "In the beginning, the universe was created.",
119
+ ] * 20
120
 
 
121
  bdh_model.train()
122
+ for text in tqdm(train_texts, desc="Training"):
123
+ bytes_tensor = text_to_bytes(text)
 
124
  inputs = bytes_tensor[:-1].unsqueeze(0)
125
  targets = bytes_tensor[1:].unsqueeze(0)
126
 
 
131
  loss.backward()
132
  optimizer.step()
133
 
134
+ print("✅ Дообучение завершено")
135
+
136
+ # -----------------------------------------------------------------------------
137
+ # 3. Генерация
138
+ # -----------------------------------------------------------------------------
139
+ bdh_model.eval()
140
+
141
+ def generate(prompt, max_len=50, temperature=0.8):
142
+ bytes_tensor = text_to_bytes(prompt).unsqueeze(0)
143
+ with torch.no_grad():
144
+ for _ in range(max_len):
145
+ logits, _ = bdh_model(bytes_tensor)
146
+ probs = F.softmax(logits[:, -1, :] / temperature, dim=-1)
147
+ next_byte = torch.multinomial(probs, num_samples=1)
148
+ bytes_tensor = torch.cat([bytes_tensor, next_byte], dim=1)
149
+ return bytes(bytes_tensor.squeeze().cpu().tolist()).decode('utf-8', errors='replace')
150
+
151
+ print("\n" + "=" * 60)
152
+ print("📊 ГЕНЕРАЦИЯ ПОСЛЕ ДООБУЧЕНИЯ")
153
+ print("=" * 60)
154
+
155
+ prompts = ["The meaning of life is", "Artificial intelligence", "To be or not to be"]
156
+
157
+ for prompt in prompts:
158
+ print(f"\n📝 {prompt}")
159
+ print(f"🐉 {generate(prompt, max_len=40)}")
160
 
161
+ print("\n🎉 ГОТОВО!")