chrisuser's picture
Release Neuro Compiler 0.3.0
81de6d2 verified
Raw History Blame Contribute Delete
2.07 kB
import torch
from torch import nn
from torch.nn import functional as F
from .physical import OPS
INPUTS = ('signature', 'register', 'immediate', 'stack')
class Encoder(nn.Module):
def __init__(self, width=96):
super().__init__()
self.width = width
self.net = nn.Sequential(nn.Linear(len(OPS) + 34 + 2, width), nn.GELU(), nn.Linear(width, width), nn.GELU(), nn.Linear(width, 42))
def forward(self, sig, reg, imm, stack):
x = torch.cat([F.one_hot(sig, len(OPS)), F.one_hot(reg + 1, 17).flatten(-2), stack.eq(0), stack.le(127)], -1).float()
z = self.net(x)
bits, l, p, src = z.split((32, 5, 3, 2), -1)
return (bits.reshape(*sig.shape, 4, 8), l, p, src)
def decode(self, out, sig, imm, stack):
bits, l, p, src = out
w = 2 ** torch.arange(8, device=sig.device)
prefix = ((bits > 0) * w).sum(-1)
pl = l.argmax(-1)
n = torch.tensor([0, 1, 4], device=sig.device)[p.argmax(-1)]
src = src.argmax(-1)
num = torch.where(src.bool(), stack[..., 0], imm[..., 0])
pos = torch.arange(8, device=sig.device)
k = pos - pl[..., None]
body = num[..., None] >> k.clamp(0, 3) * 8 & 255
v = torch.where(pos < pl[..., None], prefix.gather(-1, pos.clamp_max(3).expand(*sig.shape, 8)), body)
lengths = (pl + n).masked_fill(sig == 0, 0)
if (sig == 1).any():
raise ValueError('OOV physical MIR')
return (v, lengths)
@torch.no_grad()
def encode(self, tensors):
x = tuple((tensors[k] for k in INPUTS))
v, l = self.decode(self(*x), x[0], x[2], x[3])
return pack(v, l)
def pack(v, l):
b, t, w = v.shape
off = l.cumsum(1) - l
pos = torch.arange(w, device=v.device)
mask = pos < l[..., None]
dst = off[..., None] + pos
buf = torch.zeros(b, t * w, dtype=torch.long, device=v.device)
buf.scatter_add_(1, dst.clamp_max(t * w - 1).flatten(1), (v * mask).flatten(1))
return (buf, l.sum(1))