mac-3 / modeling /cs_pipeline.py
jacano1969's picture
Upload modeling/cs_pipeline.py
cbbbaeb verified
Raw History Blame Contribute Delete
8.71 kB
"""mac-3: modular multiplication via carry-save interleaved Horner.
Only two learned cells (full-adder, full-subtractor), applied ELEMENTWISE with
fixed routing. No prefix scan, no combine operator. The outer Horner loop feeds
operand bits on a fixed schedule with no feedback into the encoder. All wrap
bookkeeping uses fixed, unconditional round counts (no value-driven control
flow); cell inputs are always binary (masked addends), so each cell's complete
input space is its truth table."""
import torch
import torch.nn as nn
class BitCell(nn.Module):
def __init__(self, hidden: int = 32, n_in: int = 3, n_out: int = 2):
super().__init__()
self.net = nn.Sequential(
nn.Linear(n_in, hidden), nn.ReLU(),
nn.Linear(hidden, hidden), nn.ReLU(),
nn.Linear(hidden, n_out),
)
def forward(self, x):
return self.net(x)
class CSPipeline:
def __init__(self, adder, sub, device="cpu", wrap_rounds=8, use_bf16=False):
self.adder, self.sub, self.device = adder.to(device), sub.to(device), device
self.R = wrap_rounds
self.use_bf16 = bool(use_bf16) and str(device).startswith("cuda")
self.dropped_wraps = 0 # instrumentacion: debe permanecer 0 SIEMPRE
@torch.no_grad()
def _cell(self, cell, cols):
# Linear opera sobre la ultima dimension: sin reshape. El autocast (bf16)
# se abre UNA sola vez alrededor de modmul; la DECISION se umbraliza en
# fp32 (certificado exhaustivo heredado de las celdas endurecidas:
# min|logit|>=6.07, 0 flips fp32/bf16 sobre las tablas completas).
x = torch.stack(cols, -1) # (N, W, n_in)
o = (torch.sigmoid(cell(x).float()) > 0.5).float()
return o[..., 0], o[..., 1]
def _compress(self, S, C, A):
"""(S+C+A) -> (S', C') via elementwise full-adder; returns top carry-out (N,)."""
s, c = self._cell(self.adder, [S, C, A])
wrap = c[:, -1].clone()
C2 = torch.zeros_like(c); C2[:, 1:] = c[:, :-1] # carry hacia posicion j+1
return s, C2, wrap
def _shl(self, X):
out = X[:, -1].clone()
Y = torch.zeros_like(X); Y[:, 1:] = X[:, :-1]
return Y, out
def _inject(self, S, C, wraps, K, rounds):
"""Rondas FIJAS e incondicionales (sin control de flujo por valores):
adendos binarios enmascarados. Devuelve el pendiente restante (persiste)."""
for _ in range(rounds):
A = torch.clamp(wraps, 0, 1)[:, None] * K
S, C, w2 = self._compress(S, C, A)
wraps = torch.clamp(wraps - 1, min=0) + w2
return S, C, wraps
def _step(self, S, C, pend, addend, K):
"""r <- 2r + addend (mod p, lazy). El pendiente de wraps PERSISTE entre
pasos y se inyecta ANTES del doblado (mismo peso 2^Wd): nada se descarta."""
S, C, pend = self._inject(S, C, pend, K, rounds=2)
S, wS = self._shl(S); C, wC = self._shl(C)
pend = 2.0 * pend + wS + wC # la deuda (unidades de 2^Wd) se dobla con el registro
S, C, w1 = self._compress(S, C, addend)
S, C, pend = self._inject(S, C, pend + w1, K, rounds=2)
return S, C, pend
# ---------- resoluciones exactas (una vez por fase) ----------
def _ripple_add(self, S, C):
"""Resuelve V = S + C exactamente con cadena ripple del adder. Devuelve (N,Wd)."""
N, Wd = S.shape
out = torch.zeros_like(S); carry = torch.zeros(N, 1, device=S.device)
for j in range(Wd):
s, c = self._cell(self.adder, [S[:, j:j+1], C[:, j:j+1], carry])
out[:, j:j+1] = s; carry = c
return out, carry.squeeze(1) # carry final: peso 2^Wd (se pasa como wrap)
def _cond_sub(self, V, Pv):
"""V - Pv si V >= Pv (ripple del subtractor + seleccion por borrow final)."""
N, Wd = V.shape
diff = torch.zeros_like(V); borrow = torch.zeros(N, 1, device=V.device)
for j in range(Wd):
d, b = self._cell(self.sub, [V[:, j:j+1], Pv[:, j:j+1], borrow])
diff[:, j:j+1] = d; borrow = b
keep = (borrow.squeeze(1) > 0.5)[:, None].float() # borrow=1 -> V < Pv -> conservar V
return keep * V + (1 - keep) * diff
# ---------- setup neural de la constante K = 2^Wd mod p (POR FILA) ----------
def _setup_K(self, P):
"""P: (N, Wd), primos potencialmente de DISTINTO bit-length en el batch.
Por fila i: W_i = bit_length(p_i); K0_i = 2^{W_i} - p_i (< p_i, exacto);
luego (Wd - W_i) doblados exactos con resta condicional, aplicados con
mascara derivada del INPUT (ruteo, no salida del modelo)."""
N, Wd = P.shape
# msb por fila, derivado del input p (preprocesado/ruteo legal)
top_idx = torch.argmax((P.flip(1) > 0.5).float(), dim=1) # (N,)
W_row = (Wd - top_idx).to(torch.long) # bit_length por fila
two_W = torch.zeros_like(P)
two_W.scatter_(1, W_row[:, None].clamp(max=Wd - 1), 1.0) # one-hot 2^{W_i}
K = self._cond_sub(two_W, P) # K0_i = 2^{W_i} - p_i < p_i
deltas = (Wd - W_row).to(torch.float32) # doblados pendientes
max_delta = int(deltas.max().item())
for d in range(max_delta):
K2, _ = self._shl(K)
K2 = self._cond_sub(K2, P) # 2K < 2p -> una resta basta
mask = (deltas > d).float()[:, None] # ruteo por input
K = mask * K2 + (1.0 - mask) * K
return K, W_row
# ---------- API ----------
@torch.no_grad()
def modmul(self, A_msb, B_msb, P):
if self.use_bf16:
with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
return self._modmul_impl(A_msb, B_msb, P)
return self._modmul_impl(A_msb, B_msb, P)
def _modmul_impl(self, A_msb, B_msb, P):
"""A_msb,B_msb: (N, La/Lb) bits MSB-first de a, b crudos. P: (N, Wd) LSB-first."""
N, Wd = P.shape
K, W = self._setup_K(P)
zeros = torch.zeros(N, Wd, device=P.device)
e0 = torch.zeros(N, Wd, device=P.device); e0[:, 0] = 1.0
# fase 1: b_red = b mod p (Horner sobre bits de b, addend = bit en pos 0)
S, C = zeros.clone(), zeros.clone()
pend = torch.zeros(N, device=P.device)
for i in range(B_msb.shape[1]):
S, C, pend = self._step(S, C, pend, B_msb[:, i:i+1] * e0, K)
S, C, pend = self._inject(S, C, pend, K, rounds=10) # drenaje pre-resolve (1 vez por fase: generosidad gratis)
self.dropped_wraps += float(torch.nan_to_num(torch.sum(pend), posinf=1e9).item())
Bred = self._resolve(S, C, P, K)
# fase 2: (a * b_red) mod p (Horner sobre bits de a, addend = bit * Bred)
S, C = zeros.clone(), zeros.clone()
pend = torch.zeros(N, device=P.device)
for i in range(A_msb.shape[1]):
S, C, pend = self._step(S, C, pend, A_msb[:, i:i+1] * Bred, K)
S, C, pend = self._inject(S, C, pend, K, rounds=10) # drenaje pre-resolve (1 vez por fase: generosidad gratis)
self.dropped_wraps += float(torch.nan_to_num(torch.sum(pend), posinf=1e9).item())
return self._resolve(S, C, P, K)
def _resolve(self, S, C, P, K):
V, wrap = self._ripple_add(S, C)
for _ in range(5): # absorcion fija; adendos SIEMPRE binarios
A = torch.clamp(wrap, 0, 1)[:, None] * K
S2, C2, w2 = self._compress(V, A, torch.zeros_like(V))
V, wrap2 = self._ripple_add(S2, C2)
wrap = torch.clamp(wrap - 1, min=0) + w2 + wrap2
self.dropped_wraps += float(torch.nan_to_num(torch.sum(wrap), posinf=1e9).item())
# Reduccion final POR FILA: V < 2^Wd y p_i > 2^(W_i-1) -> V/p_i < 2^(delta_i+1)
# con delta_i = Wd - W_i. Restar p_i*2^s para s = delta_max..0; el shift s
# solo es aplicable (cabe en registro) a filas con delta_i >= s: mascara
# derivada del INPUT p (ruteo), no de salidas del modelo.
N, Wd = P.shape
top_idx = torch.argmax((P.flip(1) > 0.5).float(), dim=1)
deltas = top_idx.to(torch.float32) # Wd - W_i = indice del msb desde arriba
max_delta = int(deltas.max().item())
for s in range(max_delta, -1, -1):
Pv = P
for _ in range(s):
Pv, _ = self._shl_c(Pv)
V2 = self._cond_sub(V, Pv)
mask = (deltas >= s).float()[:, None]
V = mask * V2 + (1.0 - mask) * V
return V
def _shl_c(self, X):
out = X[:, -1].clone()
Y = torch.zeros_like(X); Y[:, 1:] = X[:, :-1]
return Y, out