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 only degree=1.

Anything after them is implementation-specific – the extension field, for instance, takes w defining x**degree - w.

Left unnamed, the implementation is chosen from the parameters: a degree-1 modulus above 64 bits that is a pseudo-Mersenne prime the pmf kernels cover resolves to pmf; everything else resolves to field, the extension field over a Modulus. Pass implementation= / 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 – PseudoMersenneField also 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. d is 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 k with 2**k dividing prime - 1.

A transform over this field needs a primitive 2n-th root of unity, so log2(n) + 1 is at most this. It is 1 for many primes – among them 2**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 w of its defining polynomial x^degree - w. Two fields with equal digests are the same field to a transcript.

lagrange_interpolate(values, x) → FieldElement

Evaluate at x the polynomial that takes the value values[t] at the integer t, for t = 0, 1, ..., k with k = len(values) - 1.

That polynomial is the Lagrange interpolant on the nodes 0, ..., k, of degree at most k. For example, values = [3, 4, 7] are the values of t^2 + 3 at 0, 1 and 2, so at x = 5 the result is 28.

The Lagrange denominator of node t is prod_{j != t} (t - j) = (-1)^(k-t) t! (k-t)!. All of them are therefore known from the integer k!, whose inverse is computed modulo prime: no field element is inverted.

This definition works for any field. An implementation may replace it with a native one.

Raises ValueError when values is 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 of FieldVector.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 index based on seed and index. The result, per element, is the same as calling FieldVector.sample_random for the entire vector.

This is different from field.element_from_seed(seed, i), which would sample randomness based on the seed only.

random_element(seed: bytes | None = None, random: Random | None = None) → FieldElement

A uniform element of the field.

Deterministic from seed when one is given – the same seed gives the same element on every engine – and expanded from a seed drawn from random (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 from seed when one is given.

With bound, a uniform element of the subset whose degree coefficients are integers below bound instead (bound^degree elements; any subset of a field is exceptional), drawn by vfhe.crypto.seeded as Ring.random_exceptional draws its components’ coefficients: with bound the 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 + 3 and 3 - element both work; anything else returns NotImplemented, which is what lets the other operand’s reflected method take its turn – element * vector reaches the vector.

An implementation must provide the arithmetic primitives and inverse, hash and equality. square and division have a default here written against those, which an implementation may replace with a cheaper one.

Prefer a FieldVector wherever the same operation applies to many elements: one call into C rather than n.

field: Field

The parent this element belongs to.

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, so k matters only modulo degree and the identity is k = 0. Over a prime field it is the identity for every k.

Spelled here as the exponentiation it is defined as, one power of the characteristic at a time rather than by raising to p ** k in one go. The two cost the same – both walk k * log2(p) bits – and this way the exponent stays one word wide however large k is. 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.

digest() → bytes

A 32-byte digest of the value: the same bytes as hash.

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 and FieldVector(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; hash is the digest of the contents, as on an element. Every arithmetic operation returns a fresh vector rather than writing into an operand.

field: Field

The parent every element belongs to.

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 + i becomes (v_i >> shift) mod 2^width, for every i < len(values), in place, where v_i = values[i] + 2^64 high[i] (values[i] without high).

values and high are array('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^width digit. Needs 1 <= width <= 64 and 0 <= shift < 64, or < 128 with high.

set_radix_decomposition(values: array | memoryview, width: int, digits: int, high: array | memoryview | None = None, columns: int = 1) → None

The base-2^width digits of the integers v_i = values[i] + 2^64 high[i] (values[i] without high), least significant first, one block of len(values) elements per digit: element j * len(values) + i becomes (v_i >> (j * width)) mod 2^width for j < digits, in place. Digits past bit 128 are zero.

With columns, the values are read as a matrix of len(values) // columns rows of columns entries, stored row by row, and every block holds it column by column: element j * len(values) + k * rows + i is digit j of v_(i * columns + k).

values and high are as in set_uint64. Needs 1 <= width <= 64, columns dividing len(values) and digits * 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 below 2^64.

coefficients() → list[array]

The coordinates of the elements over the prime subfield: over F_p[x] / (x^d - w), entry i of the j-th array('Q') is the coefficient of x^j in element i, for j < d. Defined for the extension fields of word-sized primes (ExtensionField, including d = 1).

set_coefficients(coefficients: Sequence[array | memoryview], start: int = 0) → None

Element start + i becomes sum_j (coefficients[j][i] mod p) x^j, for every i below the common length of the d buffers of 64-bit unsigned integers in coefficients (array('Q') buffers, say), which must fit from start. The inverse of coefficients, 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, into out when given.

sub(other, out: FieldVector | None = None) → FieldVector

self - other, into out when given.

mul(other, out: FieldVector | None = None) → FieldVector

self * other, into out when given.

rsub(other, out: FieldVector | None = None) → FieldVector

other - self for one element other, into out when given.

Not sub with 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, into out when 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. c is 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.

block reads 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 = 1 is the plain deinterleave; block = len(self) // 2 is the two halves. It must divide len(self) // 2.

chunk_length(live: int = 4) → int

How many elements one window of chunks covers.

chunks is 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, so view accepts 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. view cuts the operands to a window and every operation takes an out=, 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. start and all but the final length are multiples of padding_unit, so view accepts every one of them.

chain_bytes(live: int = 4) → int

How many bytes a sequence holding live vectors of this length touches in total.

What decides whether chunks splits into windows, and the figure to compare against last_level_cache_bytes when 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’s start and length must be multiples of.

The width the implementation’s buffers are padded to – its eltwise kernels’ vector length. view states 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

length elements from start, 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 query would copy each block.

The kernels’ preconditions are what constrain the two arguments, and an implementation states its padding unit: start must be a multiple of it, so the view’s buffers are aligned as they were allocated to be, and length must 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.frobenius applied 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 fma calls 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_even and c_odd are each a vector of a’s length or a single element, independently.

Doing it in one call rather than as two fma`s and an `interleave keeps 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 concat gives.

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 than a – its length dividing len(a) – is read cyclically rather than tiled to a’s length. twist is a vector over a’s field or, where the implementation supports it, over its prime subfield (see fold_twisted).

Dispatches to the operands’ own implementation, for the reason concat gives; the body here tiles the table and calls fma_interleave with it and its negation.

static interleave(even, odd, out: FieldVector | None = None) → FieldVector

The vector with even at the even positions and odd at the odd ones: the inverse of split_even_odd. Both must have the same length.

Dispatches to the operands’ own implementation, for the reason concat gives.

query(indices) → FieldVector

The elements at indices, gathered into a new vector.

indices is 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 IndexError as 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 element i is element offset + sum_j ((i >> j) & 1) * 2^bits[j] of this vector, where the sum skips the j with bits[j] None: bit j of i is then ignored. For example, with bits = [None, 0] and offset = 2, the result is [v[2], v[2], v[3], v[3]].

Read the vectors as multilinear tables, with bit j of an index as variable j. Then variable j of the result is variable bits[j] of this table, or, where bits[j] is None, a variable the result does not depend on. The variables of this table that bits does not name are fixed to their bits in offset. One call thus restricts a table to 0/1 values of some variables, renames the others and adds new ones.

Raises ValueError when bits has more than 63 entries or a negative one, when offset is negative, when a source bit (an entry of bits that is not None) appears twice or is set in offset, or when an index read is past the end. Also raises ValueError when out is this vector or does not hold 2^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 element r.

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), then u_i + v_i = 2 a[i] and u_i - v_i = 2 b[i] t[i]; so with untwist = 1 / (2 t) the result is a + 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 r is then one prime-field multiply per coefficient plane. mul, fma and lift_twisted take such a table the same way.

Parameters:
  • untwist – the per-position table; 1 / (2 t) undoes a lift with table t.

  • 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_twisted applied to count = len(r) vectors at once, all with the same table and each with its own element.

This vector holds the count vectors end to end, 2m elements each, and the result holds their folds end to end, m elements each: block b of the result is self[2bm : 2(b + 1)m].fold_twisted(untwist, r[b]). The table may be over the prime subfield, as for fold_twisted.

Parameters:
  • untwist – the table every block is folded with, m long.

  • 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 i of the result is self[2i] + r * (self[2i+1] - self[2i]): the interpolation that binds the low variable of a multilinear table to r. r is one element (or an int). Requires an even length.

block moves the pair partner block positions away instead of one, pairing the runs split_even_odd splits on: block = 1 binds the low variable of a table and block = len(self) // 2 the 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, for t = 0, 1 and 2, as three elements.

With (u_i, v_i) the adjacent pairs of this vector and (x_i, y_i) those of other, 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 of self.fold(t) and other.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) with a = self.fold(r), b = other.fold(r) and sums = 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 of tables[j] and f_ji(t) = u_ji + t (v_ji - u_ji) its fold at t, each entry of sums is a list of signed products (sign, factors), sign 1 or -1 and factors a nonempty tuple of indices into tables, 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 without weights. Returns (S(0), ..., S(nodes - 1)) for each entry. The tables have one even length 2m and weights has m elements; 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) with folded = [t.fold(r) for t in tables] and sums = 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, and weights has m elements. 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.

start fills 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 – position j here is position start + j of the sequence a vector filled from 0 would hold, and Field.element_from_seed is 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_random fills from, read at scattered positions rather than a contiguous window: entry k becomes what position indices[k] of that sequence holds, which is what Field.element_from_seed returns 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. indices must be as long as this vector.

indices takes the forms query does, 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 hash under 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 k covers elements k * stride through k * stride + group - 1, in index order, and only whole windows count. So stride is the distance between one window’s start and the next – group == stride tiles the vector, a larger stride leaves 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 k is digests[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, and ffi.from_buffer hands 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_elements cannot do.

Fiber k covers the group elements at k, k + stride, k + 2 * stride, … There are stride fibers and together they cover the first group * stride elements, so a vector read as group runs of stride gets one digest per position across all of the runs.

Neither window shape is the other with different arguments: hash_elements digests 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. Requires group * stride <= len(self); yields nothing otherwise.

Packed as hash_elements is, and a read-only view for the same reasons: 32 bytes per fiber, fiber k at digests[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.

modulus must be prime, and a composite one is rejected (checked with number_theory.is_prime). w must make x^degree - w irreducible over F_modulus, which is the caller’s responsibility – it is not verified here. For degree=1 no defining polynomial exists and w is ignored; for higher degrees it is required.

zero: ExtensionFieldElement

0, 1 and 2 as elements, built once with the field; inv_two is the inverse of two, 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 to ARITH_LAGRANGE_MAX_VALUES values, and by the generic definition for more.

property degree: int

The extension degree. d is 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 k with 2^k dividing p - 1.

A transform over this field’s coefficient planes needs a primitive 2n-th root of unity in F_p, so log2(n) + 1 at most this. It is 1 for many primes – among them 2^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.

domain says 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_degree is what predicts that.

ntt_points(root: int, n: int) → Any

The points a length-n negacyclic transform at root evaluates at, in the transform’s own output order.

Position i holds root ** (2 * r(i) + 1), where r reverses the log2(n) index bits – the permutation the transform leaves in its output, so after ExtensionFieldNTT.forward position i of a block holds the polynomial’s value at entry i of 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. root is a scalar of F_p.

ntt_plan(n: int, domain: str = 'auto') → Any

The negacyclic transform of length n over this field, one per length and domain.

domain says 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. See ExtensionFieldNTT for 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 index based on seed and index. The result, per element, is the same as calling FieldVector.sample_random for 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.

value is a list of up to d coefficients, low degree first; an int, taken as the constant coefficient; a native uint64_t[d] to adopt; or None for zero.

field: ExtensionField

The parent, whose d, w and 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 exponentiation FieldElement.frobenius defines it as. k counts 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 ExtensionFieldElement takes: 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 + other into out when given – __add__ with a destination.

sub(other, out=None) → ExtensionFieldVector

self - other into out when given.

mul(other, out=None) → ExtensionFieldVector

self * other into out when given.

rsub(other, out=None) → ExtensionFieldVector

other - self for one element other, in one pass.

neg(out=None) → ExtensionFieldVector

-self into out when 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. c is a vector or one element; with out and view it is what makes a chunked expression allocation-free.

scale(value, out=None) → ExtensionFieldVector

Every element multiplied by one field element, into out when 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. block deinterleaves 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 kernel field_vec_fold_twisted in one call. untwist may 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 kernel field_vec_fold_twisted_blocks in one call. untwist may be a vector over this field or over its prime subfield; r is a vector over this field.

static fma_interleave(a, b, c_even, c_odd, out=None) → ExtensionFieldVector

a + b * c_even and a + 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 kernel field_vec_lift_twisted in 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. twist may be a vector over this field or over its prime subfield.

static interleave(even, odd, out=None) → ExtensionFieldVector

Even positions from even, odd from odd: the inverse of split_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, as FieldVector.query documents.

reindex(bits, offset: int = 0, out=None) → ExtensionFieldVector

Read this vector through a map of index bits, as FieldVector.reindex documents, in one native pass.

fold(r, block: int = 1) → ExtensionFieldVector

lo + r * (hi - lo) per pair, in one kernel pass.

The pair partner sits block positions away – adjacent by default, the two halves at block = n // 2.

fold_inner_products(other: FieldVector) → tuple

Compute FieldVector.fold_inner_products (documented there) with the native kernel field_vec_fold_inner_products, in one pass over both vectors.

A field of degree above FIELD_FOLD_MAX_DEGREE takes 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 kernel field_vec_fold_and_inner_products, in one pass over both vectors.

A field of degree above FIELD_FOLD_MAX_DEGREE makes 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 kernel field_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 of arith.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 kernel field_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_unit describes.

Type:

The eltwise kernels’ vector width

view(start: int = 0, length: int | None = None) → ExtensionFieldVector

length elements from start, over this vector’s own planes.

The padding unit is the eltwise kernels’ vector width, which is what field_vec_padded_length rounds to; FieldVector.view states what start and length must satisfy against it. The view holds a reference to this vector, so the planes outlive it.

frobenius(k: int = 1) → ExtensionFieldVector

ExtensionFieldElement.frobenius on 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 position start.

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_elements documents.

hash_fibers(group: int = 1, stride: int = 1) → memoryview

Every fiber’s digest, packed, as FieldVector.hash_fibers documents.

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.

degree exists for interface uniformity with Field; 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 constant e = c << shift does not fit a 52-bit limb. Primality is checked with number_theory.is_prime, a fixed-base probable-prime test – adequate for primes from our own generator, not a defence against a hostile p.

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 k with 2^k dividing p - 1.

It bounds the roots of unity available: root_of_unity exists for orders up to 2^k, and a negacyclic transform of length n needs order 2n, so the longest is 2^(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, bounding c by 52 - shift bits rather than the default 52 – the real constraint is on the fold constant c << shift, not on c alone.

The achievable 2-adicity falls off sharply as bits moves below 52 * limbs, because the budget for c is only bits - 52 * (limbs - 1) bits wide. bits of 156, 208, 260 and 312 (3 to 6 limbs) are the roomiest choices.

property d: int

this implementation serves prime fields only. degree is the same value under the long name.

Type:

The extension degree, 1

property degree: int

The extension degree, 1. See d.

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_element with a seed, which is the name shared by every Field.

from_bytes(data: bytes) → PseudoMersenneElement

Decode a canonical big-endian encoding of exactly byte_length bytes.

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 g as g ** ((p - 1) / 2^log_order), so it needs no factorization of p - 1. Every order’s root comes from that one g, 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 for log_order above two_adicity.

ntt_plan(n: int) → PseudoMersenneNTT

The negacyclic transform of length n over this field, one per length.

See PseudoMersenneNTT for 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 to ARITH_LAGRANGE_MAX_VALUES values, 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 value into field and 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_length bytes.

to_limbs() → list[int]

All _LANES words, 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 + other into out when given.

sub(other, out=None) → PseudoMersenneVector

self - other into out when given.

mul(other, out=None) → PseudoMersenneVector

self * other into out when given.

rsub(other, out=None) → PseudoMersenneVector

other - self for one element other, in one pass.

neg(out=None) → PseudoMersenneVector

-self into out when 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 out and 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 out is self, 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 out when 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 block elements 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 from odd: the inverse of split_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, as FieldVector.query documents.

reindex(bits, offset: int = 0, out=None) → PseudoMersenneVector

Read this vector through a map of index bits, as FieldVector.reindex documents, in one native pass.

fold(r, block: int = 1) → PseudoMersenneVector

lo + r * (hi - lo) per pair, in one kernel pass.

Only the adjacent layout (block 1) has a kernel; a wider block gathers the two operands first and then runs the three whole-vector operations FieldVector.fold is written with.

fold_inner_products(other: FieldVector) → tuple

FieldVector.fold_inner_products, which documents the operation, computed by the native kernel pmf_vec_fold_inner_products in 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 kernel pmf_vec_fold_and_inner_products in 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 kernel pmf_vec_fold_product_sums in 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 kernel pmf_vec_fold_and_product_sums in 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 kernel pmf_vec_fold_twisted in 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 kernel pmf_vec_lift_twisted in 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_unit describes.

Type:

The group width

view(start: int = 0, length: int | None = None) → PseudoMersenneVector

length elements from start, over this vector’s own planes.

The padding unit is the group width pmf_vec_padded_length rounds to; FieldVector.view states what start and length must 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.

start is replayed rather than seeked: this sampler’s draw stream is walked from the beginning, so a non-zero start costs 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_elements documents.

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 psi the primitive 2n-th root of unity in root_of_unity, forward of a vector holding the coefficients of P in natural order leaves position j holding P(psi ** (2 * brv(j) + 1)), where brv reverses the log2(n) index bits: natural in, bit-reversed out, so positions 2i and 2i + 1 hold P(x) and P(-x). inverse takes that order back to coefficients, 1/n scaling included.

The root is PseudoMersenneField.root_of_unity of order 2n. Every order’s root comes from the same generator, so the plans of successive lengths satisfy plan(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 * n field elements of tables; PseudoMersenneField.ntt_plan memoizes one per length.

Build the plan for length n over field.

Raises ValueError unless n is a power of two no longer than the field allows: a 2n-th root of unity needs log2(n) + 1 at most field.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 blocks above 1, vector holds that many transforms of length n end to end (block b at b * n, the layout batch_layout names) and each is transformed on its own.

Returns a fresh vector unless in_place, in which case vector is 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 blocks messages zero-padded to n.

message holds them interleaved – coefficient i of message b at i * blocks + b – each len(message) // blocks long, a power of two dividing n. The result holds the transforms end to end, message b’s at b * n: what padding each message, pack-ing the batch and forward with blocks give, without the padding or the stages it leaves trivial.

batch_layout = 'blocks'

block b is the n consecutive elements at b * n. Named as ExtensionFieldNTT names 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 in layout, laid out the way a batched forward needs it.

layout is 'blocks' (the default) when each transform’s elements are together, or 'interleaved' when element i of block b sits at i * blocks + b. From 'blocks' there is nothing to do: the input is returned as it is unless out is 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 to layout.