Rings and polynomials

class vfhe.arith.Ring(*args, **kwargs)

A quotient polynomial ring, independent of how its elements are stored.

Ring(...) builds the default implementation (RNS, whose class is RNSRing and whose parameters the constructor below documents); pass implementation= / backend= to name another. Subclasses hold one representation each and everything specific to it; what is true for every representation belongs here.

What that split means for a caller: the members below are the ones any implementation of a quotient polynomial ring offers. An RNS ring’s own coordinates – its primes, its RNS mask, its shared base, the split degree of the incomplete transform – are RNSRing’s, because another representation of the same mathematical ring has none of them. Code that reads them should say RNSRing, which is also what Ring(...) returns.

Rings compare equal by their parameters: two RNSRing objects over the same primes are one ring, whichever object holds it.

N: int

elements are polynomials modulo X**N + 1.

Type:

Degree of the quotient

property arith_ring

This ring’s handle in the generic C interface (an ArithRing).

The handle the representation-independent kernels take. Shared and never freed, so it is safe to hold: a structure built over a ring may point at it, and nothing can prove the last one is gone.

is_quotient_ring(parent: Ring) → bool

Whether self is a quotient of parent.

True when every one of this ring’s residues is present in parent, so an element of parent reduces into this ring without a base conversion.

intersec(other: Ring) → Ring

The smaller of two nested rings: where a binary operation lands.

One of the two must be a quotient of the other, and that one is returned; a pair that is not nested is an error rather than a silently widened result.

union(other: Ring) → Ring

The smallest ring both self and other are quotients of.

Neither ring need contain the other, so this is not intersec reversed.

random_element(ntt: bool = True, random: Random | None = None) → Polynomial

A uniform element of the ring.

Parameters:
  • ntt – Return it in the mul domain (the NTT domain, for RNS) rather than the canonical one. The default costs nothing, since the sampler writes residues directly.

  • random – The source to draw from; the entropy stream when None.

random_gaussian_element(sigma: float, ntt: bool = True, random: Random | None = None) → Polynomial

An element with discrete-Gaussian coefficients of width sigma.

Parameters:
  • sigma – Standard deviation, in coefficients.

  • ntt – Convert to the mul domain before returning. Sampling is always done in the canonical domain, so True adds a transform.

  • random – The source to draw from; the entropy stream when None.

random_exceptional(seed: bytes | None = None, ntt: bool = True, random: Random | None = None) → Polynomial

A uniform element of the ring’s exceptional set: a new Polynomial filled by Polynomial.sample_exceptional, which says what the set is.

Parameters:
  • seed – Derive the element from this seed; one is drawn from random when it is None.

  • ntt – Return it in the mul domain rather than the canonical one.

  • random – The source to draw from; the entropy stream when None.

property exceptional_set_size: int

|A| for an exceptional set of this ring.

digest() → bytes

A 32-byte digest of the parameters that fix the arithmetic (for an RNSRing: the degree N, the primes in order and the splitting degree). Two rings with equal digests are the same ring to a transcript.

class vfhe.arith.Polynomial(*args, **kwargs)

An element of a Ring, in whatever representation the ring uses.

Polynomial(ring, ...) builds the ring’s own element type: the class comes from the ring’s spec, so a polynomial is always matched to its ring’s implementation and a caller never names the concrete class.

The members below are the ones every representation of a ring element offers. The RNS element’s own surface – its native handle, its representation flag and the transforms that move between representations, the per-prime coefficient matrix – is RNSPolynomial’s, which is what Polynomial(ring) returns for an RNSRing.

An element is mutable: the in-place operators and the from_* loaders write into the buffer it already owns, while the binary operators return a fresh element. Readers never mutate – reading a value does not change the representation of the object read.

ring: Ring

The parent this element belongs to.

from_array(array: Sequence[int]) → Polynomial

Load integer coefficients, low degree first, and return self.

Shorter than the ring’s degree is padded with zeros. Values are taken as signed and reduced into the modulus.

from_bigint_array(array: Sequence[int]) → Polynomial

Load coefficients too wide for a machine word, and return self.

The path from_array cannot take: it reads each value as an int64, so a coefficient at full modulus width has to come through here.

get_polynomial(signed: bool = False) → list[int]

The coefficients as Python integers, low degree first.

Over several primes, each coefficient is rebuilt from its residues as a Python integer, one big-integer computation per coefficient. When the residues are enough, to_uint64 returns them in one native call.

Parameters:

signed – Report each coefficient as the representative of smallest absolute value, in (-q/2, q/2], rather than in [0, q). What to use when the coefficients are noise.

copy() → Polynomial

A fresh element with the same value and representation.

to_backend(backend: str) → Polynomial

This element held by backend of its implementation: itself when it already is, otherwise a new element through the registered conversion.

A move is never implicit: a device copy costs more than the operation it precedes. Raises TypeError when no conversion is registered.

get_hash() → list[int]

A 256-bit digest of the value, as four 64-bit words.

Taken in the mul domain, so the same value hashes the same however the element is currently stored. Host-endian and width-dependent: an identifier within one process, not across builds.

digest() → bytes

A 32-byte digest of the value: the four words of get_hash, little-endian, one after another.

get_hash_pointer()

get_hash left in native memory, for a caller that passes it on.

as_element()

This element as an ArithElement for the generic C interface.

A view, not a copy: the returned struct points at the same storage, so it must not outlive this element. Pass it straight into the call that uses it; an implementation may return the same struct each time.

automorphism(gen: int)

self(X**gen): the Galois automorphism of the quotient ring.

gen is odd and below 2 * ring.N, so that X -> X**gen permutes the quotient. Returns a fresh element.

base_extend(ring: Ring | None = None, out: Polynomial | None = None) → Polynomial

This value in a larger ring, up to a multiple of this modulus.

The result is congruent to this element modulo M, this ring’s modulus, but is not generally equal to it: the fast conversion behind it writes x + u * M for some u below this ring’s number of primes. Reducing back into this ring recovers x, and algebra that absorbs multiples of M never sees the difference. Where the integer itself is wanted, use convert_base with exact=True.

Pass the destination ring to allocate the result, or out to write into an element that already exists.

convert_base(ring: Ring | None = None, out: Polynomial | None = None, exact: bool = False) → Polynomial

The same value, written over a different set of primes.

base_extend only adds primes. This also drops them, so neither ring need contain the other. Nothing is scaled on the way – round_division is the operation that divides as it drops primes.

The default conversion is not exact: it writes x + u * M, where M is this ring’s modulus and u is some integer below its number of primes. The result is right modulo M and only modulo M, which is all base_extend’s callers need – they reduce back, or their algebra absorbs multiples of M. Where neither holds, the term lands in the answer at the full size of M.

exact=True removes it, for roughly a tenth again of the cost. u is recovered in floating point, so x, as its representative in [0, M), must stay clear of both ends: it needs about 2^-46 * M, and a quarter of M is ample. A value that may lie anywhere in [0, M) cannot use it; a signed value much smaller than M qualifies by adding M/2 before and subtracting it after, which centers it too.

Pass the destination ring to allocate the result, or out to write into an element that already exists.

mod_reduce(ring: Ring | None = None, out: Polynomial | None = None) → Polynomial

This value reduced into a smaller ring of the same tower.

The modulus shrinks and the value is kept: exact where the smaller modulus can hold it. round_division is the other direction of the same move, dividing the value as it drops the residues.

Pass the destination ring to allocate the result, or out to write into an element that already exists.

round_division(ring: Ring) → Polynomial

Divide by the residues ring drops, rounding, in place.

The rescale primitive: the value is divided by the product of the residues that ring does not have, to the nearest integer, and self.ring becomes ring. Returns self.

Not to be confused with MLWE.round_division, which moves a whole ciphertext and takes a level.

floor_division(ring: Ring) → Polynomial

round_division truncating instead of rounding, in place.

round_division_approximate(ring: Ring) → Polynomial

round_division through the fast base conversion of the remainder, in place: cheaper, and rounded with an error of up to half the number of residues dropped. Returns self.

decompose_digit(ring: Ring, primes: list[int], log_base: int = 0, level: int = 0, dropped: int = 0, centered: bool = False) → Polynomial

A digit of this value’s residues, as a new element of ring.

With log_base 0, the residue modulo the primes given: one of this ring’s primes, or several, whose residue modulo their product is carried to ring by the fast base conversion; as stored, or centered. With a log_base, primes is one prime and the digit is digit level of its residue in base 2**log_base, the dropped lowest digits rounded away, unsigned or, if centered, balanced. ring need not hold the primes of this one.

rescale_to_power_of_two(k: int)

round(2^k * c / q) for each coefficient, as N machine words.

The rescale for a target modulus that is not one this ring’s moduli can express, which is how an element leaves for a scheme that works at a power of two. Coefficients are taken as centered representatives and the results modulo 2^k, so a word is the two’s-complement pattern of a signed value. Exact: the rounding is not carried out in floating point.

Parameters:

k – Width of the target modulus, 1 to 64.

Returns:

A native uint64_t[N].

scaled_lift(ring: Ring, delta: Any = None) → Polynomial

This value lifted to a larger ring and scaled by delta.

The base-extension behind a rescale between moduli that are not nested quotients of one another.

Parameters:
  • ring – The destination ring, which must contain this one.

  • delta – The per-residue scaling factor, as the native array the ring builds (RNSRing.modulus_ratio(..., return_pointer=True)). None scales by the product of the primes ring adds: the value x modulo q becomes (Q/q) * x modulo Q, exactly. Only that default is an operation of the generic interface: with delta given, the lift is not recorded on the execution tape.

sample_uniform(ntt: bool = True) → Polynomial

Overwrite with a uniform element of the ring; returns self.

sample_gaussian(sigma: float, ntt: bool = True) → Polynomial

Overwrite with discrete-Gaussian coefficients; returns self.

sample_exceptional(seed: bytes | None = None, ntt: bool = True) → Polynomial

Overwrite with a uniform element of the ring’s exceptional set; returns self.

The set is the elements whose CRT components (crt_components), at every prime, are all one element beta = a_0 + a_1 x + ... + a_(d-1) x^(d-1) of the residue field, d = split_degree, with integers a_j below the smallest prime p_min – the same integers at every prime. There are p_min^d of them (exceptional_set_size). Two distinct ones differ by an element whose components are all beta - beta'; its coefficients differ by integers in (-p_min, p_min), not all 0, so it is nonzero in every residue field, and the difference is invertible. Their evaluation points are thus one point in every slot.

The a_j are uniform below p_min: drawn from seed by seeded_below_many, or fresh by the entropy stream when it is None.

class vfhe.arith.RNSRing(*args, **kwargs)

Z_q[X]/(X^N + 1) with q an RNS product, over the incomplete NTT.

The modulus is a set of word-sized primes and an element is one row of residues per prime, so arithmetic is elementwise per row and a level of a modulus tower is a subset of the primes – which is what mask names and what makes quotient_ring and round_division cheap.

Primes are drawn from a process-wide base shared by every ring of the same (N, split_degree), and prime indices are global to it: two rings agree on the index of a prime they share, which is what lets a per-prime native array built for one ring be indexed by another. The base grows when a ring introduces a prime the process has not seen, so size such an array with rns_rows, never with the base’s current length.

Ring documents the parameters, and Ring(...) builds this class.

Build the ring; see Ring for what each parameter means.

implementation and backend are the keywords Ring uses to pick a class. Reaching here through Ring they are already consumed; given directly they are checked, so that naming a spec this class does not serve is an error rather than an ignored argument.

ell: int

Number of primes in this ring’s modulus. Not a level index – see the lvl versus ell split in the scheme classes.

prime_size: list[int]

Per-prime widths in bits, in the order of primes.

smallest_prime: int

what bounds an integer scalar operand.

Type:

The smallest of prime_size

split_degree: int

coefficients per residue slot.

Type:

Split degree of the incomplete transform

primes: list[int]

The primes, in the shared base’s order.

q_l: int

The product of primes, as a Python int.

prime_indices: list[int]

Each prime’s index in the shared base, in the same order as primes.

mask: int

how one ring is matched to another across a scheme, within one process.

Type:

Bitmask over the shared base selecting this ring’s primes

classmethod from_native(N: int, mask: int, base: Any) → RNSRing

The ring over the shared base base whose primes mask selects, for a value that came back from C with those parameters.

property arith_ring

This ring’s handle in the generic C interface.

Shared and never freed, so it is safe to hold: a structure built over a ring may point at it, and nothing can prove the last one is gone.

property exceptional_set_size: int

the residue fields have size p_i^split_degree, and a difference must be invertible in every one of them, so the smallest bounds the set.

Type:

|A| for this ring

property rns_rows: int

Rows a native per-prime array must have to be indexed by this ring.

One past this ring’s highest prime index, derived from mask. Prime indices are handed out append-only, so this is fixed for the ring’s lifetime and safe to store alongside an allocation sized with it. The kernels only touch rows the mask selects, so an array this long is enough even though the shared base may hold more primes.

digest() → bytes

See Ring.digest: N, the primes in order, the splitting degree.

residue_field(index: int) → ExtensionField

A residue field of R_q at the prime p = primes[index]: the field crt_components maps into.

Let d = split_degree and k = N/d. Modulo p, X^N + 1 is the product of k irreducible factors X^d - w_s, s < k, one per slot of the incomplete transform (w_s is get_rou_matrix()[index][s]). So the maximal ideals of R_q containing p are P_s = (p, X^d - w_s), and each residue field R_q/P_s is F_p[x]/(x^d - w_s), with x the class of X: a field with p^d elements. This method returns R_q/P_0 = F_p[x]/(x^d - w_0).

There is one field object per (N, split_degree, p) in the process: fields compare by identity, and the components computed through any ring with this prime have to be in the same one.

crt_components(elements: Sequence[RNSPolynomial], index: int, element_major: bool = False) → ExtensionFieldVector

The CRT components of elements at the prime p = primes[index]: each element’s residues modulo the maximal ideals of R_q that contain p, all carried into the field residue_field(index).

Let k = N/split_degree. The maximal ideals of R_q containing p are P_s = (p, X^d - w_s), s < k, with d, w_s and the residue fields R_q/P_s as in residue_field, which returns R_q/P_0. Every w_s is an odd power w_0^(x_s) of w_0, and the automorphism X -> X^(x_s) of R_q maps P_s onto P_0; component s of an element is its residue modulo P_s carried into R_q/P_0 by the isomorphism this induces. Each component is a surjective ring homomorphism R_q -> R_q/P_0, and the k components together induce an isomorphism R_q/pR_q -> (R_q/P_0)^k. So the components at every prime determine the element; from_crt_components is the inverse.

Entry s * len(elements) + b of the result is component s of elements[b]: component s of all the elements is a contiguous window. With element_major, entry b * k + s is: the components of one element are a contiguous window.

The elements may belong to any ring with this prime and this ring’s N and split_degree. They are read in the mul domain, through a converted copy when they are not in it.

lift_mod_2_128(elements: Sequence[RNSPolynomial]) → tuple[array.array, array.array]

Every coefficient of elements as the integer in [0, q) its residues define, modulo 2^128, as two array('Q')``s: entry ``e * N + k of (low, high) is coefficient k of elements[e] as low + 2^64 high.

The elements must be of this ring. They are read in the coefficient domain, through a converted copy when they are not in it.

integer_linear_combinations(elements: Sequence[RNSPolynomial], matrix: IntegerMatrix) → list[RNSPolynomial]

Multiply the integer matrix matrix by the vector elements.

Returns one element of this ring per row of matrix: element r is the sum over j of matrix[r][j] * elements[j]. For example, the rows [[1, 2], [0, -1]] and the elements [a, b] give [a + 2*b, -b]. Every entry of matrix is reduced modulo each prime, so any signed 64-bit integer works.

The results are in the representation the elements hold, since multiplying by an integer commutes with the transform. When the elements do not all hold the same one, they are read in the NTT representation, and so are the results; the elements themselves are not converted.

The work follows the nonzero entries of matrix and runs in parallel within the library limit. The first call with this ring’s primes prepares matrix for them (IntegerMatrix.prepared); later calls reuse that.

elements must all be over this ring and hold every one of its rows. matrix is an IntegerMatrix with one column per element.

crt_linear_combination(parts: Sequence[Sequence[RNSPolynomial]], index: int, coefficients: FieldVector) → ExtensionFieldVector

A linear combination of CRT components at p = primes[index], in the field residue_field(index): entry b of the result is the sum, over c and s, of coefficients[c * k + s] times component s (crt_components) of parts[c][b], with k = N/split_degree. Every parts[c] holds the same number of elements.

It equals multiplying the components laid out element-major by the coefficients and summing each element’s k entries over c and s, but the components are never formed: each coefficient of an entry is one inner product of the elements’ mul-domain words with a table built from the coefficients (polynomial_RNS_crt_linear_combination). This is the precomputation of [ACGS24, ePrint 2023/1949, App. C, Eqs. 3-4] for a linear combination of slots: each slot is an inner product with the element’s words, so the combination is one inner product with the coefficients’ combination of those vectors.

from_crt_components(vectors: Sequence[FieldVector]) → list[RNSPolynomial]

The inverse of crt_components: the elements of this ring whose components at primes[i] are vectors[i], for every i, which is the CRT reconstruction. Returned in the mul domain.

from_diagonal(vectors: Sequence[FieldVector]) → list[RNSPolynomial]

The elements whose N / split_degree components at each primes[i] are all equal: element b has every component at primes[i] equal to vectors[i][b]. The same elements as from_crt_components with every entry of vectors[i] repeated once per component, without forming the repetitions. Returned in the mul domain.

These elements form a subring, which contains the integers and the elements random_exceptional draws.

is_quotient_ring(parent: RNSRing) → bool

Whether self is a quotient of parent.

True when every one of this ring’s residues is present in parent, so an element of parent reduces into this ring without a base conversion.

property parameters: RingParameters

What this ring is, for equality and for matching a stored ring to a live one.

intersec(other: RNSRing) → RNSRing

The smaller of two nested rings: where a binary operation lands.

One of the two must be a quotient of the other, and that one is returned; a pair that is not nested is an error rather than a silently widened result.

union(other: RNSRing) → RNSRing

The ring over both rings’ primes together.

Neither ring need contain the other, so this is not intersec reversed: it is the smallest ring both are quotients of. The primes come back in the base’s own order, which is the order every per-prime array is indexed by, so a caller never has to know how primes are numbered.

static gen_primes_near(rou_order: int, prime_size: int, count: int, exclude_list: list[int] | None = None, *, split_degree: int) → list[int]

count primes p = a * rou_order + 1 nearest 2^prime_size, alternately above and below it: the nearest above, the nearest below, the next above, and so on, none in exclude_list.

The ones above have prime_size + 1 bits. As in gen_prime, a is odd when split_degree > 1; with split_degree 1 any a will do, and the nearest is taken. Alternating keeps the product of consecutive primes close to the matching power of 2^prime_size.

scalar(value: int | Sequence[int]) → RNSScalar

value as a multiplier of this ring’s elements: an integer, or one integer per prime in primes order, each reduced by its prime.

It is built once and applied without allocating, by p * scalar or p *= scalar for any element p of this ring or of a quotient of it.

random_element(ntt=True, random=None)

A uniform element of the ring.

Parameters:
  • ntt – Return it in the mul domain (the NTT domain, for RNS) rather than the canonical one. The default costs nothing, since the sampler writes residues directly.

  • random – The source to draw from; the entropy stream when None.

random_gaussian_element(sigma, ntt=True, random=None)

An element with discrete-Gaussian coefficients of width sigma.

Parameters:
  • sigma – Standard deviation, in coefficients.

  • ntt – Convert to the mul domain before returning. Sampling is always done in the canonical domain, so True adds a transform.

  • random – The source to draw from; the entropy stream when None.

random_exceptional(seed=None, ntt=True, random=None)

A uniform element of the ring’s exceptional set: a new Polynomial filled by Polynomial.sample_exceptional, which says what the set is.

Parameters:
  • seed – Derive the element from this seed; one is drawn from random when it is None.

  • ntt – Return it in the mul domain rather than the canonical one.

  • random – The source to draw from; the entropy stream when None.

spec: Spec = Spec(implementation='rns', backend='ntt', parent_cls=<class 'vfhe.arith.impl.rns.polynomial.RNSRing'>, element_cls=<class 'vfhe.arith.impl.rns.polynomial.RNSPolynomial'>, vector_cls=None, capabilities=<Capability.CORE|QUOTIENT_POLY_RING|TOWER|SAMPLING|EXACT: 31>, constraints=Constraints(max_prime_bits=62, min_transform_length=None), rank=0)

The (implementation, backend) this parent was built for.

class vfhe.arith.RNSPolynomial(*args, **kwargs)

An element of an RNSRing: one row of residues per prime.

The value is held natively and reached through obj; repr records which of the two representations (Representation) those rows are currently in, and the transforms are what move between them. Readers convert a copy, so reading never changes the representation of the object read.

Allocate an element of ring, holding no value yet.

obj adopts a native RNS_Polynomial over ring’s primes instead, in representation repr; it is freed with this object.

ring: RNSRing

The parent, whose primes index this element’s rows.

obj: Any

The native RNS_Polynomial handle, freed with this object.

repr: Representation

Which representation obj’s rows hold right now.

from_array(array: list)

Load integer coefficients, low degree first, and return self.

Shorter than the ring’s degree is padded with zeros. Values are taken as signed and reduced into the modulus.

from_bigint_array(array: list)

Load coefficients too wide for a machine word, and return self.

The path from_array cannot take: it reads each value as an int64, so a coefficient at full modulus width has to come through here.

automorphism(gen)

X -> X^gen.

Stays in the NTT domain when self is there and the ring is fully split (a permutation of the evaluation points); otherwise returns coefficients.

sample_uniform(ntt=True, random=None)

Overwrite with a uniform element of the ring; returns self.

sample_gaussian(sigma, ntt=True, random=None)

Overwrite with discrete-Gaussian coefficients; returns self.

sample_exceptional(seed=None, ntt=True, random=None)

Overwrite with a uniform element of the ring’s exceptional set; returns self.

The set is the elements whose CRT components (crt_components), at every prime, are all one element beta = a_0 + a_1 x + ... + a_(d-1) x^(d-1) of the residue field, d = split_degree, with integers a_j below the smallest prime p_min – the same integers at every prime. There are p_min^d of them (exceptional_set_size). Two distinct ones differ by an element whose components are all beta - beta'; its coefficients differ by integers in (-p_min, p_min), not all 0, so it is nonzero in every residue field, and the difference is invertible. Their evaluation points are thus one point in every slot.

The a_j are uniform below p_min: drawn from seed by seeded_below_many, or fresh by the entropy stream when it is None.

base_extend(ring: RNSRing | None = None, out: RNSPolynomial | None = None) → RNSPolynomial

This value in a larger ring, up to a multiple of this modulus.

The result is congruent to this element modulo M, this ring’s modulus, but is not generally equal to it: the fast conversion behind it writes x + u * M for some u below this ring’s number of primes. Reducing back into this ring recovers x, and algebra that absorbs multiples of M never sees the difference. Where the integer itself is wanted, use convert_base with exact=True.

Pass the destination ring to allocate the result, or out to write into an element that already exists.

convert_base(ring: RNSRing | None = None, out: RNSPolynomial | None = None, exact: bool = False) → RNSPolynomial

The same value, written over a different set of primes.

base_extend only adds primes. This also drops them, so neither ring need contain the other. Nothing is scaled on the way – round_division is the operation that divides as it drops primes.

The default conversion is not exact: it writes x + u * M, where M is this ring’s modulus and u is some integer below its number of primes. The result is right modulo M and only modulo M, which is all base_extend’s callers need – they reduce back, or their algebra absorbs multiples of M. Where neither holds, the term lands in the answer at the full size of M.

exact=True removes it, for roughly a tenth again of the cost. u is recovered in floating point, so x, as its representative in [0, M), must stay clear of both ends: it needs about 2^-46 * M, and a quarter of M is ample. A value that may lie anywhere in [0, M) cannot use it; a signed value much smaller than M qualifies by adding M/2 before and subtracting it after, which centers it too.

Pass the destination ring to allocate the result, or out to write into an element that already exists.

mod_reduce(ring: RNSRing | None = None, out: RNSPolynomial | None = None) → RNSPolynomial

This value reduced into a smaller ring of the same tower.

The modulus shrinks and the value is kept: exact where the smaller modulus can hold it. round_division is the other direction of the same move, dividing the value as it drops the residues.

Pass the destination ring to allocate the result, or out to write into an element that already exists.

floor_division(ring: RNSRing) → RNSPolynomial

round_division truncating instead of rounding, in place.

round_division(ring: RNSRing) → RNSPolynomial

Divide by the residues ring drops, rounding, in place.

The rescale primitive: the value is divided by the product of the residues that ring does not have, to the nearest integer, and self.ring becomes ring. Returns self.

Not to be confused with MLWE.round_division, which moves a whole ciphertext and takes a level.

round_division_approximate(ring: RNSRing) → RNSPolynomial

round_division through the fast base conversion of the remainder, in place: cheaper, and rounded with an error of up to half the number of residues dropped. Returns self.

decompose_digit(ring: RNSRing, primes: list[int], log_base: int = 0, level: int = 0, dropped: int = 0, centered: bool = False) → RNSPolynomial

A digit of this value’s residues, as a new element of ring.

With log_base 0, the residue modulo the primes given: one of this ring’s primes, or several, whose residue modulo their product is carried to ring by the fast base conversion; as stored, or centered. With a log_base, primes is one prime and the digit is digit level of its residue in base 2**log_base, the dropped lowest digits rounded away, unsigned or, if centered, balanced. ring need not hold the primes of this one.

rescale_to_power_of_two(k: int)

round(2^k * c / q) for each coefficient, as N machine words.

The rescale for a target modulus that is not a product of base primes, which is what round_division and scaled_lift between them cannot express. Coefficients are taken as centered representatives and the results modulo 2^k, so the words are the two’s-complement pattern of a signed value for any k up to 64 – at 64 exactly what a uint64_t holds. Exact: the rounding is not carried out in floating point.

Leaves this polynomial in the coefficient domain and does not otherwise change it.

Parameters:

k – Width of the target modulus, 1 to 64.

Returns:

A native uint64_t[N]; ffi.buffer of it is the bytes, list of it the coefficients.

scaled_lift(ring: RNSRing, delta: Any = None) → RNSPolynomial

Lifts the polynomial to a larger ring and scales it by the delta factor.

get_hash_pointer()

get_hash left in native memory, for a caller that passes it on.

get_hash()

A 256-bit digest of the value, as four 64-bit words.

Taken in the mul domain, so the same value hashes the same however the element is currently stored. Host-endian and width-dependent: an identifier within one process, not across builds.

digest() → bytes

The 32-byte BLAKE3 digest of the value, taken in the mul domain: the bytes get_hash returns as four words.

static digest_sequence(polys: list[RNSPolynomial]) → bytes

The BLAKE3 digest of one message: for each of polys in order, the rows get_hash hashes, taken in the mul domain like it.

get_coeff_matrix(repr=Representation.coeff)

One list of N coefficients per prime, in RNSRing.primes order.

The rows are in the order to_uint64 gives, which says what that order is in each representation.

from_coeff_matrix(matrix, repr=Representation.coeff)

Overwrite with one list of N coefficients per prime; returns self.

to_uint64(repr: Representation = Representation.coeff) → array

The rows in representation repr, as one array('Q') of ell * N words: words i * N to (i + 1) * N - 1 are the row of ring.primes[i]. numpy.frombuffer(words, numpy.uint64) .reshape(ell, N) reads it as a matrix without copying.

In Representation.coeff, word i * N + j is coefficient j modulo primes[i]. In Representation.ntt a row is the N / d slots of the incomplete transform one after another, d = split_degree: words i * N + s * d to i * N + s * d + d - 1 are the coefficients, low degree first, of the residue modulo X^d - w_s (for d = 1 the value at w_s), with w_s = get_rou_matrix()[i][s] = w_0^(2 brv(s) + 1) and brv the reversal of log2(N / d) bits. get_coeff_matrix returns the same rows as lists of Python ints.

Reads a converted copy when self is in the other representation.

from_uint64(values: Buffer, repr: Representation = Representation.coeff) → RNSPolynomial

Overwrite with rows laid out as to_uint64 returns them, holding representation repr; returns self.

values is an array('Q') or any C-contiguous buffer of ell * N unsigned 64-bit integers, such as a numpy.uint64 array of shape (ell, N). Every word must be below its row’s prime; ValueError otherwise, with self unchanged.

get_polynomial(signed: bool = False) → list[int]

The coefficients as Python integers, low degree first.

Over several primes, each coefficient is rebuilt from its residues as a Python integer, one big-integer computation per coefficient. When the residues are enough, to_uint64 returns them in one native call.

Parameters:

signed – Report each coefficient as the representative of smallest absolute value, in (-q/2, q/2], rather than in [0, q). What to use when the coefficients are noise.

as_element()

This polynomial as an ArithElement for the generic C interface.

A view, not a copy: the returned struct points at the same storage, so it must not outlive this polynomial. The struct is this polynomial’s own, built on first use and returned again by later calls with the current representation as its domain, so one call’s struct is valid until the next.

copy() → RNSPolynomial

A fresh element with the same value and representation.

class vfhe.arith.Representation(*values)

Which representation an RNSPolynomial currently holds.

empty

Allocated, never written. Not a data representation: converting to it is an error.

coeff

Residues of the polynomial’s coefficients, one row per prime. The canonical form: equality, digests and integer readback are defined here.

ntt

The same value under the number-theoretic transform, where multiplication is elementwise. The mul domain.

Domain is the same distinction in the vocabulary every implementation shares; domain_of maps one to the other.

vfhe.arith.repr = <enum 'Representation'>

Which representation an RNSPolynomial currently holds.

empty

Allocated, never written. Not a data representation: converting to it is an error.

coeff

Residues of the polynomial’s coefficients, one row per prime. The canonical form: equality, digests and integer readback are defined here.

ntt

The same value under the number-theoretic transform, where multiplication is elementwise. The mul domain.

Domain is the same distinction in the vocabulary every implementation shares; domain_of maps one to the other.

vfhe.arith.domain_of(representation) → int

The ArithDomain value matching a Representation.

class vfhe.arith.ComplexRing(N: int)

The CKKS encoder’s ring: polynomials of N complex coefficients and the negacyclic FFT between coefficients and slots.

spec: ClassVar[Spec] = Spec(implementation='complex', backend='fft', parent_cls=<class 'vfhe.arith.impl.complex.complex.ComplexRing'>, element_cls=<class 'vfhe.arith.impl.complex.complex.ComplexPolynomial'>, vector_cls=None, capabilities=<Capability.CORE|SAMPLING: 9>, constraints=Constraints(max_prime_bits=None, min_transform_length=None), rank=0)

The (implementation, backend) this parent was built for.

plan

The negacyclic FFT of length 2N, and where each slot lands in its output (see complex_slot_positions in arith.h).

exp_complex_polys_ifft_scale_round_to_RNS_batch(e_polys: list[ComplexPolynomial], ring: RNSRing, temp_delta: float) → list[RNSPolynomial]

Batch: for each exp-domain ComplexPolynomial, IFFT, scale by temp_delta, round to RNS/NTT.

values_ifft_scale_round_to_RNS_batch(values: Sequence[object], ring: RNSRing, scale: float, shifts: Sequence[int] | None = None, n_threads: int = 0) → list[RNSPolynomial]

For each vector in values: rotated left by shifts[k] (default 0), repeated to N values, inverse transformed, scaled by scale and rounded into ring, in the NTT domain.

Each vector’s length must be a power of two dividing N. A contiguous one-dimensional buffer of complex doubles (format Zd, e.g. a numpy complex128 array) is read in place; anything else is converted, and may hold any numbers.Complex.

class vfhe.arith.ComplexPolynomial(ring: ComplexRing)

An element of a ComplexRing: N complex coefficients, held natively in obj.

IFFT()

Slot form to coefficient form, in place.

FFT()

Coefficient form to slot form, in place.

from_array(v: Sequence[numbers.Complex | complex]) → ComplexPolynomial

Sets the first len(v) values; any numbers.Complex is accepted.

class vfhe.arith.Multiprecision

The bridge between RNS residues and multiprecision integers: loads Python integers into base-2^52 digit arrays, reconstructs them, and runs the multiprecision kernels on polynomials.

spec: ClassVar[Spec] = Spec(implementation='mp', backend='limb52', parent_cls=<class 'vfhe.arith.impl.mp.multiprecision.Multiprecision'>, element_cls=None, vector_cls=None, capabilities=<Capability.CORE|EXACT|DOMAINS_COINCIDE: 49>, constraints=Constraints(max_prime_bits=None, min_transform_length=None), rank=0)

The (implementation, backend) this parent was built for.

compute_crt_consts(primes: list[int]) → dict

Barrett CRT-reconstruction constants for primes.

Every returned list is in the order primes is given in; from_polynomial is what matches them to a ring. hat_q is the per-prime factor to apply in RNS before reconstructing, and d the digit count the MPPolynomial accumulator needs. Raises ValueError when the moduli admit no single-digit Barrett reconstruction.

static limbs(x: int, d: int) → list[int]

x as exactly d base-2^52 digits.

from_polynomial(poly: RNSPolynomial, crt_consts: dict)

Reconstruct poly’s coefficients as multiprecision integers.

crt_consts must have been built by compute_crt_consts over this polynomial’s ring primes; the two orderings are matched up here, since neither of the ones in play is the caller’s: the per-prime scaling takes its factors in RNSRing.primes order, and the native reconstruction walks the ring’s mask, so in ascending base index.

poly is left in the coefficient domain. The returned handle frees its native allocation when it is collected.

class vfhe.arith.CUDARing(*args, **kwargs)

An RNSRing whose elements live on the CUDA device.

Same primes, shared base and mask as the host ring of the same parameters, and a different parent: the two compare unequal. host is that ring.

Build the ring; see Ring for what each parameter means.

implementation and backend are the keywords Ring uses to pick a class. Reaching here through Ring they are already consumed; given directly they are checked, so that naming a spec this class does not serve is an error rather than an ignored argument.

classmethod of(host: RNSRing) → CUDARing

The device ring with host’s parameters, one per host ring.

property host: RNSRing

The host ring with the same parameters.

spec: Spec = Spec(implementation='rns', backend='cuda', parent_cls=<class 'vfhe.arith.impl.rns.cuda.CUDARing'>, element_cls=<class 'vfhe.arith.impl.rns.cuda.CUDAPolynomial'>, vector_cls=None, capabilities=<Capability.CORE|QUOTIENT_POLY_RING|EXACT: 19>, constraints=Constraints(max_prime_bits=62, min_transform_length=None), rank=1)

The (implementation, backend) this parent was built for.

class vfhe.arith.CUDAPolynomial(*args, **kwargs)

An element of a CUDARing: ring.ell rows of ring.N residues on the device.

repr is the representation the rows hold, kept from the host element that was uploaded; the device transforms nothing, so two operands must hold the same one.

Allocate an element of ring, holding no value yet.

ring: CUDARing

The parent this element belongs to.

obj: Any

The device element, released with this object.

copy() → CUDAPolynomial

A fresh element with the same value and representation.

from_array(array) → Self

Load integer coefficients, low degree first, and return self.

Shorter than the ring’s degree is padded with zeros. Values are taken as signed and reduced into the modulus.

get_polynomial(signed: bool = False) → list[int]

The coefficients as Python integers, low degree first.

Over several primes, each coefficient is rebuilt from its residues as a Python integer, one big-integer computation per coefficient. When the residues are enough, to_uint64 returns them in one native call.

Parameters:

signed – Report each coefficient as the representative of smallest absolute value, in (-q/2, q/2], rather than in [0, q). What to use when the coefficients are noise.

class vfhe.arith.ArithParent

A set of elements with arithmetic: a ring, a field, a quotient ring.

Subclasses set spec and implement exceptional_set_size. Everything else has a default here that an implementation may override when it can do better.

spec: Spec

The (implementation, backend) this parent was built for.

supports(capability: Capability) → bool

Whether this parent carries every flag in capability.

The cheap check a caller makes before an operation an implementation may not define at all, so the failure is a clear message here rather than a not-implemented answer deeper in.

require(capability: Capability) → None

Raise TypeError unless this parent carries capability.

property domains_coincide: bool

Whether the canonical and mul domains are one representation.

mul_domain() → Domain

The domain multiplication needs operands to be in.

abstract property exceptional_set_size: int

|A| for an exceptional set of this domain.

A set whose pairwise differences are all invertible. Protocols with soundness in the size of the challenge set read this rather than deriving it from the domain’s internals, which differ per implementation.