leftbrain-deepmind-math / left_brain_rt.py
Bigbearbo's picture
LeftBrain b20 v4: add/sub via segment core, 1400/1400 same, 0 wrong, 0 refused
82129c9 verified
Raw History Blame Contribute Delete
18.5 kB
# -*- coding: utf-8 -*-
r"""摘要:#278 合體模型的推論本體——只依賴 torch(給 HF 上傳/離線跑分用)。權重與欄位表從 .pt 讀入。
更新:2026-11-29|作者:Claude子代理-#278合體模型續(Claude Opus 5.5)
import torch, left_brain_rt as RT
m = RT.LeftBrainRT.load("合體模型_b20.pt")
m.answer(["Divide 33 by -225.", "Calculate -0.00258 - 0.3."]) # → ['-11/75', '-0.30258']
輸入=題目 token(字元碼點),輸出=答案 token(字元碼點,0=空位;全 0=拒答)。
forward:固定上限 T 輪的 for 迴圈,每輪 step=各門檻層 y=W2·H(W1x+b1) 加上 0/1 位的 where 閘控(不做算術)。
.pt 內容:{"meta": 欄位表(int/list/dict), "layers": {名: (W1 的 crow,col,val, b1, W2 的 crow,col,val, 形狀)}, "lut": 碼點→字類}。
建網(產生權重)在 left_brain.py;本檔不 import numpy 以外的專案程式(numpy 也不用)。
"""
import torch
from torch import nn
DT = torch.float64
class TL(nn.Module):
"""一層門檻:y = W2 · H(W1 x + b1)。整數權重存成 float64 稀疏 CSR。"""
def __init__(self, W1, b1, W2):
super().__init__()
self.register_buffer("W1", W1)
self.register_buffer("b1", b1)
self.register_buffer("W2", W2)
def forward(self, x):
if self.W1.shape[0] <= 160: # 單元少的層用密集矩陣比較快;整數權重、加總 < 2^53 → 跟稀疏逐位相同
if getattr(self, "_d", None) is None:
self._d = (self.W1.to_dense().T.contiguous(), self.W2.to_dense().T.contiguous())
h = (x @ self._d[0] + self.b1 >= 0).to(DT)
return h @ self._d[1]
h = ((self.W1 @ x.T).T + self.b1 >= 0).to(DT)
return (self.W2 @ h.T).T
def pack(self):
def sp(M):
return (M.crow_indices().clone(), M.col_indices().clone(), M.values().clone(), list(M.shape))
return {"W1": sp(self.W1), "b1": self.b1.clone(), "W2": sp(self.W2)}
@staticmethod
def unpack(d):
def un(t):
c, i, v, s = t
return torch.sparse_csr_tensor(c, i, v, size=tuple(s), dtype=DT)
return TL(un(d["W1"]), d["b1"], un(d["W2"]))
def _rows(t, idx):
"""狀態(dict/list/tensor)取列子集。"""
if isinstance(t, dict):
return {k: _rows(v, idx) for k, v in t.items()}
if isinstance(t, list):
return [_rows(v, idx) for v in t]
return t[idx]
def _put(full, part, idx):
"""把子集的新狀態放回全部列(其他列照舊)。"""
if isinstance(full, dict):
return {k: _put(full[k], part[k], idx) for k in full}
if isinstance(full, list):
return [_put(a, p, idx) for a, p in zip(full, part)]
out = full.clone()
out[idx] = part
return out
LAYERS = ("reader", "dabble", "kl", "sel", "outl")
LISTS = ("enc", "core", "oload")
XLAYERS = ("xpre", "xctl", "xnum", "xpv", "xenc", "xres", "xol", "xcore") # 堆疊機(混合、一元一次;meta["X"] 有才有)
class LeftBrainRT(nn.Module):
"""推論本體。m=欄位表(見 left_brain.LeftBrain.meta)。"""
def setup(self, meta, layers, lut, lut2=None):
self.m = meta
self.register_buffer("lut", lut)
for k in LAYERS:
setattr(self, k, layers[k])
for k in LISTS:
setattr(self, k, nn.ModuleList(layers[k]))
if meta.get("X"):
self.register_buffer("lut2", lut2)
for k in XLAYERS:
setattr(self, k, layers[k])
def _lay_names(self):
return LAYERS + (XLAYERS if self.m.get("X") else ())
# ───── 存/讀 ─────
def export(self, path):
lay = {k: getattr(self, k).pack() for k in self._lay_names()}
for k in LISTS:
lay[k] = [x.pack() for x in getattr(self, k)]
d = {"meta": self.m, "layers": lay, "lut": self.lut.clone()}
if self.m.get("X"):
d["lut2"] = self.lut2.clone()
torch.save(d, path)
@classmethod
def load(cls, path):
d = torch.load(path, weights_only=True)
names = LAYERS + (XLAYERS if d["meta"].get("X") else ())
layers = {k: TL.unpack(d["layers"][k]) for k in names}
for k in LISTS:
layers[k] = [TL.unpack(x) for x in d["layers"][k]]
o = cls()
o.setup(d["meta"], layers, d["lut"], d.get("lut2"))
return o
# ───── tokenizer:字串 ↔ 碼點 ─────
def tokenize(self, qs):
L = self.m["L"]
t = torch.zeros(len(qs), L, dtype=torch.long)
for i, q in enumerate(qs):
cp = [ord(c) for c in q][:L]
if len(q) > L:
cp[-1] = 0xFFFF # 截斷記號(OTHER 類)→ 讀題機拒答
if cp:
t[i, :len(cp)] = torch.tensor(cp)
return t
@staticmethod
def detokenize(out):
return ["".join(chr(c) for c in row if c) for row in out.tolist()]
def init_state(self, tokens):
m = self.m
Bn = tokens.shape[0]
cls = self.lut[tokens.clamp(0, 65535)] # 嵌入查表
oh = torch.zeros(Bn, m["L"], m["V"], dtype=DT)
ok = cls >= 0
oh[ok] = torch.nn.functional.one_hot(cls[ok], m["V"]).to(DT)
rd = torch.zeros(Bn, m["NRD"], dtype=DT)
t0, ts = m["tape"]
rd[:, t0:t0 + ts] = oh.reshape(Bn, -1)
rd[:, m["S0"] + m["start"]] = 1.0 # 起點
for c in m["FC0"]:
rd[:, c] = 1.0 # 小數位數 0
z = lambda n: torch.zeros(Bn, n, dtype=DT) # noqa: E731
OW = m.get("OW", m["bits"]) # 輸出路徑寬度(#278 大數:加減類加寬;舊 .pt 沒這欄=bits)
BW = OW + 4 * m.get("DO", m["D"])
st = {"rd": rd, "C": [z(n) for n in m["NC"]], "bin": z(BW), "bin2": z(BW), "sgn": z(1), "frac": z(1),
"fe": [z(3) for _ in m["NC"]], # 每台引擎:LOADP LOADED CD
"f": z(3), "cnt": z(OW + 1)} # 輸出:OLOADP OLOADED FIN
if m.get("X"):
st["x"] = self._x_init(tokens)
return st
# ───── 堆疊機(混合、一元一次)─────
def _x_init(self, tokens):
X, L = self.m["X"], self.m["L"]
Bn = tokens.shape[0]
cls = self.lut2[tokens.clamp(0, 65535)]
oh = torch.zeros(Bn, L, X["V2"], dtype=DT)
ok = cls >= 0
oh[ok] = torch.nn.functional.one_hot(cls[ok], X["V2"]).to(DT)
z = lambda n: torch.zeros(Bn, n, dtype=DT) # noqa: E731
xs = z(X["NXS"]); xs[:, X["start"]] = 1.0
rc = z(X["NR"] + 1); rc[:, 0] = 1.0 # REDUCE 次數 one-hot
return {"tape": oh.reshape(Bn, -1), "xs": xs, "sh": z(4), "fl": z(len(X["flags"])), "R": z(X["W"]),
"varl": z(26), "ops": z(6 * X["K"]), "vals": [z(X["KV"] * X["CW"]) for _ in range(X["lanes"])],
"C": [z(X["NC"]) for _ in range(X["lanes"])], "fe": [z(3) for _ in range(X["lanes"])], "rc": rc}
def _x_step(self, x):
"""一輪堆疊機:控制器(兩層門檻)→ 動作位 → 帶子/暫存/兩個堆疊/分數機板的 0/1 選擇(不做算術)。回新狀態。"""
X = self.m["X"]
b = lambda t: t > 0.5 # noqa: E731
V2, K, KV, CW, W, NC = X["V2"], X["K"], X["KV"], X["CW"], X["W"], X["NC"]
A = X["act"]
tape, ops, vals = x["tape"], x["ops"], x["vals"]
head = tape[:, :V2]
top = ops[:, :6]
v0 = vals[0]
zc = lambda n: torch.zeros(tape.shape[0], n, dtype=DT) # noqa: E731
cd = torch.stack([fe[:, 2] for fe in x["fe"]], 1)
bad = torch.cat([C[:, X["BAD"]] for C in x["C"]], 1)
xin = torch.cat([head, x["xs"], x["sh"], x["fl"], top, ops[:, 6 * (K - 1):], v0[:, CW - 1:CW], v0[:, 2 * CW - 1:2 * CW],
v0[:, (KV - 1) * CW:(KV - 1) * CW + 1], x["varl"], x["rc"][:, -1:], cd, bad], 1)
pre = b(self.xpre(xin)).to(DT)
act = b(self.xctl(torch.cat([xin, pre], 1)))
g = lambda name: act[:, A[name]] # noqa: E731
g1 = lambda name: act[:, A[name]][:, None] # noqa: E731
fl = b(x["fl"])
EQ, FIND, NEG, ROVX = fl[:, 0], fl[:, 1], fl[:, 2], fl[:, 3]
num = self.xnum(torch.cat([x["R"], head], 1))
R2 = torch.where(g1("NAPP"), num[:, :W], torch.where(g1("NSTART"), num[:, W + 1:], torch.where(g1("PUSHN"), zc(W), x["R"])))
fl2 = torch.stack([EQ | g("OP="), FIND | g("SETFIND"), (NEG | g("SETNEG")) & ~(g("PUSHN") | g("PUSHV")),
ROVX | (g("NAPP") & b(num[:, W]))], 1).to(DT)
sh2 = torch.maximum(x["sh"], act[:, A["SH" + X["shk"][0]]:A["SH" + X["shk"][0]] + 4].to(DT))
letters = head[:, X["letters"]]
varl2 = torch.where(g1("PUSHV"), torch.maximum(x["varl"], letters), x["varl"])
o0 = A["OP" + X["ops"][0]]
opbits = act[:, o0:o0 + 6].to(DT)
pushop = opbits.sum(1, keepdim=True) > 0.5
ops2 = torch.where(pushop, torch.cat([opbits, ops[:, :-6]], 1),
torch.where(g1("POPOP") | g1("WB"), torch.cat([ops[:, 6:], zc(6)], 1), ops))
pv = self.xpv(torch.cat([x["R"], x["fl"][:, 2:3]], 1))
dopush = g1("PUSHN") | g1("PUSHV") | g1("DUP") | g1("XFER")
cpy = g1("DUP") | g1("XFER")
tops = [V[:, :CW] for V in vals]
vals2, C2s, fe2s = [], [], []
for k in range(X["lanes"]):
V, C, fe = vals[k], x["C"][k], x["fe"][k]
src = torch.where(g1("PUSHN"), pv[:, :CW], torch.where(g1("PUSHV"), pv[:, CW * (k + 1):CW * (k + 2)],
torch.where(g1("DUP"), tops[k], tops[1 - k])))
src = torch.cat([src[:, :CW - 1], torch.where(cpy, zc(1), src[:, CW - 1:])], 1) # DUP/XFER 推的格不算含變數
res = self.xres(torch.cat([C, V[:, CW - 1:CW], V[:, 2 * CW - 1:2 * CW]], 1))
vals2.append(torch.where(dopush, torch.cat([src, V[:, :-CW]], 1),
torch.where(g1("WB"), torch.cat([res, V[:, 2 * CW:], zc(CW)], 1), V)))
LOADP, LOADED, CD = b(fe[:, 0]), b(fe[:, 1]), b(fe[:, 2])
enc = self.xenc(torch.cat([V[:, :2 * CW], top], 1))
y = self.xcore(C)
run = LOADED & ~CD
C2s.append(torch.where(LOADP[:, None], enc, torch.where(run[:, None], y[:, :NC], C)))
fe2s.append(torch.stack([g("START"), (LOADED | LOADP) & ~g("WB"), (CD | (run & b(y[:, NC]))) & ~g("WB")], 1).to(DT))
rc = x["rc"]
rc2 = torch.where(g1("START"), torch.cat([zc(1), rc[:, :-1]], 1), rc)
tape2 = torch.where(g1("ADV"), torch.cat([tape[:, V2:], zc(V2)], 1), tape)
return {"tape": tape2, "xs": act[:, :X["NXS"]].to(DT), "sh": sh2, "fl": fl2, "R": R2, "varl": varl2, "ops": ops2,
"vals": vals2, "C": C2s, "fe": fe2s, "rc": rc2}
def _old_dead(self, rd):
m = self.m
return (rd[:, m["S0"] + m["REJ"]] > 0.5) | (rd[:, m["ROVF"]] > 0.5)
compact = True # 已定案的區不再算(跟步驟機 sparse_run「已交卷的列不再算」同義;驗收比對 compact=False 逐位相同)
def step(self, st):
"""一輪(所有區同步):算術全在門檻層;閘控是 0/1 位的選擇。
舊讀題區(讀題機、舊引擎)在讀題機拒答後、堆疊機在 ACC/REJ 後都是吸收態(狀態不再變、對輸出的貢獻固定),
compact 時只算還活著的列。"""
m = self.m
rd, f = st["rd"], st["f"]
b = lambda x: x > 0.5 # noqa: E731
Bn = rd.shape[0]
W = m.get("OW", m["bits"]) # 輸出板/雙倍加的寬度
old_dead = self._old_dead(rd)
fin = b(f[:, 2]) # 輸出完成的列:舊區、堆疊機都不會再影響輸出
live = ~old_dead & ~fin if self.compact else torch.ones(Bn, dtype=torch.bool)
if bool(live.all()):
rd2, C2s, fe2s, ob, anyCD = self._old_part(rd, st["C"], st["fe"])
else:
idx = live.nonzero()[:, 0]
r2, c2, e2, ob_s, any_s = self._old_part(rd[idx], [C[idx] for C in st["C"]], [fe[idx] for fe in st["fe"]])
rd2 = _put(rd, r2, idx); C2s = _put(st["C"], c2, idx); fe2s = _put(st["fe"], e2, idx)
ob = torch.zeros(Bn, 2 * W + 2, dtype=DT); ob[idx] = ob_s
anyCD = torch.zeros(Bn, dtype=torch.bool); anyCD[idx] = any_s
x2 = None
if m.get("X"): # 堆疊機:舊讀題機已拒答(舊模組優先)才輸出
X, x = m["X"], st["x"]
xs = x["xs"]
xlive = ~(b(xs[:, X["ACC"]]) | b(xs[:, X["REJ"]]) | fin) if self.compact else torch.ones(Bn, dtype=torch.bool)
if bool(xlive.all()):
x2 = self._x_step(x)
elif bool(xlive.any()):
idx = xlive.nonzero()[:, 0]
x2 = _put(x, self._x_step(_rows(x, idx)), idx)
else:
x2 = x
xready = b(xs[:, X["ACC"]]) & old_dead
CW = X["CW"]
ob = ob + torch.where(xready[:, None], self.xol(x["vals"][0][:, :CW]), torch.zeros_like(ob))
anyCD = anyCD | xready
OLOADP, OLOADED, FIN = b(f[:, 0]), b(f[:, 1]), b(f[:, 2])
drun = OLOADED & ~FIN
z4 = torch.zeros_like(st["bin"][:, W:])
bin2 = torch.where(OLOADP[:, None], torch.cat([ob[:, :W], z4], 1),
torch.where(drun[:, None], self.dabble(st["bin"]), st["bin"]))
den2 = torch.where(OLOADP[:, None], torch.cat([ob[:, W + 1:2 * W + 1], z4], 1),
torch.where(drun[:, None], self.dabble(st["bin2"]), st["bin2"]))
sgn2 = torch.where(OLOADP[:, None], ob[:, W:W + 1], st["sgn"])
frac2 = torch.where(OLOADP[:, None], ob[:, 2 * W + 1:2 * W + 2], st["frac"])
cnt = st["cnt"]
cnt_sh = torch.cat([torch.zeros_like(cnt[:, :1]), cnt[:, :-1]], 1)
e0 = torch.zeros_like(cnt); e0[:, 0] = 1
cnt2 = torch.where(OLOADP[:, None], e0, torch.where(drun[:, None], cnt_sh, cnt))
f2 = torch.stack([anyCD & ~OLOADED & ~OLOADP, OLOADED | OLOADP, b(cnt2[:, W])], 1).to(DT)
out = {"rd": rd2, "C": C2s, "bin": bin2, "bin2": den2, "sgn": sgn2, "frac": frac2, "fe": fe2s, "f": f2,
"cnt": cnt2}
if x2 is not None:
out["x"] = x2
return out
def _old_part(self, rd, Cs, fes):
"""舊讀題機+舊引擎一輪(輸入可以是列的子集)→ (rd2, C2s, fe2s, 輸出板, 有引擎交卷)。"""
m = self.m
b = lambda x: x > 0.5 # noqa: E731
ovf = b(rd[:, m["ROVF"]])
ready = ~ovf & b(rd[:, m["ACCP"]]) & ~b(rd[:, m["ALA"]]) & ~b(rd[:, m["ALB"]]) # 讀完、對齊完
rd2 = self.reader(rd)
S0, NS = m["S0"], m["NS"]
Sx = rd[:, S0:S0 + NS]
C2s, fe2s, ob, anyCD = [], [], 0, torch.zeros(rd.shape[0], dtype=torch.bool)
for k, nc in enumerate(m["NC"]):
C, fe = Cs[k], fes[k]
LOADP, LOADED, CD = b(fe[:, 0]), b(fe[:, 1]), b(fe[:, 2])
acc = torch.zeros_like(ovf)
for a in m["EACC"][k]:
acc = acc | b(Sx[:, a])
acc = acc & ready
enc = self.enc[k](rd)
y = self.core[k](C)
fC, stop = y[:, :nc], b(y[:, nc])
run = LOADED & ~CD
C2s.append(torch.where(LOADP[:, None], enc, torch.where(run[:, None], fC, C)))
CD2 = CD | (run & stop)
fe2s.append(torch.stack([acc & ~LOADED & ~LOADP, LOADED | LOADP, CD2], 1).to(DT))
ob = ob + self.oload[k](torch.cat([C, Sx], 1)) # 沒載入的引擎板子全 0 → 抄出 0
anyCD = anyCD | CD
return rd2, C2s, fe2s, ob, anyCD
def settled(self, st):
"""每列是否定案(之後狀態不再變):輸出完成、或(舊讀題拒答/數超過位數)且堆疊機也拒答。"""
m = self.m
dead = self._old_dead(st["rd"])
if m.get("X"):
dead = dead & (st["x"]["xs"][:, m["X"]["REJ"]] > 0.5)
return (st["f"][:, 2] > 0.5) | dead
def forward(self, tokens, early_exit=True):
m = self.m
st = self.init_state(tokens)
self.rounds = m["T"]
for t in range(m["T"]): # 固定上限
st = self.step(st)
if early_exit and bool(self.settled(st).all()): # 全部定案就停(像生成遇到 EOS);結果跟跑滿 T 輪相同
self.rounds = t + 1
break
bad = torch.zeros(tokens.shape[0], dtype=torch.bool)
for cols, C in zip(m["BAD"], st["C"]): # 步驟機 NG/DIV0/OVF 旗
for c in cols:
bad = bad | (C[:, c] > 0.5)
ok = (st["f"][:, 2] > 0.5) & ~bad
W = m.get("OW", m["bits"])
Kh = self.kl(st["rd"])
if m.get("X"): # 堆疊機答案是分數(小數位數 K=0)
xr = (st["x"]["xs"][:, m["X"]["ACC"]] > 0.5) & self._old_dead(st["rd"])
Kh = torch.cat([torch.maximum(Kh[:, :1], xr[:, None].to(DT)), Kh[:, 1:]], 1)
x = torch.cat([st["bin"][:, W:], st["bin2"][:, W:], Kh, ok[:, None].to(DT), st["sgn"], st["frac"]], 1)
return self.outl(self.sel(x)).round().long()
@torch.no_grad()
def answer(self, qs, batch=256):
out = []
for s in range(0, len(qs), batch):
out += self.detokenize(self(self.tokenize(qs[s:s + batch])))
return out
if __name__ == "__main__":
import sys
if sys.stdout.encoding and sys.stdout.encoding.lower() != "utf-8":
sys.stdout.reconfigure(encoding="utf-8")
path = sys.argv[1]
mm = LeftBrainRT.load(path)
qs = sys.argv[2:] or ["Divide 33 by -225.", "Calculate -0.00258 - 0.3."]
for q, a in zip(qs, mm.answer(qs)):
print(q, "→", a if a else "拒答")