"""Estimated factorial worlds and reusable probability operations on CUDA. The hypothesis space is a Cartesian product of author-defined condition states. Mean effects share data across bindings. Full hypotheses, including unseen bindings, are materialized only for inference and never used as fit targets. """ from __future__ import annotations import math import torch from torch import nn from torch.nn.functional import one_hot def hypotheses(sizes,device): return torch.cartesian_prod(*[torch.arange(k,device=device) for k in sizes]).reshape(-1,len(sizes)) def design(h,sizes,full=False): pieces=[one_hot(h[:,i],size).double()[:,0 if full else 1:] for i,size in enumerate(sizes)] return torch.cat(pieces,-1) def joint_index(h,sizes): out=h[:,0].clone() for i,size in enumerate(sizes[1:],1):out=out*size+h[:,i] return out def residual_covariance(residual,full=True): n,d=residual.shape;cov=residual.T@residual/n diagonal=torch.diag_embed(cov.diagonal()) cov=.5*cov+.5*diagonal if full else diagonal return cov+.05*torch.eye(d,device=residual.device,dtype=residual.dtype) def ridge_fit(x,h,sizes,ridge=8.): z=torch.cat((torch.ones((len(h),1),device=x.device,dtype=x.dtype),design(h,sizes,True)),-1) penalty=torch.eye(z.shape[1],device=x.device,dtype=x.dtype)*ridge;penalty[0,0]=.01 inverse=torch.linalg.inv(z.T@z+penalty);weights=inverse@z.T@x leverage=(z@inverse*z).sum(-1) loo=(x-z@weights)/(1-leverage).clamp_min(.05)[:,None] grid=hypotheses(sizes,x.device) zg=torch.cat((torch.ones((len(grid),1),device=x.device,dtype=x.dtype),design(grid,sizes,True)),-1) return zg@weights,loo,weights class Decoder(nn.Module): def __init__(self,inputs,outputs,device,budget=20000): super().__init__();width=(budget-outputs)//(inputs+1+outputs) self.net=nn.Sequential(nn.Linear(inputs,width,device=device),nn.SiLU(),nn.Linear(width,outputs,device=device)) assert sum(p.numel() for p in self.parameters())<=budget def forward(self,x):return self.net(x) def neural_predict(x,encoding,grid,seed,steps=400): # Explicitly no pretrained backbone or CPU model is constructed. torch.cuda.manual_seed(seed);net=Decoder(encoding.shape[1],x.shape[1],x.device) opt=torch.optim.AdamW(net.parameters(),lr=.003,weight_decay=.01) inp=encoding.float();target=x.float() with torch.enable_grad(): for _ in range(steps): opt.zero_grad(set_to_none=True);loss=(net(inp)-target).square().mean();loss.backward();opt.step() with torch.no_grad():prediction=net(grid.float()).double() count=sum(p.numel() for p in net.parameters()) assert all(p.device.type=='cuda' and p.requires_grad for p in net.parameters()) return prediction,net.state_dict(),count,float(loss.detach()) def world_fit(x,h,sizes,kind='additive_full',seed=20751,steps=400): assert x.device.type=='cuda';grid=hypotheses(sizes,x.device);total=len(grid) if kind.startswith('additive'): mean,residual,weights=ridge_fit(x,h,sizes) params=weights.numel();checkpoint=dict(weights=weights);adaptations=1 elif kind in ('factorized_neural','joint_neural'): if kind=='factorized_neural': encode=design(h,sizes,True);encoded_grid=design(grid,sizes,True) else: encode=one_hot(joint_index(h,sizes),total).double();encoded_grid=torch.eye(total,device=x.device,dtype=x.dtype) mean,checkpoint,params,_=neural_predict(x,encode,encoded_grid,seed,steps) # Four out-of-fitting-fold predictions estimate uncertainty; all work charged. predictions=x.new_zeros(x.shape) fold=torch.arange(len(x),device=x.device)%4 for f in range(4): train=fold!=f;held=fold==f pred,_,_,_=neural_predict(x[train],encode[train],encode[held],seed+101+f,steps) predictions[held]=pred residual=x-predictions;adaptations=5 if kind=='joint_neural': seen=torch.bincount(joint_index(h,sizes),minlength=total)>0 mean=torch.where(seen[:,None],mean,x.mean(0)) elif kind=='joint_gaussian': code=joint_index(h,sizes);counts=torch.bincount(code,minlength=total).double() sums=x.new_zeros((total,x.shape[1])).scatter_add_(0,code[:,None].expand_as(x),x) mean=(sums+2*x.mean(0))/(counts[:,None]+2) # Leave-one-out class means, with a source-global fallback. loo=(sums[code]-x+2*x.mean(0))/(counts[code,None]+1) residual=x-loo;params=mean.numel();checkpoint=dict(mean=mean);adaptations=1 else:raise ValueError(kind) cov=residual_covariance(residual,kind!='additive_diag') return dict(mean=mean.detach(),cov=cov.detach(),prior=x.new_full((total,),1/total), hypotheses=grid,sizes=tuple(sizes),kind=kind,estimated_mean_scalars=params, checkpoint=checkpoint,adaptation_fits=adaptations,neural_parameters=params if 'neural' in kind else 0) def posterior(model,visible,observed): ix=list(observed) if not ix:return model['prior'][None].expand(len(visible),-1) cov=model['cov'][ix][:,ix];chol=torch.linalg.cholesky(cov) delta=visible[:,None,ix]-model['mean'][None,:,ix] white=torch.linalg.solve_triangular(chol,delta.reshape(-1,len(ix)).T,upper=False) mahal=white.square().sum(0).reshape(len(visible),-1) return (model['prior'].log()[None]-.5*mahal).softmax(-1) def topk_credit(prob,true,k=3,tolerance=1e-12): k=min(k,prob.shape[-1]);threshold=prob.topk(k,-1).values[:,-1] above=prob>threshold[:,None]+tolerance;equal=(prob-threshold[:,None]).abs()<=tolerance slots=k-above.sum(-1);credit=slots.to(prob.dtype)/equal.sum(-1).clamp_min(1) target=prob.gather(1,true[:,None]).squeeze(-1) return torch.where(target>threshold+tolerance,1.,torch.where((target-threshold).abs()<=tolerance,credit,0.)) def conditional_channels(model,observed): """Observation shifts shared by every H cancel from query decision value.""" if not observed:return model['mean'],model['cov'].diagonal() ix=list(observed);cov=model['cov'];gain=torch.linalg.solve(cov[ix][:,ix],cov[ix]).T means=model['mean']-model['mean'][:,ix]@gain.T variance=cov.diagonal()-(gain*cov[:,ix]).sum(-1) return means,variance.clamp_min(1e-12)