File size: 9,865 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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
"""Exact polynomial arithmetic, explicit cost vectors, and certified programs.

The field is F_65537. NumPy computes exact int64 schoolbook convolutions;
the configured size bound prevents integer overflow before modular reduction.
Field-operation counts model arithmetic, not machine instructions or time.
"""
from __future__ import annotations
from dataclasses import dataclass, asdict
from collections import Counter
import numpy as np
from synthesis import verify_tensor, linear_adds, digest

P = 65537
MAX_LENGTH = 8192

@dataclass
class Meter:
    add: int = 0
    mul: int = 0
    calls: int = 0
    plan_states: int = 0
    certificate_ops: int = 0
    allocations: int = 0
    def snapshot(self):
        d = asdict(self)
        d['field_ops'] = self.add + self.mul
        # Declared abstract ledger, not a measured instruction count.
        d['ledger_units'] = (self.add + self.mul + self.calls +
                             32*self.plan_states + self.certificate_ops)
        return d


def validate(a):
    a = np.asarray(a, dtype=np.int64)
    if a.ndim != 1 or len(a) < 1 or len(a) > MAX_LENGTH:
        raise ValueError('Polynomial lengths must be in [1, 8192]')
    if np.any(a < 0) or np.any(a >= P):
        raise ValueError('Coefficients must be canonical residues modulo 65537')
    return a


def base_cost(n, m):
    return n*m, n*m - (n+m-1)


class Kernel:
    """Interprets a finite, proof-carrying, depth-bounded arithmetic program.

    Every available program includes the schoolbook fallback. Selection is by
    exact dense field-operation cost, independent of coefficient values.
    """
    def __init__(self, law, cap=0):
        if type(cap) is not int or not 0 <= cap <= 20:
            raise ValueError('Invalid program depth')
        ok, work = verify_tensor(law)
        if not ok:
            raise ValueError('Rejected unsound bilinear tensor certificate')
        self.law = law
        self.cap = cap
        self.meter = Meter(certificate_ops=work)
        self.plans = {}
        self.trace = Counter()
        self.input_adds = sum(linear_adds(r) for r in law['A']+law['B'])
        self.output_adds = sum(linear_adds(r) for r in law['C'])

    def plan(self, n, m, cap=None):
        cap = self.cap if cap is None else cap
        key = (n, m, cap)
        if key in self.plans:
            return self.plans[key]
        self.meter.plan_states += 1
        bm, ba = base_cost(n, m)
        best = (bm, ba, 0)
        if cap > 0 and max(n, m) > 1 and min(n, m) > 1:
            h = (max(n, m)+1)//2
            cm, ca, _ = self.plan(h, h, cap-1)
            overhead = self.input_adds*h + (self.output_adds+2)*(2*h-1)
            candidate = (3*cm, 3*ca+overhead, 1)
            if candidate[0]+candidate[1] < bm+ba:
                best = candidate
            # A longer operand is split without permuting coefficient order.
            # This repairs the padding penalty on 2:1 Newton-lifting products.
            if max(n, m) >= 2*min(n, m):
                h = max(n, m)//2
                if n >= m:
                    x = self.plan(h, m, cap)
                    y = self.plan(n-h, m, cap)
                    extra = n-h+m-1
                else:
                    x = self.plan(n, h, cap)
                    y = self.plan(n, m-h, cap)
                    extra = n+m-h-1
                rectangular = (x[0]+y[0], x[1]+y[1]+extra, 2)
                if sum(rectangular[:2]) < sum(best[:2]):
                    best = rectangular
        self.plans[key] = best
        return best

    def cost(self, n, m):
        a, b, _ = self.plan(n, m)
        return a+b

    def _lin(self, arrays, row):
        nz = [(a, c) for a, c in zip(arrays, row) if c]
        if not nz:
            return np.zeros(len(arrays[0]), dtype=np.int64)
        a, c = nz[0]
        z = a.copy()
        self.meter.allocations += len(z)
        if c == -1:
            z = (-z) % P
            self.meter.add += len(z)
        for a, c in nz[1:]:
            z = (z + a) % P if c == 1 else (z - a) % P
            self.meter.add += len(z)
        return z

    def _mul(self, a, b, cap):
        n, m = len(a), len(b)
        self.meter.calls += 1
        _, _, split = self.plan(n, m, cap)
        if not split:
            cm, ca = base_cost(n, m)
            self.meter.mul += cm
            self.meter.add += ca
            self.meter.allocations += n+m-1
            # max coefficient sum <= 8192 * 65536**2 < 2**63.
            return np.convolve(a, b) % P
        if split == 2:
            h = max(n, m)//2
            if n >= m:
                left = self._mul(a[:h], b, cap)
                right = self._mul(a[h:], b, cap)
            else:
                left = self._mul(a, b[:h], cap)
                right = self._mul(a, b[h:], cap)
            out = np.zeros(n+m-1, dtype=np.int64)
            out[:len(left)] = left
            out[h:h+len(right)] = (out[h:h+len(right)]+right) % P
            self.meter.add += len(right)
            self.meter.allocations += len(out)
            return out
        h = (max(n, m)+1)//2
        aa = np.pad(a, (0, 2*h-n))
        bb = np.pad(b, (0, 2*h-m))
        av, bv = [aa[:h], aa[h:]], [bb[:h], bb[h:]]
        products = []
        for ar, br in zip(self.law['A'], self.law['B']):
            products.append(self._mul(self._lin(av, ar),
                                      self._lin(bv, br), cap-1))
        c = [self._lin(products, row) for row in self.law['C']]
        out = np.zeros(4*h-1, dtype=np.int64)
        out[:2*h-1] = c[0]
        for k in (1, 2):
            sl = slice(k*h, k*h+2*h-1)
            out[sl] = (out[sl]+c[k]) % P
            self.meter.add += 2*h-1
        self.meter.allocations += len(out)
        return out[:n+m-1]

    def mul(self, a, b):
        a, b = validate(a), validate(b)
        self.trace[(len(a), len(b))] += 1
        return self._mul(a, b, self.cap)

    def program(self, parent=None):
        body = {'schema': 1, 'kind': 'certified_bilinear_envelope',
                'field': P, 'cap': self.cap, 'law': self.law,
                'parent_sha256': parent, 'max_length': MAX_LENGTH}
        return {**body, 'sha256': digest(body)}


def load_program(data):
    if type(data) is not dict:
        raise ValueError('Invalid program envelope')
    body = {k: v for k, v in data.items() if k != 'sha256'}
    if digest(body) != data.get('sha256'):
        raise ValueError('Program integrity check failed')
    if body.get('field') != P or body.get('schema') != 1:
        raise ValueError('Unsupported program contract')
    if body.get('kind') != 'certified_bilinear_envelope':
        raise ValueError('Unsupported program language')
    return Kernel(body['law'], body['cap'])


class NTTKernel:
    """Conventional cached radix-two transform baseline, not a learned program.

    Roots, their construction, and modular inverse powers are charged. All
    transforms use exact field arithmetic. Schoolbook is selected whenever
    its predicted field-operation count is lower than a cached NTT estimate.
    """
    def __init__(self, law):
        self.meter = Meter()
        self.trace = Counter()
        self.roots = {}
        self.base = Kernel(law, 0)

    def _pow(self, a, k):
        y = 1
        while k:
            if k & 1:
                y = y*a % P
                self.meter.mul += 1
            k >>= 1
            if k:
                a = a*a % P
                self.meter.mul += 1
        return y

    def _roots(self, size, inverse):
        key = (size, inverse)
        if key in self.roots:
            return self.roots[key]
        w = self._pow(3, (P-1)//size)
        if inverse:
            w = self._pow(w, P-2)
        r = np.ones(size//2, dtype=np.int64)
        for j in range(1, len(r)):
            r[j] = r[j-1]*w % P
            self.meter.mul += 1
        self.roots[key] = r
        return r

    def _transform(self, a, inverse=False):
        n = len(a)
        bits = n.bit_length()-1
        # Integer indexing work is not included in field operation counts.
        rev = np.array([int(format(i, '0%db' % bits)[::-1], 2)
                        for i in range(n)], dtype=np.int64)
        out = a[rev].copy()
        size = 2
        while size <= n:
            r = self._roots(size, inverse)
            view = out.reshape(-1, size)
            left = view[:, :size//2].copy()
            right = view[:, size//2:]*r % P
            view[:, :size//2] = (left+right) % P
            view[:, size//2:] = (left-right) % P
            self.meter.mul += n//2
            self.meter.add += n
            size *= 2
        if inverse:
            inv = self._pow(n, P-2)
            out = out*inv % P
            self.meter.mul += n
        self.meter.allocations += n
        return out

    def mul(self, a, b):
        a, b = validate(a), validate(b)
        nout = len(a)+len(b)-1
        n = 1 << (nout-1).bit_length()
        if n > P-1:
            raise ValueError('Transform exceeds field root-of-unity contract')
        self.trace[(len(a), len(b))] += 1
        self.meter.calls += 1
        bm, ba = base_cost(len(a), len(b))
        estimate = (9*n*(n.bit_length()-1))//2 + 2*n
        if bm+ba <= estimate:
            self.meter.mul += bm
            self.meter.add += ba
            return np.convolve(a, b) % P
        aa = np.pad(a, (0, n-len(a)))
        bb = np.pad(b, (0, n-len(b)))
        c = self._transform(aa)*self._transform(bb) % P
        self.meter.mul += n
        return self._transform(c, True)[:nout]


def inv_scalar(x, backend):
    if not x % P:
        raise ValueError('Constant term is not a unit')
    k, a, out = P-2, int(x), 1
    while k:
        if k & 1:
            out = out*a % P
            backend.meter.mul += 1
        k >>= 1
        if k:
            a = a*a % P
            backend.meter.mul += 1
    return out