Datasets:
Formats:
json
Languages:
English
Size:
< 1K
Tags:
recursive-self-improvement
autonomous-learning
formal-power-series
exact-arithmetic
certified-compilation
reproducible-research
File size: 9,388 Bytes
aff9293 | 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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | """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 <vector>
#include <array>
#include <map>
#include <tuple>
#include <algorithm>
#include <cstdint>
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<std::tuple<int,int,int>,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<r.mul+r.add)r=c;
if(std::max(n,m)>=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<r.mul+r.add)r=rect;
}
}
cache[key]=r;return r;
}
static void base(const I*a,int n,const I*b,int m,I*z){
for(int t=0;t<n+m-1;++t){
int lo=std::max(0,t-m+1),hi=std::min(n-1,t);
I s=a[lo]*b[t-lo];for(int j=lo+1;j<=hi;++j)s+=a[j]*b[t-j];z[t]=mod(s);
}
}
static void recurse(const I*a,int n,const I*b,int m,I*z,I*work,int depth){
auto q=plan(n,m,depth);
if(!q.split){base(a,n,b,m,z);return;}
if(q.split==2){
int h=std::max(n,m)/2;
int l1=(n>=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;j<l2;++j)z[h+j]=mod(z[h+j]+right[j]);return;
}
int h=(std::max(n,m)+1)/2,l=2*h-1;
I*aa=work;I*bb=aa+2*h;I*left=bb+2*h;I*right=left+h;
I*q0=right+h;I*q1=q0+l;I*q2=q1+l;I*next=q2+l;
std::fill(aa,aa+2*h,0);std::fill(bb,bb+2*h,0);
std::copy(a,a+n,aa);std::copy(b,b+m,bb);
I*products[3]={q0,q1,q2};
for(int t=0;t<3;++t){
for(int i=0;i<h;++i){left[i]=mod(A[t][0]*aa[i]+A[t][1]*aa[h+i]);
right[i]=mod(B[t][0]*bb[i]+B[t][1]*bb[h+i]);}
recurse(left,h,right,h,products[t],next,depth-1);
}
std::fill(z,z+n+m-1,0);
for(int t=0;t<3;++t)for(int j=0;j<l && t*h+j<n+m-1;++j){
I v=mod(C[t][0]*q0[j]+C[t][1]*q1[j]+C[t][2]*q2[j]);
z[t*h+j]=mod(z[t*h+j]+v);
}
}
extern "C" int sorilun_mul(const I*a,int n,const I*b,int m,int d,I*out){
try{
if(n<1||m<1||n>8192||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<I> 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::pair<int,bool>,std::vector<I>> 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<I>& 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<I> r(n/2,1);for(int i=1;i<n/2;++i){r[i]=r[i-1]*w%P;++counter[1];}
rootcache[key]=r;return rootcache[key];
}
static void transform(std::vector<I>&a,bool inv,I*counter){
int n=a.size();for(int i=1,j=0;i<n;++i){int bit=n>>1;for(;j&bit;bit>>=1)j^=bit;j^=bit;if(i<j)std::swap(a[i],a[j]);}
for(int size=2;size<=n;size<<=1){const auto&r=roots(size,inv,counter);
for(int i=0;i<n;i+=size)for(int j=0;j<size/2;++j){I u=a[i+j],v=a[i+j+size/2]*r[j]%P;
a[i+j]=(u+v)%P;a[i+j+size/2]=mod(u-v);}
counter[0]+=n;counter[1]+=n/2;
}
if(inv){I c=fpow(n,P-2,counter);for(auto&x:a)x=x*c%P;counter[1]+=n;}
}
extern "C" int sorilun_ntt(const I*a,int n,const I*b,int m,I*out,I*counts){
try{
if(n<1||m<1||n>8192||m>8192)return 1;
counts[0]=counts[1]=0;counts[2]=1;
int len=1,lg=0;while(len<n+m-1){len<<=1;++lg;}
I estimate=9LL*len*lg/2+2*len,bmul=I(n)*m,badd=I(n)*m-(n+m-1);
if(bmul+badd<=estimate){base(a,n,b,m,out);counts[0]=badd;counts[1]=bmul;return 0;}
std::vector<I> 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<len;++i)aa[i]=aa[i]*bb[i]%P;counts[1]+=len;
transform(aa,true,counts);std::copy(aa.begin(),aa.begin()+n+m-1,out);return 0;
}catch(...){return 2;}
}
extern "C" void sorilun_clear_cache(){cache.clear();rootcache.clear();}
'''
def _cpp_array(rows):
return '{' + ','.join('{' + ','.join(map(str, r)) + '}' for r in rows) + '}'
def build(law, directory):
if not verify_tensor(law)[0]:
raise ValueError('Cannot generate code from an invalid certificate')
compiler = shutil.which('g++') or shutil.which('clang++')
if not compiler:
return {'available': False, 'reason': 'No C++ compiler', 'wall_seconds': 0}
if sys.platform == 'win32':
return {'available': False, 'reason': 'Use portable Python backend on Windows', 'wall_seconds': 0}
directory = Path(directory)
directory.mkdir(parents=True, exist_ok=True)
k = Kernel(law, 0)
text = TEMPLATE
for key in ('A', 'B', 'C'):
text = text.replace('@@'+key+'@@', _cpp_array(law[key]))
text = text.replace('@@IA@@', str(k.input_adds)).replace('@@OA@@', str(k.output_adds))
source, target = directory/'discovered_kernel.cpp', directory/'discovered_kernel.so'
source.write_text(text)
command = [compiler, '-O3', '-std=c++17', '-fPIC', '-shared', str(source), '-o', str(target)]
start = time.perf_counter()
proc = subprocess.run(command, capture_output=True, text=True, timeout=60)
if proc.returncode:
raise RuntimeError(proc.stderr)
return {'available': True, 'source': str(source), 'library': str(target),
'command': command, 'wall_seconds': time.perf_counter()-start,
'law_sha256': digest(law),
'compiler': subprocess.check_output([compiler, '--version'], text=True).splitlines()[0]}
class NativeKernel(Kernel):
def __init__(self, law, cap, library):
super().__init__(law, cap)
self.library = ctypes.CDLL(str(library))
self.function = self.library.sorilun_mul
arr = np.ctypeslib.ndpointer(dtype=np.int64, ndim=1, flags='C_CONTIGUOUS')
self.function.argtypes = [arr, ctypes.c_int, arr, ctypes.c_int,
ctypes.c_int, arr]
self.function.restype = ctypes.c_int
def _counts(self, n, m, cap):
cm, ca, split = self.plan(n, m, cap)
if not split:
return cm, ca, 1
if split == 2:
h = max(n,m)//2
if n >= 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
|