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 isRNSRingand whose parameters the constructor below documents); passimplementation=/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 sayRNSRing, which is also whatRing(...)returns.Rings compare equal by their parameters: two
RNSRingobjects 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
selfis a quotient ofparent.True when every one of this ring’s residues is present in
parent, so an element ofparentreduces 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
selfandotherare quotients of.Neither ring need contain the other, so this is not
intersecreversed.
- 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
Polynomialfilled byPolynomial.sample_exceptional, which says what the set is.- Parameters:
seed – Derive the element from this seed; one is drawn from
randomwhen 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.
- 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 whatPolynomial(ring)returns for anRNSRing.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.- 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_arraycannot 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_uint64returns 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
backendof 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
TypeErrorwhen 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.
- as_element()¶
This element as an
ArithElementfor 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.genis odd and below2 * ring.N, so thatX -> X**genpermutes 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 writesx + u * Mfor someubelow this ring’s number of primes. Reducing back into this ring recoversx, and algebra that absorbs multiples ofMnever sees the difference. Where the integer itself is wanted, useconvert_basewithexact=True.Pass the destination
ringto allocate the result, oroutto 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_extendonly adds primes. This also drops them, so neither ring need contain the other. Nothing is scaled on the way –round_divisionis the operation that divides as it drops primes.The default conversion is not exact: it writes
x + u * M, whereMis this ring’s modulus anduis some integer below its number of primes. The result is right moduloMand only moduloM, which is allbase_extend’s callers need – they reduce back, or their algebra absorbs multiples ofM. Where neither holds, the term lands in the answer at the full size ofM.exact=Trueremoves it, for roughly a tenth again of the cost.uis recovered in floating point, sox, as its representative in[0, M), must stay clear of both ends: it needs about2^-46 * M, and a quarter ofMis ample. A value that may lie anywhere in[0, M)cannot use it; a signed value much smaller thanMqualifies by addingM/2before and subtracting it after, which centers it too.Pass the destination
ringto allocate the result, oroutto 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_divisionis the other direction of the same move, dividing the value as it drops the residues.Pass the destination
ringto allocate the result, oroutto write into an element that already exists.
- round_division(ring: Ring) Polynomial¶
Divide by the residues
ringdrops, rounding, in place.The rescale primitive: the value is divided by the product of the residues that
ringdoes not have, to the nearest integer, andself.ringbecomesring. Returnsself.Not to be confused with
MLWE.round_division, which moves a whole ciphertext and takes a level.
- floor_division(ring: Ring) Polynomial¶
round_divisiontruncating instead of rounding, in place.
- round_division_approximate(ring: Ring) Polynomial¶
round_divisionthrough the fast base conversion of the remainder, in place: cheaper, and rounded with an error of up to half the number of residues dropped. Returnsself.
- 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_base0, the residue modulo theprimesgiven: one of this ring’s primes, or several, whose residue modulo their product is carried toringby the fast base conversion; as stored, orcentered. With alog_base,primesis one prime and the digit is digitlevelof its residue in base2**log_base, thedroppedlowest digits rounded away, unsigned or, ifcentered, balanced.ringneed not hold the primes of this one.
- rescale_to_power_of_two(k: int)¶
round(2^k * c / q)for each coefficient, asNmachine 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 primesringadds: the valuexmoduloqbecomes(Q/q) * xmoduloQ, exactly. Only that default is an operation of the generic interface: withdeltagiven, 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 elementbeta = a_0 + a_1 x + ... + a_(d-1) x^(d-1)of the residue field,d = split_degree, with integersa_jbelow the smallest prime p_min – the same integers at every prime. There arep_min^dof them (exceptional_set_size). Two distinct ones differ by an element whose components are allbeta - 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_jare uniform below p_min: drawn fromseedbyseeded_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
masknames and what makesquotient_ringandround_divisioncheap.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 withrns_rows, never with the base’s current length.Ringdocuments the parameters, andRing(...)builds this class.Build the ring; see
Ringfor what each parameter means.implementationandbackendare the keywordsRinguses to pick a class. Reaching here throughRingthey 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
lvlversusellsplit in the scheme classes.
- 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.
- 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
basewhose primesmaskselects, 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_qat the primep = primes[index]: the fieldcrt_componentsmaps into.Let
d = split_degreeandk = N/d. Modulop,X^N + 1is the product ofkirreducible factorsX^d - w_s,s < k, one per slot of the incomplete transform (w_sisget_rou_matrix()[index][s]). So the maximal ideals ofR_qcontainingpareP_s = (p, X^d - w_s), and each residue fieldR_q/P_sisF_p[x]/(x^d - w_s), withxthe class ofX: a field withp^delements. This method returnsR_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
elementsat the primep = primes[index]: each element’s residues modulo the maximal ideals ofR_qthat containp, all carried into the fieldresidue_field(index).Let
k = N/split_degree. The maximal ideals ofR_qcontainingpareP_s = (p, X^d - w_s),s < k, withd,w_sand the residue fieldsR_q/P_sas inresidue_field, which returnsR_q/P_0. Everyw_sis an odd powerw_0^(x_s)ofw_0, and the automorphismX -> X^(x_s)ofR_qmapsP_sontoP_0; componentsof an element is its residue moduloP_scarried intoR_q/P_0by the isomorphism this induces. Each component is a surjective ring homomorphismR_q -> R_q/P_0, and thekcomponents together induce an isomorphismR_q/pR_q -> (R_q/P_0)^k. So the components at every prime determine the element;from_crt_componentsis the inverse.Entry
s * len(elements) + bof the result is componentsofelements[b]: componentsof all the elements is a contiguous window. Withelement_major, entryb * k + sis: the components of one element are a contiguous window.The elements may belong to any ring with this prime and this ring’s
Nandsplit_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
elementsas the integer in[0, q)its residues define, modulo2^128, as twoarray('Q')``s: entry ``e * N + kof(low, high)is coefficientkofelements[e]aslow + 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
matrixby the vectorelements.Returns one element of this ring per row of
matrix: elementris the sum overjofmatrix[r][j] * elements[j]. For example, the rows[[1, 2], [0, -1]]and the elements[a, b]give[a + 2*b, -b]. Every entry ofmatrixis 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
matrixand runs in parallel within the library limit. The first call with this ring’s primes preparesmatrixfor them (IntegerMatrix.prepared); later calls reuse that.elementsmust all be over this ring and hold every one of its rows.matrixis anIntegerMatrixwith 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 fieldresidue_field(index): entry b of the result is the sum, over c and s, ofcoefficients[c * k + s]times component s (crt_components) ofparts[c][b], withk = N/split_degree. Everyparts[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 atprimes[i]arevectors[i], for everyi, which is the CRT reconstruction. Returned in the mul domain.
- from_diagonal(vectors: Sequence[FieldVector]) list[RNSPolynomial]¶
The elements whose
N / split_degreecomponents at eachprimes[i]are all equal: elementbhas every component atprimes[i]equal tovectors[i][b]. The same elements asfrom_crt_componentswith every entry ofvectors[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_exceptionaldraws.
- is_quotient_ring(parent: RNSRing) bool¶
Whether
selfis a quotient ofparent.True when every one of this ring’s residues is present in
parent, so an element ofparentreduces 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
intersecreversed: 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]¶
countprimesp = a * rou_order + 1nearest2^prime_size, alternately above and below it: the nearest above, the nearest below, the next above, and so on, none inexclude_list.The ones above have
prime_size + 1bits. As ingen_prime,ais odd whensplit_degree > 1; withsplit_degree1 anyawill do, and the nearest is taken. Alternating keeps the product of consecutive primes close to the matching power of2^prime_size.
- scalar(value: int | Sequence[int]) RNSScalar¶
valueas a multiplier of this ring’s elements: an integer, or one integer per prime inprimesorder, each reduced by its prime.It is built once and applied without allocating, by
p * scalarorp *= scalarfor any elementpof 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
Polynomialfilled byPolynomial.sample_exceptional, which says what the set is.- Parameters:
seed – Derive the element from this seed; one is drawn from
randomwhen 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;reprrecords 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.objadopts a nativeRNS_Polynomialoverring’s primes instead, in representationrepr; it is freed with this object.- obj: Any¶
The native
RNS_Polynomialhandle, 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_arraycannot 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
selfis 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 elementbeta = a_0 + a_1 x + ... + a_(d-1) x^(d-1)of the residue field,d = split_degree, with integersa_jbelow the smallest prime p_min – the same integers at every prime. There arep_min^dof them (exceptional_set_size). Two distinct ones differ by an element whose components are allbeta - 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_jare uniform below p_min: drawn fromseedbyseeded_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 writesx + u * Mfor someubelow this ring’s number of primes. Reducing back into this ring recoversx, and algebra that absorbs multiples ofMnever sees the difference. Where the integer itself is wanted, useconvert_basewithexact=True.Pass the destination
ringto allocate the result, oroutto 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_extendonly adds primes. This also drops them, so neither ring need contain the other. Nothing is scaled on the way –round_divisionis the operation that divides as it drops primes.The default conversion is not exact: it writes
x + u * M, whereMis this ring’s modulus anduis some integer below its number of primes. The result is right moduloMand only moduloM, which is allbase_extend’s callers need – they reduce back, or their algebra absorbs multiples ofM. Where neither holds, the term lands in the answer at the full size ofM.exact=Trueremoves it, for roughly a tenth again of the cost.uis recovered in floating point, sox, as its representative in[0, M), must stay clear of both ends: it needs about2^-46 * M, and a quarter ofMis ample. A value that may lie anywhere in[0, M)cannot use it; a signed value much smaller thanMqualifies by addingM/2before and subtracting it after, which centers it too.Pass the destination
ringto allocate the result, oroutto 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_divisionis the other direction of the same move, dividing the value as it drops the residues.Pass the destination
ringto allocate the result, oroutto write into an element that already exists.
- floor_division(ring: RNSRing) RNSPolynomial¶
round_divisiontruncating instead of rounding, in place.
- round_division(ring: RNSRing) RNSPolynomial¶
Divide by the residues
ringdrops, rounding, in place.The rescale primitive: the value is divided by the product of the residues that
ringdoes not have, to the nearest integer, andself.ringbecomesring. Returnsself.Not to be confused with
MLWE.round_division, which moves a whole ciphertext and takes a level.
- round_division_approximate(ring: RNSRing) RNSPolynomial¶
round_divisionthrough the fast base conversion of the remainder, in place: cheaper, and rounded with an error of up to half the number of residues dropped. Returnsself.
- 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_base0, the residue modulo theprimesgiven: one of this ring’s primes, or several, whose residue modulo their product is carried toringby the fast base conversion; as stored, orcentered. With alog_base,primesis one prime and the digit is digitlevelof its residue in base2**log_base, thedroppedlowest digits rounded away, unsigned or, ifcentered, balanced.ringneed not hold the primes of this one.
- rescale_to_power_of_two(k: int)¶
round(2^k * c / q)for each coefficient, asNmachine words.The rescale for a target modulus that is not a product of base primes, which is what
round_divisionandscaled_liftbetween 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 anykup to 64 – at 64 exactly what auint64_tholds. 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.bufferof it is the bytes,listof 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()¶
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_hashreturns as four words.
- static digest_sequence(polys: list[RNSPolynomial]) bytes¶
The BLAKE3 digest of one message: for each of
polysin order, the rowsget_hashhashes, taken in the mul domain like it.
- get_coeff_matrix(repr=Representation.coeff)¶
One list of
Ncoefficients per prime, inRNSRing.primesorder.The rows are in the order
to_uint64gives, which says what that order is in each representation.
- from_coeff_matrix(matrix, repr=Representation.coeff)¶
Overwrite with one list of
Ncoefficients per prime; returnsself.
- to_uint64(repr: Representation = Representation.coeff) array¶
The rows in representation
repr, as onearray('Q')ofell * Nwords: wordsi * Nto(i + 1) * N - 1are the row ofring.primes[i].numpy.frombuffer(words, numpy.uint64) .reshape(ell, N)reads it as a matrix without copying.In
Representation.coeff, wordi * N + jis coefficientjmoduloprimes[i]. InRepresentation.ntta row is theN / dslots of the incomplete transform one after another,d = split_degree: wordsi * N + s * dtoi * N + s * d + d - 1are the coefficients, low degree first, of the residue moduloX^d - w_s(ford = 1the value atw_s), withw_s = get_rou_matrix()[i][s] = w_0^(2 brv(s) + 1)andbrvthe reversal oflog2(N / d)bits.get_coeff_matrixreturns the same rows as lists of Python ints.Reads a converted copy when
selfis in the other representation.
- from_uint64(values: Buffer, repr: Representation = Representation.coeff) RNSPolynomial¶
Overwrite with rows laid out as
to_uint64returns them, holding representationrepr; returnsself.valuesis anarray('Q')or any C-contiguous buffer ofell * Nunsigned 64-bit integers, such as anumpy.uint64array of shape(ell, N). Every word must be below its row’s prime; ValueError otherwise, withselfunchanged.
- 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_uint64returns 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
ArithElementfor 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
RNSPolynomialcurrently holds.emptyAllocated, never written. Not a data representation: converting to it is an error.
coeffResidues of the polynomial’s coefficients, one row per prime. The canonical form: equality, digests and integer readback are defined here.
nttThe same value under the number-theoretic transform, where multiplication is elementwise. The mul domain.
Domainis the same distinction in the vocabulary every implementation shares;domain_ofmaps one to the other.
- vfhe.arith.repr = <enum 'Representation'>¶
Which representation an
RNSPolynomialcurrently holds.emptyAllocated, never written. Not a data representation: converting to it is an error.
coeffResidues of the polynomial’s coefficients, one row per prime. The canonical form: equality, digests and integer readback are defined here.
nttThe same value under the number-theoretic transform, where multiplication is elementwise. The mul domain.
Domainis the same distinction in the vocabulary every implementation shares;domain_ofmaps one to the other.
- vfhe.arith.domain_of(representation) int¶
The
ArithDomainvalue matching aRepresentation.
- class vfhe.arith.ComplexRing(N: int)¶
The CKKS encoder’s ring: polynomials of
Ncomplex 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_positionsin 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 byshifts[k](default 0), repeated toNvalues, inverse transformed, scaled byscaleand rounded intoring, in the NTT domain.Each vector’s length must be a power of two dividing
N. A contiguous one-dimensional buffer of complex doubles (formatZd, e.g. a numpycomplex128array) is read in place; anything else is converted, and may hold anynumbers.Complex.
- class vfhe.arith.ComplexPolynomial(ring: ComplexRing)¶
An element of a
ComplexRing:Ncomplex coefficients, held natively inobj.- 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; anynumbers.Complexis accepted.
- class vfhe.arith.Multiprecision¶
The bridge between RNS residues and multiprecision integers: loads Python integers into base-
2^52digit 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
primesis given in;from_polynomialis what matches them to a ring.hat_qis the per-prime factor to apply in RNS before reconstructing, anddthe digit count theMPPolynomialaccumulator needs. RaisesValueErrorwhen the moduli admit no single-digit Barrett reconstruction.
- static limbs(x: int, d: int) list[int]¶
xas exactlydbase-2^52 digits.
- from_polynomial(poly: RNSPolynomial, crt_consts: dict)¶
Reconstruct
poly’s coefficients as multiprecision integers.crt_constsmust have been built bycompute_crt_constsover 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 inRNSRing.primesorder, and the native reconstruction walks the ring’s mask, so in ascending base index.polyis left in the coefficient domain. The returned handle frees its native allocation when it is collected.
- class vfhe.arith.CUDARing(*args, **kwargs)¶
An
RNSRingwhose 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.
hostis that ring.Build the ring; see
Ringfor what each parameter means.implementationandbackendare the keywordsRinguses to pick a class. Reaching here throughRingthey 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.- 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.ellrows ofring.Nresidues on the device.repris 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.- 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_uint64returns 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
specand implementexceptional_set_size. Everything else has a default here that an implementation may override when it can do better.- 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.
- 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.