Fields and vectors¶
- class vfhe.arith.Field(*args, **kwargs)¶
A finite field F_(p^d).
Field(modulus, degree=1, ...)builds a concrete implementation. The first two parameters are the ones every implementation takes:modulus– the prime p.degree– the extension degree d; 1 (the default) is the prime field F_p. Some implementations serve onlydegree=1.
Anything after them is implementation-specific – the extension field, for instance, takes
wdefiningx**degree - w.Left unnamed, the implementation is chosen from the parameters: a
degree-1 modulus above 64 bits that is a pseudo-Mersenne prime thepmfkernels cover resolves topmf; everything else resolves tofield, the extension field over aModulus. Passimplementation=/backend=to name one explicitly; either way the modulus width is checked against the resolved backend’s constraints.Unlike
Ring, the members below are the whole common surface and every implementation carries all of them: the two that exist differ in how an element is stored, not in what a field offers. An implementation may add to it –PseudoMersenneFieldalso serves transform plans and roots of unity – and code that uses such an addition names that class.- prime: int¶
the prime p this field is built over.
- Type:
The characteristic
- degree: int¶
The extension degree d. 1 for a prime field.
dis the short name for the same value, which is what the coefficient kernels are written in terms of.
- zero: FieldElement¶
0, 1 and 2 as elements, built once with the field.
- property order: int¶
The number of elements of the field,
prime**degree.
- property two_adicity: int¶
The largest
kwith2**kdividingprime - 1.A transform over this field needs a primitive 2n-th root of unity, so
log2(n) + 1is at most this. It is 1 for many primes – among them2**61 - 1– and such a field admits no transform of length above 1.
- property exceptional_set_size: int¶
every nonzero difference of two field elements is invertible, so the whole field is exceptional.
- Type:
|A|for any field is its order
- digest() bytes¶
A 32-byte digest of the parameters that fix the arithmetic: the prime, the degree and, for an extension, the constant
wof its defining polynomialx^degree - w. Two fields with equal digests are the same field to a transcript.
- lagrange_interpolate(values, x) FieldElement¶
Evaluate at
xthe polynomial that takes the valuevalues[t]at the integert, fort = 0, 1, ..., kwithk = len(values) - 1.That polynomial is the Lagrange interpolant on the nodes
0, ..., k, of degree at mostk. For example,values = [3, 4, 7]are the values oft^2 + 3at 0, 1 and 2, so atx = 5the result is 28.The Lagrange denominator of node
tisprod_{j != t} (t - j) = (-1)^(k-t) t! (k-t)!. All of them are therefore known from the integerk!, whose inverse is computed moduloprime: no field element is inverted.This definition works for any field. An implementation may replace it with a native one.
Raises ValueError when
valuesis empty, or when the nodes are not distinct in this field (len(values) > prime).- Parameters:
values – the polynomial’s values at
0, 1, ..., k, elements of this field.x – the point to evaluate at, an element of this field.
- digest_elements(elements) bytes¶
The digest of a handful of elements, without building a vector.
Exactly
FieldVector(self, elements).hash(), and so exactly the matching entry ofFieldVector.hash_elements– the same bytes, in index order, one element after another.What it avoids is the vector. A vector of two elements still allocates a plane per coefficient, the pointer table and the struct the kernels read – at a handful of elements that is most of the cost and none of it is hashing. Use it where the elements are already objects and a vector would exist only to be hashed; hash a vector you already have.
- element_from_seed(seed: bytes, index: int) FieldElement¶
Samples the element at position
indexbased onseedandindex. The result, per element, is the same as callingFieldVector.sample_randomfor the entire vector.This is different from
field.element_from_seed(seed, i), which would sample randomness based on theseedonly.
- random_element(seed: bytes | None = None, random: Random | None = None) FieldElement¶
A uniform element of the field.
Deterministic from
seedwhen one is given – the same seed gives the same element on every engine – and expanded from a seed drawn fromrandom(the entropy stream when None) otherwise.
- random_exceptional(seed: bytes | None = None, bound: int | None = None, random: Random | None = None) FieldElement¶
A uniform element of the field’s exceptional set, which for a field is the whole field:
random_element, deterministic fromseedwhen one is given.With
bound, a uniform element of the subset whosedegreecoefficients are integers belowboundinstead (bound^degreeelements; any subset of a field is exceptional), drawn byvfhe.crypto.seededasRing.random_exceptionaldraws its components’ coefficients: withboundthe ring’s smallest prime and the residue field at one of its primes, this is every CRT component there of the ring element from the same seed, so fields of different characteristic read one ring element alike.
- class vfhe.arith.FieldElement(*args, **kwargs)¶
One element of a
Field, in whatever representation the field uses.FieldElement(field, value)builds the field’s own element type: the class comes from the field’s spec, so an element is always matched to its field’s implementation and a caller never names the concrete class.Elements are immutable in use: every operator returns a fresh element. An int on either side of an operator is reduced into the field first, so
element + 3and3 - elementboth work; anything else returns NotImplemented, which is what lets the other operand’s reflected method take its turn –element * vectorreaches the vector.An implementation must provide the arithmetic primitives and
inverse,hashand equality.squareand division have a default here written against those, which an implementation may replace with a cheaper one.Prefer a
FieldVectorwherever the same operation applies to many elements: one call into C rather than n.- square() FieldElement¶
self * self, which an implementation may do cheaper.
- frobenius(k: int = 1) FieldElement¶
self ** (prime ** k): the k-th power of the Frobenius automorphism.It generates the Galois group of the field over its prime subfield, which is cyclic of order
degree, sokmatters only modulodegreeand the identity isk = 0. Over a prime field it is the identity for everyk.Spelled here as the exponentiation it is defined as, one power of the characteristic at a time rather than by raising to
p ** kin one go. The two cost the same – both walkk * log2(p)bits – and this way the exponent stays one word wide however largekis. An implementation that can compute it as the F_p-linear map on coefficients it also is – a permutation of the positions with a constant each – replaces this.
- inverse() FieldElement¶
The multiplicative inverse. Raises ValueError for zero.
- hash() bytes¶
A 32-byte digest of the value.
The leaf digest a Merkle tree over field elements takes. Pinned to the canonical value, so an element digests the same however it was built; host-dependent, so it identifies within one process, not across builds.
- class vfhe.arith.FieldVector(*args, **kwargs)¶
Many elements of one
Field, held together in one buffer.A vector exists because a length-n operation costs one call into C instead of n: the kernels see whole arrays, so they vectorize across elements and the per-element boundary crossing disappears. Prefer it to a Python list of elements wherever the same operation applies to all of them.
FieldVector(field, n)builds n zeros andFieldVector(field, values)builds from a sequence; either way the class comes from the field’s spec, so a vector is always matched to its field’s implementation and a caller never names the concrete class. A field whose implementation has no vector type raises TypeError.An implementation must provide the operations whose cost is the point – elementwise
+ - *, broadcast against a single element,scale,sum, and the movement and encoding it needs. The rest have a default here, written once against those: correct for any implementation, and replaceable by one that can do better.Vectors are mutable through
__setitem__, so they are not hashable;hashis the digest of the contents, as on an element. Every arithmetic operation returns a fresh vector rather than writing into an operand.- to_list() list[FieldElement]¶
The contents as a list of elements, in order.
One call into C for the whole buffer; the per-element cost that remains is building the Python objects.
- copy() FieldVector¶
A fresh vector with the same contents.
- set_uint64(values: array | memoryview, start: int = 0, shift: int = 0, width: int = 64, high: array | memoryview | None = None) None¶
Element
start + ibecomes(v_i >> shift) mod 2^width, for everyi < len(values), in place, wherev_i = values[i] + 2^64 high[i](values[i]withouthigh).valuesandhigharearray('Q')``s (or any buffers of 64-bit unsigned integers) of one length that fits from `start`. With the defaults this loads the integers themselves; with a `shift` and a `width` it loads one bit field of each, such as one base-``2^widthdigit. Needs1 <= width <= 64and0 <= shift < 64, or< 128withhigh.
- set_radix_decomposition(values: array | memoryview, width: int, digits: int, high: array | memoryview | None = None, columns: int = 1) None¶
The base-
2^widthdigits of the integersv_i = values[i] + 2^64 high[i](values[i]withouthigh), least significant first, one block oflen(values)elements per digit: elementj * len(values) + ibecomes(v_i >> (j * width)) mod 2^widthforj < digits, in place. Digits past bit 128 are zero.With
columns, the values are read as a matrix oflen(values) // columnsrows ofcolumnsentries, stored row by row, and every block holds it column by column: elementj * len(values) + k * rows + iis digitjofv_(i * columns + k).valuesandhighare as inset_uint64. Needs1 <= width <= 64,columnsdividinglen(values)anddigits * len(values) <= len(self); the elements past the blocks are left as they are.
- to_uint64() array | None¶
The elements as an
array('Q'), or None when one of them is not an integer below2^64.
- coefficients() list[array]¶
The coordinates of the elements over the prime subfield: over
F_p[x] / (x^d - w), entryiof thej-tharray('Q')is the coefficient ofx^jin elementi, forj < d. Defined for the extension fields of word-sized primes (ExtensionField, includingd = 1).
- set_coefficients(coefficients: Sequence[array | memoryview], start: int = 0) None¶
Element
start + ibecomessum_j (coefficients[j][i] mod p) x^j, for everyibelow the common length of thedbuffers of 64-bit unsigned integers incoefficients(array('Q')buffers, say), which must fit fromstart. The inverse ofcoefficients, with the same domain.
- scale(value, out: FieldVector | None = None) FieldVector¶
Every element multiplied by one element (or int): the broadcast
__mul__under the name that says there is no second vector.
- add(other, out: FieldVector | None = None) FieldVector¶
self + other, intooutwhen given.
- sub(other, out: FieldVector | None = None) FieldVector¶
self - other, intooutwhen given.
- mul(other, out: FieldVector | None = None) FieldVector¶
self * other, intooutwhen given.
- rsub(other, out: FieldVector | None = None) FieldVector¶
other - selffor one elementother, intooutwhen given.Not
subwith the operands swapped: subtraction does not commute, and this is the one kernel for it. Worth a name because the alternative – negate, then add – is two passes where this is one.
- neg(out: FieldVector | None = None) FieldVector¶
-self, intooutwhen given.
- fma(b, c, out: FieldVector | None = None) FieldVector¶
self + b * c, with the product formed and consumed in one pass.The one fused expression worth a primitive, because it is the shape most of them reduce to. A multiply and an add move the product through memory twice and allocate a vector nothing else reads; this does neither.
cis a vector or one element.An implementation without a fused kernel still gives the right answer the long way round, so a caller may always write it.
- sum() FieldElement¶
The sum of every element, as one element.
- inverse() FieldVector¶
The elementwise inverse, by Montgomery’s trick.
One inversion plus three multiplications per element, rather than n inversions: the prefix products are formed, the last is inverted, and a reverse sweep peels each factor back off. Raises ValueError if any element is zero.
- split_even_odd(block: int = 1, out: tuple[FieldVector, FieldVector] | None = None) tuple[FieldVector, FieldVector]¶
The elements at even and at odd positions, as two half vectors: the inverse of
interleave.blockreads the vector as alternating runs of that many elements rather than as single ones: run 0 goes to the first result, run 1 to the second, run 2 to the first again, and so on.block = 1is the plain deinterleave;block = len(self) // 2is the two halves. It must dividelen(self) // 2.
- chunk_length(live: int = 4) int¶
How many elements one window of
chunkscovers.chunksis the usual way to reach this; take it directly to size a scratch vector before the loop starts.- Parameters:
live – How many vectors of this length the sequence has in hand at once – its operands, its result and any scratch.
- Returns:
A multiple of
padding_unit, soviewaccepts it, and never longer than this vector.
- chunks(live: int = 4)¶
(start, length)windows covering this vector, for running a sequence of operations a piece at a time.Use it when several operations run over the same long vectors one after another. Written the direct way, each operation reads the whole vector back from memory before the next one starts; driven through these windows, each piece is loaded once and every operation in the sequence runs on it while it is still in cache.
viewcuts the operands to a window and every operation takes anout=, so the sequence is the same calls in the same order:scratch = FieldVector(field, max(n for _, n in a.chunks())) for start, length in a.chunks(): x, y = a.view(start, length), b.view(start, length) t = scratch.view(0, length) x.sub(y, out=t) y.fma(t, t, out=result.view(start, length))
Windows are only worth taking when the vectors are large enough that the sequence would otherwise stream them from memory repeatedly, so this yields a single window covering the whole vector until they are, and the loop above is then exactly the direct form. That means it is always safe to write; there is no size below which it costs something.
- Parameters:
live – How many vectors of this length the sequence has in hand at once – its operands, its result and any scratch. It sets how wide a window can be, so an underestimate makes them too wide to help.
- Returns:
(start, length)pairs in order, together covering the vector exactly.startand all but the finallengthare multiples ofpadding_unit, soviewaccepts every one of them.
- chain_bytes(live: int = 4) int¶
How many bytes a sequence holding
livevectors of this length touches in total.What decides whether
chunkssplits into windows, and the figure to compare againstlast_level_cache_byteswhen reasoning about a sequence: one vector can sit well inside the cache while the sequence around it does not fit at all.
- property padding_unit: int¶
What
view’sstartandlengthmust be multiples of.The width the implementation’s buffers are padded to – its eltwise kernels’ vector length.
viewstates the rule in terms of it; this is how a caller learns the number, so that code laying a computation out in views can decide where the views can begin rather than guessing a kernel constant.
- view(start: int = 0, length: int | None = None) FieldVector¶
lengthelements fromstart, sharing this vector’s buffers.No copy: the result reads and writes the same memory, so a change through one is visible through the other, and it keeps this vector alive for as long as it lives. That is what lets a cache-blocked algorithm stay in Python – take a view per block and hand it to the same whole-vector operations – where
querywould copy each block.The kernels’ preconditions are what constrain the two arguments, and an implementation states its padding unit:
startmust be a multiple of it, so the view’s buffers are aligned as they were allocated to be, andlengthmust be too unless the view reaches the end of this vector. Writing through a view whose length is not a whole number of units would otherwise reach into the next elements of the parent, which are not the view’s to touch.
- frobenius(k: int = 1) FieldVector¶
FieldElement.frobeniusapplied to every element.An implementation that has the coefficient map replaces this, which is the elementwise spelling of the definition.
- static concat(vectors: list, out: FieldVector | None = None) FieldVector¶
One vector holding every element of
vectors, in order.Reached on the front, so it dispatches to the operands’ own implementation rather than running the generic body below. Without that, the documented spelling
FieldVector.concat(...)would take the Python path even where a kernel exists – the body here is the fallback for an implementation that has none, not the normal route.
- static fma_interleave(a: FieldVector, b: FieldVector, c_even, c_odd, out: FieldVector | None = None) FieldVector¶
Two
fmacalls sharing operands, written straight into one vector:out[2i] = a[i] + b[i] * c_even[i] out[2i + 1] = a[i] + b[i] * c_odd[i]
The result has twice the length of
a.c_evenandc_oddare each a vector ofa’s length or a single element, independently.Doing it in one call rather than as two
fma`s and an `interleavekeeps the two halves out of memory: they are produced and consumed a window at a time, so at large sizes the result is written once rather than the halves being written, read back and written again.Reached on the front, so it dispatches to the operands’ own implementation, for the reason
concatgives.- Parameters:
a – the addend, and the length the operands share.
b – the multiplicand both products share.
c_even – multiplier for the even output positions.
c_odd – multiplier for the odd output positions.
out – where to write, of length
2 * len(a); a new vector when omitted.
- Returns:
out, or the vector allocated for the result.
- static lift_twisted(a, b, twist, out: FieldVector | None = None) FieldVector¶
Two vectors combined through a table, into adjacent pairs:
out[2i] = a[i] + b[i] * twist[i mod len(twist)] out[2i + 1] = a[i] - b[i] * twist[i mod len(twist)]
The inverse move to
fold_twisted. The product is formed once per pair, and a table shorter thana– its length dividinglen(a)– is read cyclically rather than tiled toa’s length.twistis a vector overa’s field or, where the implementation supports it, over its prime subfield (seefold_twisted).Dispatches to the operands’ own implementation, for the reason
concatgives; the body here tiles the table and callsfma_interleavewith it and its negation.
- static interleave(even, odd, out: FieldVector | None = None) FieldVector¶
The vector with
evenat the even positions andoddat the odd ones: the inverse ofsplit_even_odd. Both must have the same length.Dispatches to the operands’ own implementation, for the reason
concatgives.
- query(indices) FieldVector¶
The elements at
indices, gathered into a new vector.indicesis any sequence of ints, negative ones counting from the end.It may instead be a buffer of unsigned 64-bit indices – an
array("Q"), a memoryview cast to one, anything with 8-byte unsigned items – and then nothing is converted or checked per index: the buffer goes to the kernel as it stands and the bound is tested there. That matters once the gather is as long as the vector, where a Python call per index costs many times the gather itself; and a caller gathering the same positions more than once builds the buffer a single time and keeps it.Negative indices cannot be written in that form, so a buffer’s indices must already be in range; one that is not raises
IndexErroras the sequence form does. A buffer of signed items is taken as a plain sequence rather than silently read as unsigned.
- reindex(bits, offset: int = 0, out: FieldVector | None = None) FieldVector¶
Read this vector through a map of index bits.
The result has
2^len(bits)elements. Its elementiis elementoffset + sum_j ((i >> j) & 1) * 2^bits[j]of this vector, where the sum skips thejwithbits[j]None: bitjofiis then ignored. For example, withbits = [None, 0]andoffset = 2, the result is[v[2], v[2], v[3], v[3]].Read the vectors as multilinear tables, with bit
jof an index as variablej. Then variablejof the result is variablebits[j]of this table, or, wherebits[j]is None, a variable the result does not depend on. The variables of this table thatbitsdoes not name are fixed to their bits inoffset. One call thus restricts a table to 0/1 values of some variables, renames the others and adds new ones.Raises ValueError when
bitshas more than 63 entries or a negative one, whenoffsetis negative, when a source bit (an entry ofbitsthat is not None) appears twice or is set inoffset, or when an index read is past the end. Also raises ValueError whenoutis this vector or does not hold2^len(bits)elements.- Parameters:
bits – one entry per bit of the result’s indices: its source bit, the bit of this vector’s indices it supplies, or None.
offset – the bits of this vector’s indices that are the same for every element read.
out – where to write: a vector of
2^len(bits)elements, not this one. A new vector when omitted.
- Returns:
out, or the vector allocated for the result.
- fold_twisted(untwist: FieldVector, r, out: FieldVector | None = None) FieldVector¶
The fold that undoes
lift_twisted, recombining the two halves with the elementr.This vector is read as adjacent pairs
(u_i, v_i) = (self[2i], self[2i + 1]), and the result has one element per pair:out[i] = (u_i + v_i) / 2 + (u_i - v_i) * untwist[i] * r
If the pairs were made by
lift_twisted(a, b, t), thenu_i + v_i = 2 a[i]andu_i - v_i = 2 b[i] t[i]; so withuntwist = 1 / (2 t)the result isa + r * b. The result and the table are half this vector’s length. The field’s characteristic must be odd, so that 2 is invertible.Over an extension field the table may also be a vector over the prime subfield – the degree-1 field with the same prime – and its product with
ris then one prime-field multiply per coefficient plane.mul,fmaandlift_twistedtake such a table the same way.- Parameters:
untwist – the per-position table;
1 / (2 t)undoes a lift with tablet.r – the element the halves are recombined with.
out – where to write, of half this length; a new vector when omitted.
- Returns:
out, or the vector allocated for the result.
- fold_twisted_blocks(untwist: FieldVector, r: FieldVector, out: FieldVector | None = None) FieldVector¶
fold_twistedapplied tocount = len(r)vectors at once, all with the same table and each with its own element.This vector holds the
countvectors end to end,2melements each, and the result holds their folds end to end,melements each: blockbof the result isself[2bm : 2(b + 1)m].fold_twisted(untwist, r[b]). The table may be over the prime subfield, as forfold_twisted.- Parameters:
untwist – the table every block is folded with,
mlong.r – the element each block is recombined with, one per block.
out – where to write, of half this length; a new vector when omitted.
- Returns:
out, or the vector allocated for the result.
- fold(r, block: int = 1) FieldVector¶
even + r * (odd - even)over adjacent pairs, half the length.Position
iof the result isself[2i] + r * (self[2i+1] - self[2i]): the interpolation that binds the low variable of a multilinear table tor.ris one element (or an int). Requires an even length.blockmoves the pair partnerblockpositions away instead of one, pairing the runssplit_even_oddsplits on:block = 1binds the low variable of a table andblock = len(self) // 2the high one, with the positions in between reached by the powers of two between. The result is in the same order either way – the bound variable’s index is the one that disappears.
- fold_inner_products(other: FieldVector) tuple¶
The inner product of the two vectors folded at
t, fort= 0, 1 and 2, as three elements.With
(u_i, v_i)the adjacent pairs of this vector and(x_i, y_i)those ofother, this is the quadratic:q(t) = sum_i (u_i + t (v_i - u_i)) (x_i + t (y_i - x_i))
at those three points:
q(t)is the inner product ofself.fold(t)andother.fold(t). Both vectors have the same even length; they may be the same vector.An implementation with a kernel reads each vector once and allocates nothing; the body here splits both vectors and runs the products and sums as whole-vector operations.
- fold_and_inner_products(other: FieldVector, r: FieldElement | int) tuple¶
(a, b, sums)witha = self.fold(r),b = other.fold(r)andsums = a.fold_inner_products(b).Both vectors have the same length, a multiple of 4, so that the folds have an even length. An implementation with a kernel reads each vector once, writing the folds and summing their pairs in the same pass; the body here makes the three calls.
- static fold_product_sums(tables: list, sums: list, nodes: int, weights: FieldVector | None = None) list[tuple]¶
Weighted sums of signed products of the tables folded at
t= 0 ..nodes - 1.With
(u_ji, v_ji)the adjacent pairs oftables[j]andf_ji(t) = u_ji + t (v_ji - u_ji)its fold att, each entry ofsumsis a list of signed products(sign, factors),sign1 or -1 andfactorsa nonempty tuple of indices intotables, and stands for the polynomial:S(t) = sum_i w_i sum_(sign, factors) sign * prod_(j in factors) f_ji(t)
with
w_i = weights[i], or 1 withoutweights. Returns(S(0), ..., S(nodes - 1))for each entry. The tables have one even length2mandweightshasmelements; an index may appear in several products, and more than once in one.Reached on the front, it dispatches to the tables’ own implementation; the body here runs it as whole-vector operations, a fixed number of them per table, product and node.
- static fold_and_product_sums(tables: list, r: FieldElement | int, sums: list, nodes: int, weights: FieldVector | None = None) tuple¶
(folded, sums)withfolded = [t.fold(r) for t in tables]andsums = FieldVector.fold_product_sums(folded, sums, nodes, weights).The tables have one length, a multiple of 4, so that the folds have an even length
2m, andweightshasmelements. An implementation with a kernel reads each table once, writing the folds and summing their pairs in the same pass; the body here makes the calls.
- sample_random(seed: bytes, start: int = 0) None¶
Overwrite every element with a uniform one, in place.
A pure function of
seed: the same seed fills the same vector on every engine.startfills from that position of the same sequence rather than from its beginning, so a window of a long vector can be built on its own – positionjhere is positionstart + jof the sequence a vector filled from 0 would hold, andField.element_from_seedis the single-position form of the same definition.
- sample_random_at(seed: bytes, indices) None¶
Overwrite every element with the seeded one at the matching entry of
indices, in place.The same sequence
sample_randomfills from, read at scattered positions rather than a contiguous window: entrykbecomes what positionindices[k]of that sequence holds, which is whatField.element_from_seedreturns for it. Positions may repeat and need not be sorted, and they are positions in the sequence, not in this vector – there is no upper bound on them.indicesmust be as long as this vector.indicestakes the formsquerydoes, a buffer of unsigned 64-bit values included, and for the same reason: the point of this over a call per position is that nothing happens per position outside C.
- hash() bytes¶
A 32-byte digest of the whole vector’s contents.
- digest() bytes¶
A 32-byte digest of the vector: its
hashunder a tag of its own, so that a vector of one element does not digest like that element.
- hash_elements(group: int = 1, stride: int = 1) memoryview¶
One digest per window of elements, packed: the leaves a Merkle tree over this vector takes.
A window is a contiguous run: window
kcovers elementsk * stridethroughk * stride + group - 1, in index order, and only whole windows count. Sostrideis the distance between one window’s start and the next –group == stridetiles the vector, a largerstrideleaves gaps, a smaller one overlaps.The digests come back packed: 32 bytes per window in window order, empty when no whole window fits, so window
kisdigests[32 * k : 32 * (k + 1)]. That is the layout the kernel writes and the layout a tree builder or a transcript reads, so neither end has to slice. A caller that wants an object per window can cut them out, but at a long vector’s window count that is the expensive form and should be its own decision rather than the default.The return is a read-only memoryview of the kernel’s own buffer, not a copy of it: it compares, slices, joins and converts like
bytes, andffi.from_bufferhands it back to C without copying, so a long vector’s digests reach a Merkle tree without ever being duplicated. It keeps the C allocation alive for as long as it lives.bytes(digests)is the copy, when a caller wants one – and it is what a caller needs to hash the digests or key a dict by them, which a view over mutable storage cannot do.A gather is the other shape and is
hash_fibers, not this with different arguments: neither is a special case of the other, which is why they are two names.- Parameters:
group – How many consecutive elements go into each digest.
stride – Distance between the starts of consecutive windows.
- hash_fibers(group: int = 1, stride: int = 1) memoryview¶
One digest per fiber: the gather
hash_elementscannot do.Fiber
kcovers thegroupelements atk,k + stride,k + 2 * stride, … There arestridefibers and together they cover the firstgroup * strideelements, so a vector read asgroupruns ofstridegets one digest per position across all of the runs.Neither window shape is the other with different arguments:
hash_elementsdigests a contiguous run, this digests a gather. A caller whose digest spans positions rather than a run needs this one, and without it the spacing would have to be built into the layout instead. Requiresgroup * stride <= len(self); yields nothing otherwise.Packed as
hash_elementsis, and a read-only view for the same reasons: 32 bytes per fiber, fiberkatdigests[32 * k : 32 * (k + 1)].An implementation without a kernel gathers each fiber and hashes it, which is the same digest one call at a time.
- class vfhe.arith.ExtensionField(*args, **kwargs)¶
F_(p^d) as F_p[x]/(x^d - w), with scalar 64-bit coefficient kernels.
Build F_(modulus^degree) with defining polynomial
x^degree - w.modulusmust be prime, and a composite one is rejected (checked withnumber_theory.is_prime).wmust makex^degree - wirreducible over F_modulus, which is the caller’s responsibility – it is not verified here. Fordegree=1no defining polynomial exists andwis ignored; for higher degrees it is required.- zero: ExtensionFieldElement¶
0, 1 and 2 as elements, built once with the field;
inv_twois the inverse oftwo, which halving needs on every call.
- lagrange_interpolate(values, x) ExtensionFieldElement¶
Field.lagrange_interpolate, computed in one native call (field_ext_lagrange_interpolate) for up toARITH_LAGRANGE_MAX_VALUESvalues, and by the generic definition for more.
- property degree: int¶
The extension degree.
dis the same value under the short name the coefficient kernels are written in terms of.
- property order: int¶
The number of elements of the field,
prime**degree.
- property two_adicity: int¶
The largest
kwith2^kdividingp - 1.A transform over this field’s coefficient planes needs a primitive 2n-th root of unity in F_p, so
log2(n) + 1at most this. It is 1 for many primes – among them2^61 - 1– and such a field admits no transform of length above 1.
- root_subfield_degree(n: int) int¶
The degree of the smallest subfield holding a primitive 2n-th root of unity: the least k with
p**k == 1 (mod 2n).Not a choice – every primitive 2n-th root generates that same subfield, so a transform whose evaluation domain must avoid F_p needs this above 1, and one that must avoid every proper subfield needs it to equal
degree. The prime is what decides it, not the root.
- root_of_unity(n: int, domain: str = 'auto') ExtensionFieldElement¶
A primitive 2n-th root of unity, i.e. an element with
psi ** n == -1.domainsays where it must live:'base'for F_p,'extension'for outside it,'auto'(the default) for whichever exists, base first. A base-domain root is the one arith’s own transform plan chose, so the two agree; an extension one is deterministic in(p, d, w, n), so the same field gives the same root on every run and engine.Raises ValueError when the requested domain has no such element –
root_subfield_degreeis what predicts that.
- ntt_points(root: int, n: int) Any¶
The points a length-
nnegacyclic transform atrootevaluates at, in the transform’s own output order.Position
iholdsroot ** (2 * r(i) + 1), whererreverses thelog2(n)index bits – the permutation the transform leaves in its output, so afterExtensionFieldNTT.forwardpositioniof a block holds the polynomial’s value at entryiof this table.Under that reversal the entries are consecutive odd powers of
root, so one pass of multiplications produces the whole table where writing the definition out is a modular exponentiation per entry.rootis a scalar of F_p.
- ntt_plan(n: int, domain: str = 'auto') Any¶
The negacyclic transform of length
nover this field, one per length and domain.domainsays where the root of unity lives and therefore which of the two implementations runs;'auto'takes the base domain wherever it exists, that being about 3x the faster. SeeExtensionFieldNTTfor the basis, the output order, and the batch layout – which is not the same for the two domains.
- digest_elements(elements) bytes¶
Field.digest_elements, which documents the operation.An element already holds its d coefficients contiguously, and a vector’s digest is those coefficients one element after another – so the bytes the hash covers can be laid out directly and handed to the single-element kernel with a width of
count * d. No vector, and one buffer instead of a plane apiece.
- element_from_seed(seed: bytes, index: int) ExtensionFieldElement¶
Samples the element at position
indexbased onseedandindex. The result, per element, is the same as callingFieldVector.sample_randomfor the entire vector.
- spec: Spec = Spec(implementation='field', backend='scalar', parent_cls=<class 'vfhe.arith.impl.field.field.ExtensionField'>, element_cls=<class 'vfhe.arith.impl.field.field.ExtensionFieldElement'>, vector_cls=<class 'vfhe.arith.impl.field.vector.ExtensionFieldVector'>, capabilities=<Capability.CORE|SAMPLING|EXACT|DOMAINS_COINCIDE: 57>, constraints=Constraints(max_prime_bits=62, min_transform_length=None), rank=0)¶
The (implementation, backend) this parent was built for.
- class vfhe.arith.ExtensionFieldElement(*args, **kwargs)¶
One element of an
ExtensionField: d coefficients over F_p.Build an element of
field.valueis a list of up to d coefficients, low degree first; an int, taken as the constant coefficient; a nativeuint64_t[d]to adopt; or None for zero.- field: ExtensionField¶
The parent, whose
d,wand native modulus the kernels below read.
- value: Any¶
The d coefficients, low degree first, as a native
uint64_t[d].
- frobenius(k: int = 1) ExtensionFieldElement¶
self ** (p ** k), as the coefficient map it is.A permutation of the d coefficient positions with one constant each, derived from
(p, d, w)– not the exponentiationFieldElement.frobeniusdefines it as.kcounts modulo d, the order of the group.
- inverse() ExtensionFieldElement¶
The multiplicative inverse. Raises ValueError for zero.
- hash() bytes¶
A 32-byte digest of the value.
The leaf digest a Merkle tree over field elements takes. Pinned to the canonical value, so an element digests the same however it was built; host-dependent, so it identifies within one process, not across builds.
- class vfhe.arith.ExtensionFieldVector(*args, **kwargs)¶
n elements of one
ExtensionField, held in d coefficient planes.Build from a length, or from a sequence of values.
An int allocates that many zeros. A sequence builds one element per entry, each accepted in the forms
ExtensionFieldElementtakes: an element of the same field, an int, or a list of up to d coefficients.- field: ExtensionField¶
The parent every element belongs to.
- to_list() list[ExtensionFieldElement]¶
Every element, in index order.
- copy() ExtensionFieldVector¶
An independent vector with the same contents.
- set_uint64(values: array | memoryview, start: int = 0, shift: int = 0, width: int = 64, high: array | memoryview | None = None) None¶
See
FieldVector.set_uint64; one call for all the values.
- to_uint64() array | None¶
See
FieldVector.to_uint64; one call for the whole vector.
- coefficients() list[array]¶
See
FieldVector.coefficients; one copy per coefficient.
- set_coefficients(coefficients: Sequence[array | memoryview], start: int = 0) None¶
See
FieldVector.set_coefficients; one call per coefficient.
- add(other, out=None) ExtensionFieldVector¶
self + otherintooutwhen given –__add__with a destination.
- sub(other, out=None) ExtensionFieldVector¶
self - otherintooutwhen given.
- mul(other, out=None) ExtensionFieldVector¶
self * otherintooutwhen given.
- rsub(other, out=None) ExtensionFieldVector¶
other - selffor one elementother, in one pass.
- neg(out=None) ExtensionFieldVector¶
-selfintooutwhen given.
- fma(b, c, out=None) ExtensionFieldVector¶
self + b * c, the product formed and consumed in one pass.Four streams through memory rather than the six a multiply and an add take, and no intermediate vector at all.
cis a vector or one element; withoutandviewit is what makes a chunked expression allocation-free.
- scale(value, out=None) ExtensionFieldVector¶
Every element multiplied by one field element, into
outwhen given.
- sum() ExtensionFieldElement¶
The sum of every element; zero for an empty vector.
- inverse() ExtensionFieldVector¶
The elementwise inverse, by Montgomery’s trick.
One inversion and three multiplications per element rather than n inversions. Raises ValueError if any element is zero.
- split_even_odd(block: int = 1, out: tuple[ExtensionFieldVector, ExtensionFieldVector] | None = None) tuple[ExtensionFieldVector, ExtensionFieldVector]¶
Deinterleave into the even-indexed and odd-indexed halves.
Requires an even length; each half holds n / 2 elements.
blockdeinterleaves runs of that many elements instead of single ones.
- fold_twisted(untwist, r, out=None) ExtensionFieldVector¶
FieldVector.fold_twisted, which documents the operation, computed by the native kernelfield_vec_fold_twistedin one call.untwistmay be a vector over this field or over its prime subfield.
- fold_twisted_blocks(untwist, r, out=None) ExtensionFieldVector¶
FieldVector.fold_twisted_blocks, which documents the operation, computed by the native kernelfield_vec_fold_twisted_blocksin one call.untwistmay be a vector over this field or over its prime subfield;ris a vector over this field.
- static fma_interleave(a, b, c_even, c_odd, out=None) ExtensionFieldVector¶
a + b * c_evenanda + b * c_odd, interleaved into one vector.
- static lift_twisted(a, b, twist, out=None) ExtensionFieldVector¶
FieldVector.lift_twisted, which documents the operation, computed by the native kernelfield_vec_lift_twistedin one call. The kernel forms each product once per pair, reads a short table cyclically without copying it, and writes each pair while it is still in cache.twistmay be a vector over this field or over its prime subfield.
- static interleave(even, odd, out=None) ExtensionFieldVector¶
Even positions from
even, odd fromodd: the inverse ofsplit_even_odd.
- static concat(vectors: list, out=None) ExtensionFieldVector¶
One vector holding every element of
vectors, in order.
- query(indices) ExtensionFieldVector¶
The elements at
indices, gathered, asFieldVector.querydocuments.
- reindex(bits, offset: int = 0, out=None) ExtensionFieldVector¶
Read this vector through a map of index bits, as
FieldVector.reindexdocuments, in one native pass.
- fold(r, block: int = 1) ExtensionFieldVector¶
lo + r * (hi - lo)per pair, in one kernel pass.The pair partner sits
blockpositions away – adjacent by default, the two halves atblock = n // 2.
- fold_inner_products(other: FieldVector) tuple¶
Compute
FieldVector.fold_inner_products(documented there) with the native kernelfield_vec_fold_inner_products, in one pass over both vectors.A field of degree above
FIELD_FOLD_MAX_DEGREEtakes the front’s whole-vector body instead.
- fold_and_inner_products(other: FieldVector, r: FieldElement | int) tuple¶
Compute
FieldVector.fold_and_inner_products(documented there) with the native kernelfield_vec_fold_and_inner_products, in one pass over both vectors.A field of degree above
FIELD_FOLD_MAX_DEGREEmakes the separate calls instead: the two folds, then their inner products.
- static fold_product_sums(tables: list, sums: list, nodes: int, weights: FieldVector | None = None) list[tuple]¶
Compute
FieldVector.fold_product_sums(documented there) with the native kernelfield_vec_fold_product_sums, in one pass over the tables.A shape or a degree past the kernel’s bounds (the
FIELD_FOLD_MAX_*constants ofarith.h), or an empty list of sums, takes the front’s whole-vector body instead.
- static fold_and_product_sums(tables: list, r: FieldElement | int, sums: list, nodes: int, weights: FieldVector | None = None) tuple¶
Compute
FieldVector.fold_and_product_sums(documented there) with the native kernelfield_vec_fold_and_product_sums, in one pass over the tables.A shape or a degree past the kernel’s bounds, or an empty list of sums, makes the separate calls instead: the folds, then their product sums.
- chunk_length(live: int = 4) int¶
FieldVector.chunk_length, with an element taking d words, one per coefficient plane.
- chain_bytes(live: int = 4) int¶
FieldVector.chain_bytes, with an element taking d words, one per coefficient plane.
- property padding_unit: int¶
the unit
FieldVector.padding_unitdescribes.- Type:
The eltwise kernels’ vector width
- view(start: int = 0, length: int | None = None) ExtensionFieldVector¶
lengthelements fromstart, over this vector’s own planes.The padding unit is the eltwise kernels’ vector width, which is what
field_vec_padded_lengthrounds to;FieldVector.viewstates whatstartandlengthmust satisfy against it. The view holds a reference to this vector, so the planes outlive it.
- frobenius(k: int = 1) ExtensionFieldVector¶
ExtensionFieldElement.frobeniuson every element, as the d whole-plane scalings it is.
- sample_random_at(seed: bytes, indices) None¶
FieldVector.sample_random_at, which documents the operation.
- sample_random(seed: bytes, start: int = 0) None¶
Fill with uniform elements drawn from
seed, in place, taking the sequence from positionstart.
- hash() bytes¶
BLAKE3 over every element in index order, 32 bytes.
- hash_elements(group: int = 1, stride: int = 1) memoryview¶
Every window’s digest, packed, as
FieldVector.hash_elementsdocuments.
- hash_fibers(group: int = 1, stride: int = 1) memoryview¶
Every fiber’s digest, packed, as
FieldVector.hash_fibersdocuments.
- class vfhe.arith.PseudoMersenneField(*args, **kwargs)¶
F_p for a pseudo-Mersenne prime, with the kernels in C.
Build the field for an explicit prime.
degreeexists for interface uniformity withField; this implementation serves only prime fields, so any value but 1 is rejected. Rejects a prime whose bit-length has no kernel, and one whose fold constante = c << shiftdoes not fit a 52-bit limb. Primality is checked withnumber_theory.is_prime, a fixed-base probable-prime test – adequate for primes from our own generator, not a defence against a hostilep.- zero: PseudoMersenneElement¶
0, 1 and 2 as elements, built once with the field.
- property order: int¶
The number of elements of the field,
prime**degree.
- property two_adicity: int¶
The largest
kwith2^kdividingp - 1.It bounds the roots of unity available:
root_of_unityexists for orders up to2^k, and a negacyclic transform of lengthnneeds order2n, so the longest is2^(k - 1).
- classmethod generate(bits: int, two_adicity: int = 0, max_two_adicity: int | None = None) PseudoMersenneField¶
Search for a suitable prime of the given bit-length and build the field.
Delegates to
number_theory.gen_pseudo_mersenne_prime, boundingcby52 - shiftbits rather than the default 52 – the real constraint is on the fold constantc << shift, not oncalone.The achievable 2-adicity falls off sharply as
bitsmoves below52 * limbs, because the budget forcis onlybits - 52 * (limbs - 1)bits wide.bitsof 156, 208, 260 and 312 (3 to 6 limbs) are the roomiest choices.
- property d: int¶
this implementation serves prime fields only.
degreeis the same value under the long name.- Type:
The extension degree, 1
- property byte_length: int¶
Bytes in the canonical encoding of an element.
- random(seed: bytes) PseudoMersenneElement¶
Sample a uniform element deterministically from
seed.The same as
random_elementwith a seed, which is the name shared by everyField.
- from_bytes(data: bytes) PseudoMersenneElement¶
Decode a canonical big-endian encoding of exactly
byte_lengthbytes.Rejects anything else: a wrong length, or a value at or above
p, which would give one field element two encodings.
- root_of_unity(log_order: int) PseudoMersenneElement¶
A primitive
2^log_order-th root of unity, memoized.Derived from the least quadratic non-residue
gasg ** ((p - 1) / 2^log_order), so it needs no factorization ofp - 1. Every order’s root comes from that oneg, which ties the roots of successive orders together by squaring:root_of_unity(k - 1) == root_of_unity(k) ** 2. That is the convention arith’s RNS transforms follow, and what lets a fold across transform lengths line up.Note that a generator of the full group F_p^* is NOT offered: verifying one requires factoring
p - 1, which is not feasible at these sizes, and an NTT needs only the 2-primary subgroup. Raises ValueError forlog_orderabovetwo_adicity.
- ntt_plan(n: int) PseudoMersenneNTT¶
The negacyclic transform of length
nover this field, one per length.See
PseudoMersenneNTTfor the basis and output order, and for the lengths a field admits.
- lagrange_interpolate(values, x) PseudoMersenneElement¶
Field.lagrange_interpolate, computed in one native call (pmf_lagrange_interpolate) for up toARITH_LAGRANGE_MAX_VALUESvalues, and by the generic definition for more.
- spec = Spec(implementation='pmf', backend='limb52', parent_cls=<class 'vfhe.arith.impl.pmf.pseudo_mersenne.PseudoMersenneField'>, element_cls=<class 'vfhe.arith.impl.pmf.pseudo_mersenne.PseudoMersenneElement'>, vector_cls=<class 'vfhe.arith.impl.pmf.vector.PseudoMersenneVector'>, capabilities=<Capability.CORE|EXACT|DOMAINS_COINCIDE: 49>, constraints=Constraints(max_prime_bits=312, min_transform_length=None), rank=0)¶
The (implementation, backend) this parent was built for.
- class vfhe.arith.PseudoMersenneElement(*args, **kwargs)¶
An element of a
PseudoMersenneField.Immutable by construction – there are no in-place operators and no setters – which is what makes
__hash__sound.Reduce
valueintofieldand pack it into a fresh buffer.- field: PseudoMersenneField¶
The parent, whose limb layout and native parameters the kernels read.
- square() PseudoMersenneElement¶
Equivalent to
self * self, via a kernel free to specialize.
- inverse() PseudoMersenneElement¶
Return the multiplicative inverse, computed as
a^(p-2)(Fermat) in one C call.Raises ZeroDivisionError for zero.
- to_bytes() bytes¶
Canonical fixed-width big-endian encoding,
byte_lengthbytes.
- to_limbs() list[int]¶
All
_LANESwords, padding included, for tests that pin the layout.
- hash() bytes¶
BLAKE3 over the canonical encoding, 32 bytes.
Hashing the encoding rather than the raw limbs keeps the digest independent of the representation and of the padding lanes, so the two engines cannot disagree.
- digest() bytes¶
The same digest under the name this implementation grew up with.
- class vfhe.arith.PseudoMersenneVector(*args, **kwargs)¶
n elements of one
PseudoMersenneField, held in L limb planes.Build from a length, or from a sequence of values.
An int allocates that many zeros. A sequence builds one element per entry, each either an element of the same field or an int, which is reduced into it.
- field: PseudoMersenneField¶
The parent every element belongs to.
- to_list() list[PseudoMersenneElement]¶
Every element, in index order.
- copy() PseudoMersenneVector¶
An independent vector with the same contents.
- set_uint64(values: array | memoryview, start: int = 0, shift: int = 0, width: int = 64, high: array | memoryview | None = None) None¶
See
FieldVector.set_uint64; one call for all the values.
- set_radix_decomposition(values: array | memoryview, width: int, digits: int, high: array | memoryview | None = None, columns: int = 1) None¶
See
FieldVector.set_radix_decomposition; one call for all the digits.
- to_uint64() array | None¶
See
FieldVector.to_uint64; one call for the whole vector.
- add(other, out=None) PseudoMersenneVector¶
self + otherintooutwhen given.
- sub(other, out=None) PseudoMersenneVector¶
self - otherintooutwhen given.
- mul(other, out=None) PseudoMersenneVector¶
self * otherintooutwhen given.
- rsub(other, out=None) PseudoMersenneVector¶
other - selffor one elementother, in one pass.
- neg(out=None) PseudoMersenneVector¶
-selfintooutwhen given.
- fma(b, c, out=None) PseudoMersenneVector¶
self + b * c, the long way round.There is no fused kernel over this field, so the product is formed into
outand the addend folded in after: the right answer, one pass more than a fused one, and still free of the intermediate a caller would otherwise allocate.Except when
outisself, which is the shape a caller accumulating in place writes. Forming the product there first would overwrite the addend before it is added, so that one case takes a vector for the product – the answer the aliasing contract promises, at the cost the fused path does not pay.
- scale(value, out=None) PseudoMersenneVector¶
Every element multiplied by one field element, into
outwhen given.
- sum() PseudoMersenneElement¶
The sum of every element; zero for an empty vector.
- inverse() PseudoMersenneVector¶
See
FieldVector.inverse; one call for the whole vector.
- split_even_odd(block: int = 1, out: tuple[PseudoMersenneVector, PseudoMersenneVector] | None = None) tuple[PseudoMersenneVector, PseudoMersenneVector]¶
Deinterleave into the even-indexed and odd-indexed halves.
Requires an even length; each half holds n / 2 elements. Runs of
blockelements above 1 are gathered rather than deinterleaved: there is no kernel for that layout here, only for the adjacent one.
- static interleave(even, odd, out=None) PseudoMersenneVector¶
Even positions from
even, odd fromodd: the inverse ofsplit_even_odd.
- static concat(vectors: list, out=None) PseudoMersenneVector¶
One vector holding every element of
vectors, in order.
- query(indices) PseudoMersenneVector¶
The elements at
indices, gathered, asFieldVector.querydocuments.
- reindex(bits, offset: int = 0, out=None) PseudoMersenneVector¶
Read this vector through a map of index bits, as
FieldVector.reindexdocuments, in one native pass.
- fold(r, block: int = 1) PseudoMersenneVector¶
lo + r * (hi - lo)per pair, in one kernel pass.Only the adjacent layout (
block1) has a kernel; a wider block gathers the two operands first and then runs the three whole-vector operationsFieldVector.foldis written with.
- fold_inner_products(other: FieldVector) tuple¶
FieldVector.fold_inner_products, which documents the operation, computed by the native kernelpmf_vec_fold_inner_productsin one pass over both vectors, three products a pair.
- fold_and_inner_products(other: FieldVector, r: FieldElement | int) tuple¶
FieldVector.fold_and_inner_products, which documents the operation, computed by the native kernelpmf_vec_fold_and_inner_productsin one pass over both vectors.
- static fold_product_sums(tables: list, sums: list, nodes: int, weights: FieldVector | None = None) list[tuple]¶
FieldVector.fold_product_sums, which documents the operation, computed by the native kernelpmf_vec_fold_product_sumsin one pass over the tables; a shape past the kernel’s bounds takes the whole-vector body.
- static fold_and_product_sums(tables: list, r: FieldElement | int, sums: list, nodes: int, weights: FieldVector | None = None) tuple¶
FieldVector.fold_and_product_sums, which documents the operation, computed by the native kernelpmf_vec_fold_and_product_sumsin one pass over the tables; a shape past the kernel’s bounds makes the separate calls.
- fold_twisted(untwist: FieldVector, r: FieldElement | int, out: FieldVector | None = None) PseudoMersenneVector¶
FieldVector.fold_twisted, which documents the operation, computed by the native kernelpmf_vec_fold_twistedin one pass, two products a pair.
- static lift_twisted(a: FieldVector, b: FieldVector, twist: FieldVector, out: FieldVector | None = None) PseudoMersenneVector¶
FieldVector.lift_twisted, which documents the operation, computed by the native kernelpmf_vec_lift_twistedin one pass: one product per pair, the table read cyclically in place, each pair written where it belongs.
- chunk_length(live: int = 4) int¶
FieldVector.chunk_length, with an element taking one word per limb plane.
- chain_bytes(live: int = 4) int¶
FieldVector.chain_bytes, with an element taking one word per limb plane.
- property padding_unit: int¶
the unit
FieldVector.padding_unitdescribes.- Type:
The group width
- view(start: int = 0, length: int | None = None) PseudoMersenneVector¶
lengthelements fromstart, over this vector’s own planes.The padding unit is the group width
pmf_vec_padded_lengthrounds to;FieldVector.viewstates whatstartandlengthmust satisfy against it. The view holds a reference to this vector, so the planes outlive it.
- sample_random(seed: bytes, start: int = 0) None¶
Fill with uniform elements drawn from
seed, in place.startis replayed rather than seeked: this sampler’s draw stream is walked from the beginning, so a non-zerostartcosts the values before it as well (_sample_random_replayed).
- hash() bytes¶
BLAKE3 over every element’s canonical encoding, in order, 32 bytes.
- hash_elements(group: int = 1, stride: int = 1) memoryview¶
Every window’s digest, packed, as
FieldVector.hash_elementsdocuments.
- class vfhe.arith.PseudoMersenneNTT(field: PseudoMersenneField, n: int)¶
The transform of F_p[X]/(X^n + 1) for one power-of-two
n.Same basis as arith’s RNS transforms. With
psithe primitive 2n-th root of unity inroot_of_unity,forwardof a vector holding the coefficients of P in natural order leaves positionjholdingP(psi ** (2 * brv(j) + 1)), wherebrvreverses thelog2(n)index bits: natural in, bit-reversed out, so positions2iand2i + 1holdP(x)andP(-x).inversetakes that order back to coefficients, 1/n scaling included.The root is
PseudoMersenneField.root_of_unityof order2n. Every order’s root comes from the same generator, so the plans of successive lengths satisfyplan(n // 2).root_of_unity == plan(n).root_of_unity ** 2, the relation a fold across lengths relies on.Plans are cheap to keep and cost
2 * nfield elements of tables;PseudoMersenneField.ntt_planmemoizes one per length.Build the plan for length
noverfield.Raises ValueError unless
nis a power of two no longer than the field allows: a 2n-th root of unity needslog2(n) + 1at mostfield.two_adicity.- root_of_unity: PseudoMersenneElement¶
psi, the primitive 2n-th root of unity the transform evaluates at.
- forward(vector: PseudoMersenneVector, in_place: bool = False, blocks: int = 1) PseudoMersenneVector¶
Coefficients in natural order to evaluations in bit-reversed order.
With
blocksabove 1,vectorholds that many transforms of lengthnend to end (blockbatb * n, the layoutbatch_layoutnames) and each is transformed on its own.Returns a fresh vector unless
in_place, in which casevectoris transformed and returned.
- inverse(vector: PseudoMersenneVector, in_place: bool = False, blocks: int = 1) PseudoMersenneVector¶
Evaluations in bit-reversed order back to coefficients; see
forward.
- encode_blocks(message: PseudoMersenneVector, blocks: int) PseudoMersenneVector¶
The forward transforms of
blocksmessages zero-padded ton.messageholds them interleaved – coefficientiof messagebati * blocks + b– eachlen(message) // blockslong, a power of two dividingn. The result holds the transforms end to end, messageb’s atb * n: what padding each message,pack-ing the batch andforwardwithblocksgive, without the padding or the stages it leaves trivial.
- batch_layout = 'blocks'¶
block
bis thenconsecutive elements atb * n. Named asExtensionFieldNTTnames its own, so a caller can lay out a batch for either plan the same way.- Type:
How a batch of transforms is laid out
- pack(vector: PseudoMersenneVector, blocks: int = 1, out: PseudoMersenneVector | None = None, layout: str = 'blocks') PseudoMersenneVector¶
vector, held inlayout, laid out the way a batchedforwardneeds it.layoutis'blocks'(the default) when each transform’s elements are together, or'interleaved'when elementiof blockbsits ati * blocks + b. From'blocks'there is nothing to do: the input is returned as it is unlessoutis given, in which case it is copied there. From'interleaved'it is a transpose, one pass.
- unpack(vector: PseudoMersenneVector, blocks: int = 1, out: PseudoMersenneVector | None = None, layout: str = 'blocks') PseudoMersenneVector¶
The inverse of
pack: a transformed batch back tolayout.