"""Optional native interpreter generated from the discovered tensor certificate. Compilation is an explicit one-time cost. The portable NumPy interpreter remains available; this backend does not change the declared arithmetic algorithms. """ from __future__ import annotations import ctypes import json from pathlib import Path import shutil import subprocess import sys import time import numpy as np from arithmetic import Kernel, P, validate from synthesis import verify_tensor, digest TEMPLATE = r''' #include #include #include #include #include #include using I=long long; static const I P=65537; static const int A[3][2]=@@A@@; static const int B[3][2]=@@B@@; static const int C[3][3]=@@C@@; static const int IA=@@IA@@, OA=@@OA@@; static I mod(I x){x%=P;return x<0?x+P:x;} struct Plan{I mul,add;int split;}; static std::map,Plan> cache; static Plan plan(int n,int m,int d){ auto key=std::make_tuple(n,m,d);auto it=cache.find(key); if(it!=cache.end())return it->second; Plan r{I(n)*m,I(n)*m-(n+m-1),0}; if(d>0 && std::min(n,m)>1){ int h=(std::max(n,m)+1)/2;auto q=plan(h,h,d-1); Plan c{3*q.mul,3*q.add+I(IA)*h+I(OA+2)*(2*h-1),1}; if(c.mul+c.add=2*std::min(n,m)){ int half=std::max(n,m)/2;Plan x,y;int extra; if(n>=m){x=plan(half,m,d);y=plan(n-half,m,d);extra=n-half+m-1;} else{x=plan(n,half,d);y=plan(n,m-half,d);extra=n+m-half-1;} Plan rect{x.mul+y.mul,x.add+y.add+extra,2}; if(rect.mul+rect.add=m?h+m-1:n+h-1),l2=(n>=m?n-h+m-1:n+m-h-1); I*left=work;I*right=left+l1;I*next=right+l2; if(n>=m){recurse(a,h,b,m,left,next,depth);recurse(a+h,n-h,b,m,right,next,depth);} else{recurse(a,n,b,h,left,next,depth);recurse(a,n,b+h,m-h,right,next,depth);} std::fill(z,z+n+m-1,0);std::copy(left,left+l1,z); for(int j=0;j8192||m>8192||d<0||d>20)return 1; if(!plan(n,m,d).split){base(a,n,b,m,out);return 0;} // Geometrically shrinking operands bound the arena by 32*n+128. std::vector workspace(32*std::max(n,m)+128); recurse(a,n,b,m,out,workspace.data(),d);return 0; }catch(...){return 2;} } static std::map,std::vector> rootcache; static I fpow(I a,I k,I*counter){I r=1;while(k){if(k&1){r=r*a%P;++counter[1];} k>>=1;if(k){a=a*a%P;++counter[1];}}return r;} static const std::vector& roots(int n,bool inv,I*counter){ auto key=std::make_pair(n,inv);auto it=rootcache.find(key);if(it!=rootcache.end())return it->second; I w=fpow(3,(P-1)/n,counter);if(inv)w=fpow(w,P-2,counter); std::vector r(n/2,1);for(int i=1;i&a,bool inv,I*counter){ int n=a.size();for(int i=1,j=0;i>1;for(;j&bit;bit>>=1)j^=bit;j^=bit;if(i8192||m>8192)return 1; counts[0]=counts[1]=0;counts[2]=1; int len=1,lg=0;while(len aa(len),bb(len);std::copy(a,a+n,aa.begin());std::copy(b,b+m,bb.begin()); transform(aa,false,counts);transform(bb,false,counts); for(int i=0;i= m: x = self._counts(h,m,cap) y = self._counts(n-h,m,cap) else: x = self._counts(n,h,cap) y = self._counts(n,m-h,cap) return cm, ca, 1+x[2]+y[2] h = (max(n,m)+1)//2 _, _, calls = self._counts(h, h, cap-1) return cm, ca, 1+3*calls def mul(self, a, b): a = np.ascontiguousarray(validate(a)) b = np.ascontiguousarray(validate(b)) self.trace[(len(a),len(b))] += 1 out = np.empty(len(a)+len(b)-1, dtype=np.int64) cm, ca, calls = self._counts(len(a),len(b),self.cap) self.meter.mul += cm self.meter.add += ca self.meter.calls += calls self.meter.allocations += len(out) status = self.function(a,len(a),b,len(b),self.cap,out) if status: raise RuntimeError('Native kernel error code %d' % status) return out class NativeNTTKernel: def __init__(self, law, library): from arithmetic import Meter from collections import Counter self.meter = Meter() self.trace = Counter() self.library = ctypes.CDLL(str(library)) self.function = self.library.sorilun_ntt arr = np.ctypeslib.ndpointer(dtype=np.int64, ndim=1, flags='C_CONTIGUOUS') self.function.argtypes = [arr, ctypes.c_int, arr, ctypes.c_int, arr, arr] self.function.restype = ctypes.c_int def mul(self, a, b): a = np.ascontiguousarray(validate(a)) b = np.ascontiguousarray(validate(b)) self.trace[(len(a),len(b))] += 1 out = np.empty(len(a)+len(b)-1, dtype=np.int64) counts = np.zeros(3, dtype=np.int64) status = self.function(a,len(a),b,len(b),out,counts) if status: raise RuntimeError('Native NTT error code %d' % status) self.meter.add += int(counts[0]) self.meter.mul += int(counts[1]) self.meter.calls += int(counts[2]) self.meter.allocations += len(out) return out