Files
Xenith/demo/numpy_brain.py
2026-10-29 20:48:09 +07:00

197 lines
8.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# numpy_brain.py — запасная реализация MoE-мозга бактерии на чистом numpy.
#
# Тот же API и та же математика, что у xe.MoEBrain (C++): входная проекция →
# gate-softmax top-k → SwiGLU-эксперты → головы (движение / коммуникация /
# ценность); обучение REINFORCE с базой ценности и Adam. Используется демо
# «мини-мир бактерий», если модуль xenith_engine не собран/не импортируется.
#
# C++-версия быстрее в 5-20 раз; эта — чтобы демо запускалось везде.
import numpy as np
def _softmax(x):
x = x - np.max(x)
e = np.exp(x)
return e / (e.sum() + 1e-12)
def _silu(x):
return x / (1.0 + np.exp(-x))
class NumpyMoEBrain:
def __init__(self, d_obs, d_model=24, ffn=32, n_experts=4, top_k=2,
n_move=9, n_comm=9, seed=0):
self.d_obs = d_obs
self.d_model = d_model
self.ffn = ffn
self.n_experts = n_experts
self.top_k = min(top_k, n_experts)
self.n_move = n_move
self.n_comm = n_comm
rng = np.random.default_rng(seed if seed else 12345)
s_in = 1.0 / np.sqrt(d_obs)
s_e = 1.0 / np.sqrt(d_model)
s_f = 1.0 / np.sqrt(ffn)
self.w_in = rng.normal(0, s_in, (d_obs, d_model)).astype(np.float32)
self.gate = rng.normal(0, 0.10, (d_model, n_experts)).astype(np.float32)
self.w1 = rng.normal(0, s_e, (n_experts, d_model, ffn)).astype(np.float32)
self.w3 = rng.normal(0, s_e, (n_experts, d_model, ffn)).astype(np.float32)
self.w2 = rng.normal(0, s_f, (n_experts, ffn, d_model)).astype(np.float32)
self.w_move = rng.normal(0, s_e, (d_model, n_move)).astype(np.float32)
self.w_comm = rng.normal(0, s_e, (d_model, n_comm)).astype(np.float32)
self.w_val = rng.normal(0, 0.3 * s_e, (d_model,)).astype(np.float32)
self._adam_t = 0
self._m = {}
self._v = {}
for k, p in self._params():
self._m[k] = np.zeros_like(p)
self._v[k] = np.zeros_like(p)
self._buf = []
self._cache = None
self.last_loss = 0.0
self.learn_calls = 0
self.episode_len = 0
def _params(self):
yield 'w_in', self.w_in
yield 'gate', self.gate
yield 'w1', self.w1
yield 'w3', self.w3
yield 'w2', self.w2
yield 'w_move', self.w_move
yield 'w_comm', self.w_comm
yield 'w_val', self.w_val
@property
def n_params(self):
return sum(p.size for _, p in self._params())
# ------------------------------------------------------------------
def forward(self, x):
x = np.asarray(x, dtype=np.float32).reshape(-1)
h = x @ self.w_in # [d]
g = h @ self.gate # [E]
sel = np.argpartition(-g, self.top_k - 1)[:self.top_k]
sel = sel[np.argsort(-g[sel])]
pk = _softmax(g[sel]) # [k]
y = np.zeros(self.d_model, dtype=np.float32)
cache_a1 = np.zeros((self.top_k, self.ffn), dtype=np.float32)
cache_a3 = np.zeros_like(cache_a1)
cache_ha = np.zeros_like(cache_a1)
cache_sw = np.zeros((self.top_k, self.d_model), dtype=np.float32)
for t, e in enumerate(sel):
a1 = h @ self.w1[e]
a3 = h @ self.w3[e]
ha = _silu(a1) * a3
sw = ha @ self.w2[e]
cache_a1[t], cache_a3[t], cache_ha[t], cache_sw[t] = a1, a3, ha, sw
y += pk[t] * sw
ml = y @ self.w_move
cl = y @ self.w_comm
v = float(y @ self.w_val)
self._cache = dict(x=x, h=h, sel=sel, pk=pk, a1=cache_a1, a3=cache_a3,
ha=cache_ha, sw=cache_sw, y=y, ml=ml, cl=cl, v=v)
return ml.astype(np.float32), cl.astype(np.float32), v
def remember(self, move_action, comm_action, reward):
assert self._cache is not None, 'remember() до forward()'
c = self._cache
self._buf.append(dict(c, am=int(move_action), ac=int(comm_action), r=float(reward)))
self.episode_len = len(self._buf)
# ------------------------------------------------------------------
def learn(self, lr=1e-3, gamma=0.95):
if not self._buf:
return 0.0
n = len(self._buf)
R = np.zeros(n, dtype=np.float32)
acc = 0.0
for t in range(n - 1, -1, -1):
acc = self._buf[t]['r'] + gamma * acc
R[t] = acc
grads = {k: np.zeros_like(p) for k, p in self._params()}
loss = 0.0
for t, s in enumerate(self._buf):
A = R[t] - s['v']
pm = _softmax(s['ml'])
pc = _softmax(s['cl'])
dm = -A * (np.eye(self.n_move, dtype=np.float32)[s['am']] - pm)
dc = -A * (np.eye(self.n_comm, dtype=np.float32)[s['ac']] - pc)
dv = s['v'] - R[t]
loss += -A * (np.log(max(1e-9, pm[s['am']])) + np.log(max(1e-9, pc[s['ac']]))) \
+ 0.5 * dv * dv
y = s['y']
grads['w_move'] += np.outer(y, dm)
grads['w_comm'] += np.outer(y, dc)
grads['w_val'] += y * dv
dy = dm @ self.w_move.T + dc @ self.w_comm.T + dv * self.w_val
# эксперты и gate
dpk = np.zeros(self.top_k, dtype=np.float32)
dsw = np.zeros_like(s['sw'])
for t2 in range(self.top_k):
dsw[t2] = s['pk'][t2] * dy
dpk[t2] = float(dy @ s['sw'][t2])
sdp = float(np.dot(s['pk'], dpk))
dg = np.zeros(self.n_experts, dtype=np.float32)
for t2 in range(self.top_k):
dg[s['sel'][t2]] = s['pk'][t2] * (dpk[t2] - sdp)
grads['gate'] += np.outer(s['h'], dg)
dh = dg @ self.gate.T
for t2, e in enumerate(s['sel']):
a1, a3, ha = s['a1'][t2], s['a3'][t2], s['ha'][t2]
dha = dsw[t2] @ self.w2[e].T
sg = 1.0 / (1.0 + np.exp(-a1))
da1 = dha * a3 * (sg * (1 + a1 * (1 - sg)))
da3 = dha * _silu(a1)
grads['w2'][e] += np.outer(ha, dsw[t2])
grads['w1'][e] += np.outer(s['h'], da1)
grads['w3'][e] += np.outer(s['h'], da3)
dh += da1 @ self.w1[e].T + da3 @ self.w3[e].T
grads['w_in'] += np.outer(s['x'], dh)
# клип нормы + Adam
gnorm = np.sqrt(sum(float((g ** 2).sum()) for g in grads.values()))
if gnorm > 5.0:
scale = 5.0 / (gnorm + 1e-12)
for k in grads:
grads[k] *= scale
self._adam_t += 1
b1, b2, eps = 0.9, 0.999, 1e-8
bc1 = 1 - b1 ** self._adam_t
bc2 = 1 - b2 ** self._adam_t
for k, p in self._params():
self._m[k] = b1 * self._m[k] + (1 - b1) * grads[k]
self._v[k] = b2 * self._v[k] + (1 - b2) * grads[k] ** 2
p -= lr * (self._m[k] / bc1) / (np.sqrt(self._v[k] / bc2) + eps)
self._buf.clear()
self.episode_len = 0
self.last_loss = loss / n
self.learn_calls += 1
return self.last_loss
def clear_episode(self):
self._buf.clear()
self.episode_len = 0
# ------------------------------------------------------------------
def genome(self):
return np.concatenate([p.reshape(-1) for _, p in self._params()]).astype(np.float32)
def set_genome(self, g):
g = np.asarray(g, dtype=np.float32).reshape(-1)
off = 0
for k, p in self._params():
n = p.size
p.reshape(-1)[:] = g[off:off + n]
off += n
for k, _ in self._params():
self._m[k] = np.zeros_like(self._m[k])
self._v[k] = np.zeros_like(self._v[k])
self._adam_t = 0
self._buf.clear()
def mutate(self, sigma, seed):
rng = np.random.default_rng(seed & 0xFFFFFFFF)
for _, p in self._params():
p += rng.normal(0, sigma, p.shape).astype(np.float32)