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|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
if a_post.shape[0] < self.n_neurons:
|
| 42 |
-
a_post = torch.cat([a_post, torch.zeros(self.n_neurons - a_post.shape[0])])
|
| 43 |
|
| 44 |
-
|
| 45 |
-
|
|
|
|
|
|
|
| 46 |
|
| 47 |
-
|
| 48 |
-
spike_post = (self.acc_post >= self.threshold).float()
|
| 49 |
|
| 50 |
-
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
-
|
| 54 |
-
self.
|
| 55 |
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
|
|
|
|
|
|
| 59 |
|
|
|
|
| 60 |
self.step_count += 1
|
| 61 |
-
|
| 62 |
-
self.consolidate()
|
| 63 |
-
|
| 64 |
-
return weight_matrix + update
|
| 65 |
|
| 66 |
-
def
|
| 67 |
-
self.
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
embed_shard = None
|
| 96 |
-
for name, shard in weight_map.items():
|
| 97 |
-
if 'embed_tokens' in name:
|
| 98 |
-
embed_shard = shard
|
| 99 |
-
break
|
| 100 |
-
|
| 101 |
-
shard_path = hf_hub_download(repo_id=repo_id, filename=embed_shard)
|
| 102 |
-
shard = load_file(shard_path)
|
| 103 |
-
embeddings = None
|
| 104 |
-
for name, tensor in shard.items():
|
| 105 |
-
if 'embed_tokens' in name:
|
| 106 |
-
embeddings = tensor.float()
|
| 107 |
-
break
|
| 108 |
-
|
| 109 |
-
print(f"✅ Эмбеддинги загружены: {embeddings.shape}")
|
| 110 |
-
|
| 111 |
-
# -----------------------------------------------------------------------------
|
| 112 |
-
# 3. ЗАГРУЖАЕМ BDH
|
| 113 |
-
# -----------------------------------------------------------------------------
|
| 114 |
-
print("\n📥 Загрузка BDH...")
|
| 115 |
-
|
| 116 |
-
config_path = hf_hub_download(
|
| 117 |
-
repo_id="Andrewstivan/AURA",
|
| 118 |
-
filename="bdh_plasticity/bdh_config.json",
|
| 119 |
-
repo_type="model"
|
| 120 |
-
)
|
| 121 |
-
with open(config_path, 'r') as f:
|
| 122 |
-
config_dict = json.load(f)
|
| 123 |
-
|
| 124 |
-
# Убираем лишние поля
|
| 125 |
-
config_dict.pop('model_type', None)
|
| 126 |
-
|
| 127 |
-
config_dict['use_plasticity'] = True
|
| 128 |
-
config = BDHConfig(**config_dict)
|
| 129 |
-
bdh_model = BDH(config).to(device)
|
| 130 |
-
|
| 131 |
-
weights_path = hf_hub_download(
|
| 132 |
-
repo_id="Andrewstivan/AURA",
|
| 133 |
-
filename="bdh_plasticity/bdh_plasticity.safetensors",
|
| 134 |
-
repo_type="model"
|
| 135 |
-
)
|
| 136 |
-
weights = load_file(weights_path)
|
| 137 |
-
|
| 138 |
-
with torch.no_grad():
|
| 139 |
-
bdh_model.encoder.weight_fp32.data = weights['encoder'].to(device)
|
| 140 |
-
bdh_model.encoder_v.weight_fp32.data = weights['encoder_v'].to(device)
|
| 141 |
-
bdh_model.decoder.weight_fp32.data = weights['decoder'].to(device)
|
| 142 |
-
|
| 143 |
-
bdh_model.encoder.update_ternary_weights()
|
| 144 |
-
bdh_model.encoder_v.update_ternary_weights()
|
| 145 |
-
bdh_model.decoder.update_ternary_weights()
|
| 146 |
-
|
| 147 |
-
print("✅ BDH загружена")
|
| 148 |
-
|
| 149 |
-
# -----------------------------------------------------------------------------
|
| 150 |
-
# 4. ПОЛНЫЙ ПЕРЕНОС ТОКЕНИЗАТОРА (ВСЕ 32000)
|
| 151 |
-
# -----------------------------------------------------------------------------
|
| 152 |
-
print("\n🔄 Полный перенос токенизатора (все 32000 токенов)...")
|
| 153 |
-
|
| 154 |
-
plasticity_embed = Plasticity(n_neurons=4096)
|
| 155 |
-
|
| 156 |
-
# БЕРЁМ ВСЕ ТОКЕНЫ!
|
| 157 |
-
for token_str, token_id in tqdm(vocab.items(), desc="Перенос токенов", total=vocab_size):
|
| 158 |
-
token_bytes = token_str.encode('utf-8')
|
| 159 |
-
byte_tensor = torch.tensor(list(token_bytes), dtype=torch.long).unsqueeze(0).to(device)
|
| 160 |
|
| 161 |
-
|
|
|
|
| 162 |
|
| 163 |
-
|
| 164 |
-
bdh_embedding = bdh_model.embed(byte_tensor).mean(dim=1).squeeze(0)
|
| 165 |
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
plasticity_embed.consolidate()
|
| 171 |
-
print("✅ Знания токенизатора перенесены (ВСЕ 32000)")
|
| 172 |
-
|
| 173 |
-
# -----------------------------------------------------------------------------
|
| 174 |
-
# 5. ПОЛНЫЙ ПЕРЕНОС lm_head (ВСЕ 32000)
|
| 175 |
-
# -----------------------------------------------------------------------------
|
| 176 |
-
print("\n🔄 Полный перенос lm_head (все 32000)...")
|
| 177 |
-
|
| 178 |
-
lm_head_aura = None
|
| 179 |
-
for shard_file in set(weight_map.values()):
|
| 180 |
-
shard_path = hf_hub_download(repo_id=repo_id, filename=shard_file)
|
| 181 |
-
shard = load_file(shard_path)
|
| 182 |
-
for name, tensor in shard.items():
|
| 183 |
-
if 'lm_head' in name:
|
| 184 |
-
lm_head_aura = tensor.float()
|
| 185 |
-
break
|
| 186 |
-
if lm_head_aura is not None:
|
| 187 |
-
break
|
| 188 |
-
|
| 189 |
-
print(f"✅ lm_head Aura загружен: {lm_head_aura.shape}")
|
| 190 |
-
|
| 191 |
-
plasticity_lm = Plasticity(n_neurons=4096)
|
| 192 |
-
|
| 193 |
-
# БЕРЁМ ВСЕ ТОКЕНЫ!
|
| 194 |
-
for token_id in tqdm(range(vocab_size), desc="Перенос lm_head", total=vocab_size):
|
| 195 |
-
target = lm_head_aura[token_id].to(device)
|
| 196 |
|
| 197 |
-
|
| 198 |
-
|
|
|
|
| 199 |
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
# -
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
)
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import random
|
| 3 |
+
from typing import List, Set, Tuple, Optional
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
import time
|
| 6 |
+
|
| 7 |
+
# ========== КОНФИГУРАЦИЯ ==========
|
| 8 |
+
@dataclass
|
| 9 |
+
class Config:
|
| 10 |
+
num_neurons: int = 1000
|
| 11 |
+
depth: int = 3
|
| 12 |
+
input_size: int = 256
|
| 13 |
+
output_size: int = 256
|
| 14 |
+
spike_threshold: int = 1000
|
| 15 |
+
input_signal_strength: int = 1000
|
| 16 |
+
signal_scale_shift: int = 8
|
| 17 |
+
explore_noise_scale: int = 64
|
| 18 |
+
sparsity: float = 0.05
|
| 19 |
+
neighbor_radius: int = 10
|
| 20 |
+
hebbian_step_threshold: int = 10
|
| 21 |
+
sigma_decay_shift: int = 8
|
| 22 |
+
dopamine_decay: int = 9
|
| 23 |
+
homeostasis_interval_steps: int = 100
|
| 24 |
+
prune_interval_steps: int = 200
|
| 25 |
+
min_neurons: int = 100
|
| 26 |
+
target_activity: int = 100
|
| 27 |
+
|
| 28 |
+
# ========== НЕЙРОНЫ ==========
|
| 29 |
+
class Neuron:
|
| 30 |
+
def __init__(self, idx: int, threshold: int = 1000, noise_scale: int = 0):
|
| 31 |
+
self.idx = idx
|
| 32 |
+
self.potential = 0
|
| 33 |
+
self.threshold = threshold
|
| 34 |
+
self.fired = False
|
| 35 |
+
self.refractory = 0
|
| 36 |
+
self.neuron_sigma = 0
|
| 37 |
+
self.noise_scale = noise_scale
|
| 38 |
+
self.noise_accum = (idx * 1103515245 + 12345) & 0x7FFFFFFF
|
| 39 |
+
self.outgoing_synapses = []
|
| 40 |
+
self.outgoing_neurons = []
|
| 41 |
+
self.total_fires = 0
|
| 42 |
+
self.neuron_type = "basic"
|
| 43 |
+
|
| 44 |
+
def tick(self, step_count: int) -> Tuple[bool, int]:
|
| 45 |
+
if self.refractory > 0:
|
| 46 |
+
self.refractory -= 1
|
| 47 |
+
return False, 0
|
| 48 |
+
if self.potential >= self.threshold:
|
| 49 |
+
self.fired = True
|
| 50 |
+
output = self.potential
|
| 51 |
+
self.refractory = 2
|
| 52 |
+
self.neuron_sigma += 1
|
| 53 |
+
self.total_fires += 1
|
| 54 |
+
return True, output
|
| 55 |
+
self.fired = False
|
| 56 |
+
return False, 0
|
| 57 |
+
|
| 58 |
+
def integrate(self, signal: int):
|
| 59 |
+
if self.refractory == 0:
|
| 60 |
+
self.potential += signal
|
| 61 |
+
|
| 62 |
+
def fire_ternary(self) -> int:
|
| 63 |
+
if self.fired:
|
| 64 |
+
if self.potential >= self.threshold + (self.threshold >> 2):
|
| 65 |
+
return 1
|
| 66 |
+
elif self.potential <= self.threshold - (self.threshold >> 2):
|
| 67 |
+
return -1
|
| 68 |
+
return 0
|
| 69 |
+
|
| 70 |
+
def propagate(self, shift: int) -> List[Tuple[int, int]]:
|
| 71 |
+
if not self.fired:
|
| 72 |
+
return []
|
| 73 |
+
ternary = self.fire_ternary()
|
| 74 |
+
if ternary == 0:
|
| 75 |
+
self.potential = 0
|
| 76 |
+
return []
|
| 77 |
+
updates = []
|
| 78 |
+
for tgt, syn in zip(self.outgoing_neurons, self.outgoing_synapses):
|
| 79 |
+
signal = ternary * syn.weight
|
| 80 |
+
if signal != 0:
|
| 81 |
+
updates.append((tgt, signal << shift))
|
| 82 |
+
self.potential = 0
|
| 83 |
+
return updates
|
| 84 |
+
|
| 85 |
+
def get_logit_with_noise(self) -> int:
|
| 86 |
+
self.noise_accum = (self.noise_accum * 1103515245 + 12345) & 0x7FFFFFFF
|
| 87 |
+
if self.noise_scale == 0:
|
| 88 |
+
return self.potential
|
| 89 |
+
noise = (self.noise_accum % (self.noise_scale * 2 + 1)) - self.noise_scale
|
| 90 |
+
return self.potential + noise
|
| 91 |
+
|
| 92 |
+
def is_protected(self) -> bool:
|
| 93 |
+
return False
|
| 94 |
+
|
| 95 |
+
class ExcitatoryNeuron(Neuron):
|
| 96 |
+
def __init__(self, idx: int, threshold: int = 1000):
|
| 97 |
+
super().__init__(idx, threshold)
|
| 98 |
+
self.neuron_type = "excitatory"
|
| 99 |
+
def fire_ternary(self) -> int:
|
| 100 |
+
return 1 if self.fired else 0
|
| 101 |
+
|
| 102 |
+
class InhibitoryNeuron(Neuron):
|
| 103 |
+
def __init__(self, idx: int, threshold: int = 1000):
|
| 104 |
+
super().__init__(idx, threshold)
|
| 105 |
+
self.neuron_type = "inhibitory"
|
| 106 |
+
def fire_ternary(self) -> int:
|
| 107 |
+
return -1 if self.fired else 0
|
| 108 |
+
|
| 109 |
+
class OscillatorNeuron(Neuron):
|
| 110 |
+
def __init__(self, idx: int, period_steps: int, threshold: int = 1000):
|
| 111 |
+
super().__init__(idx, threshold)
|
| 112 |
+
self.neuron_type = "oscillator"
|
| 113 |
+
self.period_steps = period_steps
|
| 114 |
+
self.step_counter = 0
|
| 115 |
+
def tick(self, step_count: int) -> Tuple[bool, int]:
|
| 116 |
+
self.step_counter += 1
|
| 117 |
+
if self.step_counter >= self.period_steps:
|
| 118 |
+
self.step_counter = 0
|
| 119 |
+
self.fired = True
|
| 120 |
+
return True, self.threshold
|
| 121 |
+
return False, 0
|
| 122 |
+
def is_protected(self) -> bool:
|
| 123 |
+
return True
|
| 124 |
+
|
| 125 |
+
class CategoryDetectorNeuron(Neuron):
|
| 126 |
+
def __init__(self, idx: int, category_bytes: List[int], threshold: int = 1000):
|
| 127 |
+
super().__init__(idx, threshold)
|
| 128 |
+
self.neuron_type = "category_detector"
|
| 129 |
+
self.category_bytes = set(category_bytes)
|
| 130 |
+
def integrate(self, signal: int, input_byte: Optional[int] = None):
|
| 131 |
+
if input_byte is not None and input_byte in self.category_bytes:
|
| 132 |
+
super().integrate(signal)
|
| 133 |
+
def is_protected(self) -> bool:
|
| 134 |
+
return True
|
| 135 |
+
|
| 136 |
+
# ========== СИНАПС ==========
|
| 137 |
+
class Synapse:
|
| 138 |
+
def __init__(self, source: int, target: int, weight: int = 0):
|
| 139 |
+
self.source = source
|
| 140 |
+
self.target = target
|
| 141 |
+
self.weight = weight
|
| 142 |
+
self.G = 0
|
| 143 |
+
self.sigma = 0
|
| 144 |
+
self.bcm_theta = 512
|
| 145 |
+
|
| 146 |
+
def hebbian_update(self, pre_fired: bool, post_fired: bool,
|
| 147 |
+
post_potential: int, dopamine_gain: int = 512):
|
| 148 |
+
if pre_fired and post_fired:
|
| 149 |
+
self.sigma += dopamine_gain
|
| 150 |
+
if abs(self.sigma) >= 10:
|
| 151 |
+
delta = 1 if self.sigma > 0 else -1
|
| 152 |
+
self.G = max(-1, min(1, self.G + delta))
|
| 153 |
+
self.sigma = 0
|
| 154 |
+
else:
|
| 155 |
+
self.sigma = (self.sigma * 255) >> 8
|
| 156 |
+
|
| 157 |
+
def homeostasis(self, target_activity: int = 100):
|
| 158 |
+
current = abs(self.weight) * 100
|
| 159 |
+
if current > target_activity:
|
| 160 |
+
scale = (target_activity << 8) // current
|
| 161 |
+
self.weight = (self.weight * scale) >> 8
|
| 162 |
+
|
| 163 |
+
# ========== ГРАФ ==========
|
| 164 |
+
class Graph:
|
| 165 |
+
def __init__(self, config: Config):
|
| 166 |
+
self.config = config
|
| 167 |
+
self._n = config.num_neurons
|
| 168 |
+
self.synapses: List[Synapse] = []
|
| 169 |
+
self._incoming_count = [0] * self._n
|
| 170 |
+
self._build()
|
| 171 |
+
|
| 172 |
+
def _build(self):
|
| 173 |
+
for i in range(self._n):
|
| 174 |
+
for j in range(max(0, i - self.config.neighbor_radius),
|
| 175 |
+
min(self._n, i + self.config.neighbor_radius + 1)):
|
| 176 |
+
if i != j and random.random() < self.config.sparsity:
|
| 177 |
+
self.synapses.append(Synapse(i, j))
|
| 178 |
+
self._update_incoming_counts()
|
| 179 |
+
|
| 180 |
+
def _update_incoming_counts(self):
|
| 181 |
+
self._incoming_count = [0] * self._n
|
| 182 |
+
for syn in self.synapses:
|
| 183 |
+
self._incoming_count[syn.target] += 1
|
| 184 |
+
|
| 185 |
+
def get_incoming_count(self, idx: int) -> int:
|
| 186 |
+
return self._incoming_count[idx] if idx < len(self._incoming_count) else 0
|
| 187 |
+
|
| 188 |
+
def get_outgoing_count(self, idx: int) -> int:
|
| 189 |
+
return sum(1 for s in self.synapses if s.source == idx)
|
| 190 |
+
|
| 191 |
+
def get_all_synapses(self) -> List[Synapse]:
|
| 192 |
+
return self.synapses
|
| 193 |
+
|
| 194 |
+
def remove_neuron(self, idx: int):
|
| 195 |
+
self.synapses = [s for s in self.synapses if s.source != idx and s.target != idx]
|
| 196 |
+
self._update_incoming_counts()
|
| 197 |
+
|
| 198 |
+
@property
|
| 199 |
+
def n(self) -> int:
|
| 200 |
+
return self._n
|
| 201 |
+
|
| 202 |
+
@property
|
| 203 |
+
def num_edges(self) -> int:
|
| 204 |
+
return len(self.synapses)
|
| 205 |
|
| 206 |
+
# ========== ПЛАСТИЧНОСТЬ ==========
|
| 207 |
class Plasticity:
|
| 208 |
+
def __init__(self, graph: Graph, config: Config):
|
| 209 |
+
self.graph = graph
|
| 210 |
+
self.config = config
|
| 211 |
+
|
| 212 |
+
def hebbian_update(self, active_neurons: Set[int], potentials: List[int],
|
| 213 |
+
dopamine_gain: int = 512):
|
| 214 |
+
for src in active_neurons:
|
| 215 |
+
for syn in self.graph.synapses:
|
| 216 |
+
if syn.source == src:
|
| 217 |
+
post_active = syn.target in active_neurons
|
| 218 |
+
post_pot = potentials[syn.target] if post_active else 0
|
| 219 |
+
syn.hebbian_update(True, post_active, post_pot, dopamine_gain)
|
| 220 |
+
|
| 221 |
+
def homeostasis_all(self):
|
| 222 |
+
for syn in self.graph.synapses:
|
| 223 |
+
syn.homeostasis(self.config.target_activity)
|
| 224 |
+
|
| 225 |
+
# ========== ЯДРО AURA ==========
|
| 226 |
+
class AuraCore:
|
| 227 |
+
def __init__(self, config: Config):
|
| 228 |
+
self.config = config
|
| 229 |
+
self.graph = Graph(config)
|
| 230 |
+
self.plasticity = Plasticity(self.graph, config)
|
| 231 |
+
self.neurons: List[Neuron] = []
|
| 232 |
+
self._init_neurons()
|
| 233 |
+
self._init_category_detectors()
|
| 234 |
+
self._init_oscillators()
|
| 235 |
+
self._build_caches()
|
| 236 |
+
|
| 237 |
+
self.input_neurons = list(range(min(config.input_size, len(self.neurons))))
|
| 238 |
+
self.output_neurons = list(range(min(config.output_size, len(self.neurons))))
|
| 239 |
+
|
| 240 |
self.step_count = 0
|
| 241 |
+
self.active_neurons: Set[int] = set()
|
| 242 |
+
self.dopamine_trace = 0
|
| 243 |
+
self.dopamine_gain = 512
|
| 244 |
+
self.homeostasis_osc = self.neurons[-2]
|
| 245 |
+
self.prune_osc = self.neurons[-1]
|
| 246 |
|
| 247 |
+
def _init_neurons(self):
|
| 248 |
+
n = self.config.num_neurons
|
| 249 |
+
n_exc = int(n * 0.70)
|
| 250 |
+
n_inh = int(n * 0.15)
|
| 251 |
+
idx = 0
|
| 252 |
+
for _ in range(n_exc):
|
| 253 |
+
self.neurons.append(ExcitatoryNeuron(idx, self.config.spike_threshold))
|
| 254 |
+
idx += 1
|
| 255 |
+
for _ in range(n_inh):
|
| 256 |
+
self.neurons.append(InhibitoryNeuron(idx, self.config.spike_threshold))
|
| 257 |
+
idx += 1
|
| 258 |
+
while idx < n:
|
| 259 |
+
self.neurons.append(Neuron(idx, self.config.spike_threshold))
|
| 260 |
+
idx += 1
|
| 261 |
+
|
| 262 |
+
def _init_category_detectors(self):
|
| 263 |
+
self.neurons.append(CategoryDetectorNeuron(
|
| 264 |
+
len(self.neurons), list(range(48, 58)), self.config.spike_threshold
|
| 265 |
+
))
|
| 266 |
+
self.neurons.append(CategoryDetectorNeuron(
|
| 267 |
+
len(self.neurons), list(range(65, 91)), self.config.spike_threshold
|
| 268 |
+
))
|
| 269 |
+
self.neurons.append(CategoryDetectorNeuron(
|
| 270 |
+
len(self.neurons), list(range(97, 123)), self.config.spike_threshold
|
| 271 |
+
))
|
| 272 |
+
self.neurons.append(CategoryDetectorNeuron(
|
| 273 |
+
len(self.neurons), [9, 10, 32], self.config.spike_threshold
|
| 274 |
+
))
|
| 275 |
+
|
| 276 |
+
def _init_oscillators(self):
|
| 277 |
+
self.neurons.append(OscillatorNeuron(
|
| 278 |
+
len(self.neurons), self.config.homeostasis_interval_steps, self.config.spike_threshold
|
| 279 |
+
))
|
| 280 |
+
self.neurons.append(OscillatorNeuron(
|
| 281 |
+
len(self.neurons), self.config.prune_interval_steps, self.config.spike_threshold
|
| 282 |
+
))
|
| 283 |
+
|
| 284 |
+
def _build_caches(self):
|
| 285 |
+
for n in self.neurons:
|
| 286 |
+
n.outgoing_synapses = []
|
| 287 |
+
n.outgoing_neurons = []
|
| 288 |
+
for syn in self.graph.synapses:
|
| 289 |
+
if syn.source < len(self.neurons):
|
| 290 |
+
self.neurons[syn.source].outgoing_synapses.append(syn)
|
| 291 |
+
self.neurons[syn.source].outgoing_neurons.append(syn.target)
|
| 292 |
+
|
| 293 |
+
def forward(self, input_byte: int, reward: int = 0, explore: bool = True) -> int:
|
| 294 |
+
self.dopamine_trace = (self.dopamine_trace * self.config.dopamine_decay + reward * 10) // 10
|
| 295 |
+
self.dopamine_trace = max(0, min(1024, self.dopamine_trace))
|
| 296 |
+
self.dopamine_gain = 512 + self.dopamine_trace
|
| 297 |
|
| 298 |
+
if self.homeostasis_osc.tick(self.step_count)[0]:
|
| 299 |
+
self.plasticity.homeostasis_all()
|
| 300 |
+
if self.prune_osc.tick(self.step_count)[0]:
|
| 301 |
+
self._prune_isolated()
|
| 302 |
|
| 303 |
+
input_idx = self.input_neurons[input_byte % len(self.input_neurons)]
|
| 304 |
+
input_neuron = self.neurons[input_idx]
|
|
|
|
|
|
|
| 305 |
|
| 306 |
+
if isinstance(input_neuron, CategoryDetectorNeuron):
|
| 307 |
+
input_neuron.integrate(self.config.input_signal_strength, input_byte=input_byte)
|
| 308 |
+
else:
|
| 309 |
+
input_neuron.integrate(self.config.input_signal_strength)
|
| 310 |
|
| 311 |
+
self.active_neurons.clear()
|
|
|
|
| 312 |
|
| 313 |
+
for _ in range(self.config.depth):
|
| 314 |
+
fired_this_step = []
|
| 315 |
+
for i, n in enumerate(self.neurons):
|
| 316 |
+
if n.tick(self.step_count)[0]:
|
| 317 |
+
fired_this_step.append(n)
|
| 318 |
+
self.active_neurons.add(i)
|
| 319 |
+
for src in fired_this_step:
|
| 320 |
+
updates = src.propagate(self.config.signal_scale_shift)
|
| 321 |
+
for tgt, signal in updates:
|
| 322 |
+
if tgt < len(self.neurons):
|
| 323 |
+
self.neurons[tgt].integrate(signal)
|
| 324 |
|
| 325 |
+
potentials = [n.potential for n in self.neurons]
|
| 326 |
+
self.plasticity.hebbian_update(self.active_neurons, potentials, self.dopamine_gain)
|
| 327 |
|
| 328 |
+
logits = [0] * self.config.output_size
|
| 329 |
+
for byte in range(self.config.output_size):
|
| 330 |
+
idx = self.output_neurons[byte]
|
| 331 |
+
if idx < len(self.neurons):
|
| 332 |
+
logits[byte] = self.neurons[idx].get_logit_with_noise() if explore else self.neurons[idx].potential
|
| 333 |
|
| 334 |
+
next_byte = max(range(self.config.output_size), key=lambda i: logits[i])
|
| 335 |
self.step_count += 1
|
| 336 |
+
return next_byte
|
|
|
|
|
|
|
|
|
|
| 337 |
|
| 338 |
+
def _prune_isolated(self):
|
| 339 |
+
if self.graph.n <= self.config.min_neurons:
|
| 340 |
+
return
|
| 341 |
+
dead = []
|
| 342 |
+
for i, n in enumerate(self.neurons):
|
| 343 |
+
if i < self.config.input_size or n.is_protected():
|
| 344 |
+
continue
|
| 345 |
+
if self.graph.get_incoming_count(i) == 0 and self.graph.get_outgoing_count(i) == 0:
|
| 346 |
+
dead.append(i)
|
| 347 |
+
if dead and self.graph.n - len(dead) >= self.config.min_neurons:
|
| 348 |
+
for idx in sorted(dead, reverse=True):
|
| 349 |
+
self.graph.remove_neuron(idx)
|
| 350 |
+
del self.neurons[idx]
|
| 351 |
+
self._build_caches()
|
| 352 |
+
|
| 353 |
+
# ========== ИНИЦИАЛИЗАЦИЯ МОДЕЛИ ==========
|
| 354 |
+
print("🚀 Инициализация AURA...")
|
| 355 |
+
config = Config()
|
| 356 |
+
config.num_neurons = 800
|
| 357 |
+
config.depth = 3
|
| 358 |
+
core = AuraCore(config)
|
| 359 |
+
print(f"✅ Модель готова: {len(core.neurons)} нейронов, {core.graph.num_edges} синапсов")
|
| 360 |
+
|
| 361 |
+
# ========== ФУНКЦИИ ДЛЯ GRADIO ==========
|
| 362 |
+
def generate_text(prompt: str, steps: int = 100, temperature: float = 1.0, reward: int = 0) -> str:
|
| 363 |
+
"""Генерация текста из промпта."""
|
| 364 |
+
if not prompt:
|
| 365 |
+
prompt = "A"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 366 |
|
| 367 |
+
# Устанавливаем шум в зависимости от температуры
|
| 368 |
+
core.config.explore_noise_scale = int(64 * temperature)
|
| 369 |
|
| 370 |
+
start_time = time.time()
|
|
|
|
| 371 |
|
| 372 |
+
# Подаём промпт
|
| 373 |
+
for ch in prompt:
|
| 374 |
+
core.forward(ord(ch), reward=reward, explore=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 375 |
|
| 376 |
+
# Генерируем
|
| 377 |
+
result = list(prompt)
|
| 378 |
+
current = ord(prompt[-1])
|
| 379 |
|
| 380 |
+
for _ in range(steps):
|
| 381 |
+
current = core.forward(current, reward=reward, explore=True)
|
| 382 |
+
if 32 <= current <= 126 or current in (9, 10, 13):
|
| 383 |
+
result.append(chr(current))
|
| 384 |
+
elif current == 0:
|
| 385 |
+
result.append(' ')
|
| 386 |
+
else:
|
| 387 |
+
result.append(chr(32 + (current % 95)))
|
| 388 |
+
|
| 389 |
+
elapsed = time.time() - start_time
|
| 390 |
+
|
| 391 |
+
stats = f"""
|
| 392 |
+
⏱️ Время: {elapsed:.2f} сек
|
| 393 |
+
📊 Шагов: {steps}
|
| 394 |
+
🔥 Активных нейронов: {len(core.active_neurons)}
|
| 395 |
+
💪 Дофамин: {core.dopamine_trace}
|
| 396 |
+
"""
|
| 397 |
+
|
| 398 |
+
return ''.join(result), stats
|
| 399 |
+
|
| 400 |
+
def reset_model():
|
| 401 |
+
"""Сброс модели."""
|
| 402 |
+
global core
|
| 403 |
+
core = AuraCore(config)
|
| 404 |
+
return "✅ Модель сброшена"
|
| 405 |
+
|
| 406 |
+
# ========== ИНТЕРФЕЙС GRADIO ==========
|
| 407 |
+
with gr.Blocks(title="AURA — Спайковая нейросеть", theme=gr.themes.Soft()) as demo:
|
| 408 |
+
gr.Markdown("""
|
| 409 |
+
# 🧠 AURA — Спайковая нейросеть с Hebbian-обучением
|
| 410 |
+
|
| 411 |
+
Минимальная версия ядра AURA. Модель обучается на лету через локальную пластичность.
|
| 412 |
+
""")
|
| 413 |
+
|
| 414 |
+
with gr.Row():
|
| 415 |
+
with gr.Column(scale=2):
|
| 416 |
+
prompt_input = gr.Textbox(
|
| 417 |
+
label="📝 Промпт",
|
| 418 |
+
placeholder="Введите текст для генерации...",
|
| 419 |
+
value="Hello",
|
| 420 |
+
lines=2
|
| 421 |
+
)
|
| 422 |
+
|
| 423 |
+
with gr.Row():
|
| 424 |
+
steps_slider = gr.Slider(
|
| 425 |
+
label="📏 Длина генерации",
|
| 426 |
+
minimum=10,
|
| 427 |
+
maximum=500,
|
| 428 |
+
value=100,
|
| 429 |
+
step=10
|
| 430 |
+
)
|
| 431 |
+
temp_slider = gr.Slider(
|
| 432 |
+
label="🌡️ Temperature (креативность)",
|
| 433 |
+
minimum=0.1,
|
| 434 |
+
maximum=2.0,
|
| 435 |
+
value=1.0,
|
| 436 |
+
step=0.1
|
| 437 |
+
)
|
| 438 |
+
|
| 439 |
+
reward_slider = gr.Slider(
|
| 440 |
+
label="🏆 Reward (награда за шаг)",
|
| 441 |
+
minimum=0,
|
| 442 |
+
maximum=100,
|
| 443 |
+
value=0,
|
| 444 |
+
step=10
|
| 445 |
+
)
|
| 446 |
+
|
| 447 |
+
generate_btn = gr.Button("🚀 Сгенерировать", variant="primary", size="lg")
|
| 448 |
+
reset_btn = gr.Button("🔄 Сбросить модель", variant="secondary")
|
| 449 |
+
|
| 450 |
+
with gr.Column(scale=3):
|
| 451 |
+
output_text = gr.Textbox(
|
| 452 |
+
label="✨ Сгенерированный текст",
|
| 453 |
+
lines=10,
|
| 454 |
+
max_lines=20
|
| 455 |
+
)
|
| 456 |
+
stats_text = gr.Textbox(
|
| 457 |
+
label="📊 Статистика",
|
| 458 |
+
lines=5
|
| 459 |
+
)
|
| 460 |
+
|
| 461 |
+
generate_btn.click(
|
| 462 |
+
fn=generate_text,
|
| 463 |
+
inputs=[prompt_input, steps_slider, temp_slider, reward_slider],
|
| 464 |
+
outputs=[output_text, stats_text]
|
| 465 |
)
|
| 466 |
+
|
| 467 |
+
reset_btn.click(
|
| 468 |
+
fn=reset_model,
|
| 469 |
+
inputs=[],
|
| 470 |
+
outputs=[output_text]
|
| 471 |
+
)
|
| 472 |
+
|
| 473 |
+
gr.Markdown("""
|
| 474 |
+
---
|
| 475 |
+
### О модели
|
| 476 |
+
- **Архитектура**: Спайковая нейросеть на разреженном графе
|
| 477 |
+
- **Обучение**: Hebbian-пластичность (локальные правила)
|
| 478 |
+
- **Нейронов**: 800 (70% excitatory, 15% inhibitory)
|
| 479 |
+
- **Категориальные детекторы**: цифры, буквы, пробелы
|
| 480 |
+
""")
|
| 481 |
+
|
| 482 |
+
if __name__ == "__main__":
|
| 483 |
+
demo.launch()
|