Download modeling/bitserial.py from jacano-mac/mac-1: direct link, hf CLI and curl.
- Browser
- Download file 5.61 kB
-
https://huggingface.co/jacano-mac/mac-1/resolve/main/modeling/bitserial.py
- Command line
-
hf download hf://jacano-mac/mac-1/modeling/bitserial.py
-
curl -L -o bitserial.py https://huggingface.co/jacano-mac/mac-1/resolve/main/modeling/bitserial.py
5.61 kB
| """Multiplicacion modular EXACTA bit-serial — modulo self-contained de la submission. | |
| (a*b) mod p SIN formar el producto y SIN aritmetica de Python sobre los valores: | |
| celdas de 1 bit (o de k bits, radix-2^k) APRENDIDAS (full-adder + full-subtractor) | |
| componen una suma modular exacta g(r,s,p)=(r+s) mod p, y con ella todo el pipeline. | |
| La exactitud y la invariancia al ancho vienen de que las celdas son funciones finitas | |
| aprendidas; la recurrencia/localidad de bit es arquitectura (permitida). | |
| Cambios vs version base: | |
| * BitCell parametrizada por k. k=1 == celda original (in=3,out=2): carga tus .pt. | |
| * addmod/modmul radix-2^k: procesan k bits por paso -> cadena ~Wi/k (menos pasos | |
| secuenciales y, al compilar, grafo ~k veces menor -> compila mucho mas rapido). | |
| * torch.compile selectivo del addmod (fusiona el bucle de acarreo, ataca el | |
| overhead de dispatch que es el cuello en CPU). Una compilacion por W; el batch | |
| se marca dinamico (cambiar N no recompila). La compilacion ocurre en warmup() | |
| (en load()), nunca dentro del presupuesto de inferencia. | |
| """ | |
| from __future__ import annotations | |
| import torch | |
| import torch.nn as nn | |
| def to_bits_lsb(x: int, width: int) -> list[int]: | |
| return [(x >> i) & 1 for i in range(width)] | |
| def from_bits_lsb(bits) -> int: | |
| v = 0 | |
| for i, b in enumerate(bits): | |
| if b: | |
| v |= (1 << i) | |
| return v | |
| class BitCell(nn.Module): | |
| """Celda radix-2^k. k=1 -> (in=3,out=2) identica a la original. | |
| add: f(k bits r, k bits s, carry_in) -> (k bits sum, carry_out) | |
| sub: f(k bits a, k bits b, borrow_in) -> (k bits diff, borrow_out) | |
| """ | |
| def __init__(self, hidden: int = 32, k: int = 1): | |
| super().__init__() | |
| self.k = k | |
| self.net = nn.Sequential( | |
| nn.Linear(2 * k + 1, hidden), nn.ReLU(), | |
| nn.Linear(hidden, hidden), nn.ReLU(), | |
| nn.Linear(hidden, k + 1), | |
| ) | |
| def forward(self, x): | |
| return self.net(x) | |
| class ExactPipeline: | |
| def __init__(self, adder: BitCell, sub: BitCell, device: str, | |
| k: int = 1, use_compile: bool = True, compile_min_width: int = 96): | |
| self.adder, self.sub, self.device = adder, sub, device | |
| self.k = k | |
| self.use_compile = use_compile | |
| self.compile_min_width = compile_min_width # bajo esto, eager (no vale el coste de compilar) | |
| self._addmod_c = (torch.compile(self._addmod_impl, dynamic=False, fullgraph=True) | |
| if use_compile else None) | |
| # -- nucleo: (r+s) mod p exacto, radix-2^k (k=1 == bit-serial original) ---- | |
| def _addmod_impl(self, r, s, p): | |
| k = self.k | |
| N, W = r.shape | |
| dev = r.device | |
| Wi = W + 1 # r+s < 2p cabe en W+1 bits | |
| pad = (-Wi) % k | |
| Wp = Wi + pad # multiplo de k | |
| z = torch.zeros(N, Wp - W, device=dev) | |
| r = torch.cat([r, z], -1); s = torch.cat([s, z], -1); p = torch.cat([p, z], -1) | |
| nch = Wp // k | |
| # suma (cadena de acarreo, k bits por paso) | |
| carry = torch.zeros(N, 1, device=dev); summ = [] | |
| for ch in range(nch): | |
| sl = slice(ch * k, ch * k + k) | |
| o = (torch.sigmoid(self.adder(torch.cat([r[:, sl], s[:, sl], carry], -1))) > 0.5).float() | |
| summ.append(o[:, :k]); carry = o[:, k:k + 1] | |
| summ = torch.cat(summ, -1) | |
| # resta sum - p (cadena de prestamo); borrow final=1 => sum<p | |
| borrow = torch.zeros(N, 1, device=dev); diff = [] | |
| for ch in range(nch): | |
| sl = slice(ch * k, ch * k + k) | |
| o = (torch.sigmoid(self.sub(torch.cat([summ[:, sl], p[:, sl], borrow], -1))) > 0.5).float() | |
| diff.append(o[:, :k]); borrow = o[:, k:k + 1] | |
| diff = torch.cat(diff, -1) | |
| res = torch.where(borrow > 0.5, summ, diff) | |
| return res[:, :W] | |
| def addmod(self, r, s, p): | |
| W = r.shape[1] | |
| if self.use_compile and W >= self.compile_min_width: | |
| # batch dinamico (N varia sin recompilar); W estatico (desenrolla el bucle) | |
| torch._dynamo.mark_dynamic(r, 0) | |
| torch._dynamo.mark_dynamic(s, 0) | |
| torch._dynamo.mark_dynamic(p, 0) | |
| return self._addmod_c(r, s, p) | |
| return self._addmod_impl(r, s, p) | |
| def warmup(self, widths, n: int = 2): | |
| """Fuerza la compilacion (coste alto) FUERA del presupuesto, en load(). | |
| Pasa los W que de verdad vas a computar (los p_bits de cada tier <= max_pbits). | |
| """ | |
| if not self.use_compile: | |
| return | |
| for W in sorted(set(int(w) for w in widths)): | |
| if W < self.compile_min_width: | |
| continue | |
| d = torch.zeros(n, W, device=self.device) | |
| self.addmod(d, d, d) | |
| def modmul(self, a_msb, b_msb, P): | |
| """(a*b) mod p. a_msb/b_msb: (N,La)/(N,Lb) MSB-first. P: (N,W). -> (N,W) LSB-first.""" | |
| N, W = P.shape | |
| dev = P.device | |
| r = torch.zeros(N, W, device=dev) | |
| for j in range(b_msb.shape[1]): | |
| bit = torch.zeros(N, W, device=dev); bit[:, 0] = b_msb[:, j] | |
| r = self.addmod(r, r, P) # 2r | |
| r = self.addmod(r, bit, P) # + b_i | |
| b_red = r | |
| r = torch.zeros(N, W, device=dev) | |
| for j in range(a_msb.shape[1]): | |
| ai = a_msb[:, j:j + 1] | |
| r = self.addmod(r, r, P) # 2r | |
| added = self.addmod(r, b_red, P) # r + b_red | |
| r = torch.where(ai > 0.5, added, r) # condicional segun bit de a | |
| return r | |