File size: 4,508 Bytes
c08a9c6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | """NeuroLD 0.1.0 graph placement policy, frozen for inference."""
import math
from pathlib import Path
import torch
from torch import nn
from safetensors.torch import load_file
class GraphPolicy(nn.Module):
def __init__(self,width=48,layers=3):
super().__init__(); self.node=nn.Linear(3,width); self.msg=nn.ModuleList(nn.Sequential(nn.Linear(width+1,width),nn.SiLU(),nn.Linear(width,width)) for _ in range(layers)); self.up=nn.ModuleList(nn.Sequential(nn.Linear(width*2,width),nn.SiLU(),nn.LayerNorm(width)) for _ in range(layers)); self.start=nn.Linear(width,1); self.query=nn.Linear(width,width); self.key=nn.Linear(width,width); self.bias=nn.Linear(width,1); self.edge_scale=nn.Parameter(torch.tensor(0.5))
def logits(self,sizes,edges,weights):
n=sizes.numel(); e=torch.cat((edges,edges.flip(1)),0); w=torch.cat((weights,weights),0); src,dst=e.unbind(1); w=w/(weights.mean().clamp_min(1e-6) if weights.numel() else 1); deg=torch.zeros(n,device=sizes.device).index_add_(0,dst,w); count=torch.zeros_like(deg).index_add_(0,dst,torch.ones_like(w)); h=self.node(torch.stack((sizes.float()/512,torch.log1p(deg),torch.log1p(count)),1))
for msg,up in zip(self.msg,self.up):
m=msg(torch.cat((h[src],torch.log1p(w)[:,None]),1)); agg=torch.zeros_like(h).index_add_(0,dst,m*w[:,None]); h=h+up(torch.cat((h,agg/deg.clamp_min(1)[:,None]),1))
# Dense pair score for small prototypes; graph messages remain sparse.
affinity=torch.zeros((n,n),device=h.device); affinity.index_put_((e[:,0],e[:,1]),w,accumulate=True)
pair=self.query(h)@self.key(h).T/math.sqrt(h.shape[-1])+self.bias(h).T+self.edge_scale*torch.log1p(affinity)
return self.start(h).squeeze(1),pair
def imitation_loss(self,sizes,edges,weights,teacher):
start,pair=self.logits(sizes,edges,weights); n=teacher.numel(); mask=torch.arange(n,device=teacher.device)[None,:]==teacher[:,None]; used=mask.cumsum(0).bool(); scores=pair[teacher[:-1]].masked_fill(used[:-1],-1e9)
return (nn.functional.cross_entropy(start[None],teacher[:1])+nn.functional.cross_entropy(scores,teacher[1:]))/2
@torch.no_grad()
def decode(self,sizes,edges,weights,count=1,seed=0,noise=0.):
start,pair=self.logits(sizes,edges,weights); n=start.numel(); device=start.device; g=torch.Generator(device=device).manual_seed(seed); used=torch.zeros((count,n),device=device,dtype=torch.bool); order=[]
for i in range(n):
logits=start[None,:].expand(count,-1) if i==0 else pair[order[-1]]
if noise:
u=torch.rand(logits.shape,generator=g,device=device).clamp(1e-6,1-1e-6); perturb=-torch.log(-torch.log(u))*noise; perturb[0]=0; logits=logits+perturb
j=logits.masked_fill(used,-torch.inf).argmax(1); order.append(j); used.scatter_(1,j[:,None],True)
return torch.stack(order,1)
def load_model(path=None, device="cpu"):
root = Path(path) if path is not None else Path(__file__).resolve().parent
config = __import__("json").loads((root / "config.json").read_text(encoding="utf-8"))
model = GraphPolicy(config["width"], config["layers"])
model.load_state_dict(load_file(str(root / "model.safetensors"), device="cpu"), strict=True)
return model.to(device).eval()
@torch.inference_mode()
def predict_order(model, sizes, edges, weights, *, candidates=1, seed=0, noise=0.0):
"""Return [candidates, N] permutations for one bounded graph (N <= 24)."""
device = next(model.parameters()).device
sizes = torch.as_tensor(sizes, dtype=torch.long, device=device)
edges = torch.as_tensor(edges, dtype=torch.long, device=device).reshape(-1, 2)
weights = torch.as_tensor(weights, dtype=torch.float32, device=device)
if sizes.ndim != 1 or not 1 <= sizes.numel() <= 24:
raise ValueError("Expected 1..24 objects; use the NeuroLD hierarchy for larger graphs")
if weights.shape != (edges.shape[0],) or not bool((sizes > 0).all()):
raise ValueError("Invalid sizes/edges/weights")
if edges.numel() and not bool(((edges >= 0) & (edges < sizes.numel())).all()):
raise ValueError("Edge endpoint outside graph")
if not bool(torch.isfinite(weights).all()) or not bool((weights >= 0).all()):
raise ValueError("Weights must be finite and nonnegative")
if candidates < 1:
raise ValueError("candidates must be positive")
return model.decode(sizes, edges, weights, candidates, seed, noise)
|