vfhe.mlwe¶
LWE, Module-LWE and MGSW over the vfhe.arith ring: MLWE_Scheme with MLWE, MLWE_Key and MLWE_Set, LWE_Key and LWE, MGSW_Scheme and MGSW, and the gates CMUX and NCMUX.
A scheme is built over vfhe.arith.RNSRing levels and draws every key, mask
and noise from its random source, so MLWE_Scheme(ring, random=Random(seed))
is reproducible. Keys for key switching, MGSW encryptions and the bootstrapping
keys vfhe.fhe makes of them are sampled through one kernel on up to
n_threads threads, each sample from seeds of its own taken in order, so a
key never depends on the thread count.
>>> from vfhe.arith import Ring
>>> from vfhe.mlwe import MLWE_Scheme
>>> scheme = MLWE_Scheme(Ring(256, 120, split_degree=1))
>>> key = scheme.key_gen_sparse(32, 3.2)
>>> len(key.key) == scheme.r
True
- vfhe.mlwe.CMUX(in1: MLWE, in2: MLWE, selector: MGSW) MLWE¶
The controlled multiplexer:
in1 + selector * (in2 - in1)by external product, so an encryption of 0 selectsin1and of 1 selectsin2.
- class vfhe.mlwe.LWE(ring: RNSRing, m: list[int] | None = None, key: LWE_Key | None = None, is_trivial: bool = False, obj=None, n: int | None = None)¶
An LWE sample of dimension
noverring’s primes:mencrypted underkey, a noiseless sample ofmwithis_trivial, an adopted native sampleobj, or an empty one.- linear_decrypt(key: LWE_Key, recompose: bool = False) list[int] | int¶
The linear part of decrypting this sample under
key.This is
b - <a, s>per limb (the encoded message plus the noise), CRT-recomposed into one integer withrecompose.
- class vfhe.mlwe.MGSW(scheme: MGSW_Scheme, obj: list[MLWE] | None = None)¶
An MGSW ciphertext of an
MGSW_Scheme:objholds its(r + 1) * ellMLWE samples, one per gadget row.- multiply_by_monomial(exponent: int, minus_one: bool = False) MGSW¶
An MGSW of
m * X^exponent(orm * (X^exponent - 1)withminus_one) from this MGSW ofm: every row multiplied asMLWE.multiply_by_monomial()does, the transformed monomial built once for all of them. Rows keep their representation.
- property gadget_size: int¶
what C strides the array by.
Read off the key itself rather than the scheme, since a key encrypted at a level carries the gadget for that level’s primes only.
- Type:
Gadget keys per component of the key
- check_level(sample: MLWE) None¶
Raises unless this key was encrypted for
sample’s level.A product reads one gadget element per digit of the sample and divides by the ratio the key’s gadget was scaled with, both of which follow the level the key was encrypted for.
- internal_product(other: MGSW, n_threads: int = 0) MGSW¶
The MGSW of the product of the two messages: the external product of
selfwith every row ofother, laid out asotherand over its ring.selfmust consume samples overother’s rows’ ring. Without special primes that is the ring both live in, andselfis encrypted for level 0. With special primesother’s rows live over its key ring, which is no level of its own scheme:selfthen belongs to a scheme where that ring is a level (one more special prime above it), encrypted for that level – which keeps the rows over the key ring, the noise of a product with a special prime.
- class vfhe.mlwe.MLWE(scheme: MLWE_Scheme, lvl: int | None = None, ring: RNSRing | None = None, rank: int | None = None, obj=None)¶
A Module-LWE sample over
ringat levellvl:rmask components and the body, held natively inobj. It is the ciphertext of every scheme, with+,-and*and the scheme’s operations on it.- seed: bytes | None = None¶
The seed the mask was drawn from (
MLWE_Scheme.sample), or None. Kept by copies only. An in-place change of the mask leaves it stale; writers check it against the mask before relying on it.
- property repr¶
Which domain every component of this sample is in.
Setting it stamps the same answer into the C structure. The generic kernels refuse to combine elements from different domains, so the two sides must not drift: this is the one place that writes either.
- new_like(lvl: int | None = None, ring: RNSRing | None = None, rank: int | None = None) CtT¶
Allocates an empty ciphertext of the same concrete type as
self.Operations that derive a ciphertext allocate it here, so a subclass (e.g.
CKKS_Ciphertext) keeps its type and metadata. With neitherlvlnorring, the result hasself’s ring (special primes included), level, rank andis_extended; otherwiselvldefaults toself.lvlandringandrankdefault as in__init__().
- multiply_by_monomial(exponent: int, minus_one: bool = False) CtT¶
self * X^exponent, orself * (X^exponent - 1)withminus_one, for any integerexponent(X^N = -1).The result has
self’s ring (special primes included), level, type and representation. In the coefficient domain the product is a signed shift, adding no noise beyond permuting it; in the NTT domain it is the pointwise product with the monomial’s transform, which saves the two transforms a shift would need there.
- classmethod from_components(scheme: MLWE_Scheme, a: Sequence[RNSPolynomial], b: RNSPolynomial, lvl: int | None = None) CtT¶
The sample with mask
a(one polynomial per component) and bodyb, all over one ring: a level ofscheme, or another ring of it such as a special one. The polynomials are copied (into the NTT domain), so they may be temporaries; the rank islen(a).lvldefaults to the ring’s level,-1for a ring that is none.
- round_division(ring: RNSRing | None = None, lvl: int | None = None, n_threads: int = 0) CtT¶
Round-divide the ciphertext down into a smaller (quotient) ring.
The destination is given either as
ringor as a level indexlvlintoscheme.rings(exactly one must be supplied). The dropped primes are those in the current ring but not the destination. Afterwardsself.lvlis set to the destination’s index inscheme.rings(its level), not its prime count.
- mod_reduce(ring: RNSRing | None = None, lvl: int | None = None) CtT¶
Reduces the ciphertext into a smaller (quotient) ring, in place.
Drops the primes the destination lacks without dividing the value, unlike
round_division(): the linear decryption is kept modulo the smaller modulus only. Giveringorlvl; the domain is kept.
- vfhe.mlwe.NCMUX(in1: MLWE, in2: MLWE, selector: MGSW, aut_minus1: MLWE_Set | list[MLWE_Set]) MLWE¶
CMUXfor a selector encrypting a bit through its negation: the gate the bootstraps evaluate with the key-switch key of the automorphismX -> X^-1,aut_minus1, atin1’s level.
- vfhe.mlwe.CMUX_batch(in1: list[MLWE], in2: list[MLWE], selector: MGSW, n_threads: int = 0) list[MLWE]¶
CMUX(in1[i], in2[i], selector)for everyi: one selector over many pairs, the multiplexers run in parallel. Each pair is at one level, whichselectorwas encrypted for. The results are left canonical.
- class vfhe.mlwe.GadgetParams(log_base: int | None = None, digits: int | None = None, primes_per_digit: int = 1)¶
How a gadget product decomposes an element, which is what its keys are generated for.
log_baseNoneis the RNS gadget: one digit per prime, the residue, or withprimes_per_digitaone per group ofaprimes, the value modulo their product.log_basewis the radix gadget: each residue split into base-2^wdigits, of which the topdigitsare kept (all by default). Keeping fewer than a prime has is the approximate decomposition, over one prime only; seeMLWE_Scheme.gadget_scalars(). Whether the digits are balanced (balanced) is not here: keys do not depend on it.- native(balanced: bool = True)¶
The parameters as the native products take them (a
GadgetParams *), with balanced digits ifbalanced.
- class vfhe.mlwe.IntegerMatrix(rows: Sequence[Sequence[int]] | Buffer)¶
A matrix of integers, for multiplying vectors of ring elements by it (
RNSRing.integer_linear_combinations()).rowsis either a sequence of rows of Python integers or a two-dimensional buffer of signed 64-bit integers in row-major order (C order), for instance a NumPy array of dtypeint64. A buffer is read in place, not copied, so it must not change while the matrix is in use. Every entry must fit in a signed 64-bit integer.The first product with elements over some primes prepares a native copy of the matrix for them (
prepared), which later products reuse.- prepared(ring: RNSRing) Any¶
Return the native form of the matrix for elements of
ring: aRNS_IntegerMatrix(rns_integer_matrix_new) holding a copy of the matrix with its entries reduced modulo each of the ring’s primes.There is one such form per base of primes (the primes of all the rings of one degree and split degree), kept for the life of the matrix. When
ringhas primes the form does not cover yet, it is rebuilt for those and the ones it covered, so a chain of levels shares one form.
- class vfhe.mlwe.MLWE_Key(key: list[list[int]], sigma_err: float, scheme: MLWE_Scheme, ring: RNSRing | None = None)¶
A secret key of an
MLWE_Scheme:keyholds itsscheme.rcoefficient vectors andsigma_errthe noise width of its encryptions.- extended_key_obj() Any¶
The native key an extended product decrypts under, over this key’s ring:
MLWE_Scheme.quadratic_key_polys(), then thes_i. Built on first use and cached on the key.
- class vfhe.mlwe.MLWE_Scheme(rings: list[RNSRing] | RNSRing, special_primes: int = 0, special_rings: list[RNSRing] | None = None, max_lvl: int | None = None, module_rank: int = 1, balanced: bool = True, random: Random | None = None)¶
A leveled Module-LWE scheme over a chain of
RNSRinglevels: keys, encryption and linear decryption, homomorphic addition and multiplication, key switching and automorphisms, every sample drawn from itsrandomsource.Create a leveled scheme in one of two initialization modes.
Single
RNSRing: the level chain is derived automatically by dropping the top prime one at a time.special_primesreserves that many top primes as the special (key-switching) primes, andmax_lvlcaps the number of levels, by default every one down to a single prime.List of
RNSRing: the levels are given explicitly.rings[i]is leveliandspecial_rings[i]its special-prime-extended ring (required whenspecial_primes > 0; defaults toringsotherwise). This allows non-nested level rings, e.g. for rational rescaling.
balanceddecomposes against the RNS gadget into centered digits, in(-p_j/2, p_j/2], rather than into residues in[0, p_j), and against the radix gadget into balanced base-2^wdigits of the centered residue, rather than into the residue’s unsigned digits (w = 1always takes the unsigned ones, which are no larger). The balanced digits are in[-2^(w-1), 2^(w-1)), except the top one, which carries what the others leave and is in[-2^(w-1), 2^(w-1)]. The keys are the same either way, and the balanced digits add about one bit less noise standard deviation at the same cost. The key-switch keys the scheme generates carry the choice, andMGSW_Schemefollows it.randomis the source every key, mask and noise of the scheme is drawn from: the entropy stream when None, or a seededvfhe.crypto.random.Random, under which the scheme is reproducible.- random¶
The source the scheme’s samplers draw from.
- property parameters: SchemeParameters¶
What this scheme is, for equality and for matching a stored scheme to a live one.
- property extended_rank: int¶
Rank of the extended (not-yet-relinearized) product of two samples.
The product lives in the symmetric square of the ciphertext module:
r*(r+1)/2quadratic components plus r linear ones (2 at rank 1). Seetensor_product().
- level_of_ring(ring: RNSRing, strict: bool = True) int¶
Return the level index of
ringinself.rings.Rings are identified by their RNS
mask(their prime set), so an on-the-fly quotient with the same primes as a scheme level still resolves to that level. A ring outsideself.rings(e.g. a special/extended ring) raises whenstrictis set, or resolves to the sentinel level-1whenstrictisFalse.
- key_gen(sigma_err: float, distribution: str = 'ternary') MLWE_Key¶
A secret key drawn from
distributionover allN * rcoefficients, with error parametersigma_err."ternary", the only one so far, draws every coefficient uniformly from{-1, 0, 1}. For a key with a fixed number of non-zero coefficients, seekey_gen_sparse().
- gadget_scalars(lvl: int, gadget_params: GadgetParams | None = None, ring: RNSRing | None = None, primes: int | None = None) list[list[int]]¶
The gadget a key at
lvlmust be generated against.One entry per gadget element, each a per-prime scaling vector to multiply a key polynomial by (zero in every slot but one, or but a group’s, so the product is that multiple of the slots’ CRT idempotent).
The default gadget is the RNS one: element
iisP * e_i, one per prime, and a key switch decomposes an element into its residues. With the radix gadget,gadget_params.log_basew, each of those splits intoceil(log2(p_i) / w)elementsP * 2^(w*k) * e_iand the key switch decomposes each residue into base-2^wdigits, so every product it accumulates is bounded by2^winstead of by the prime. That is what makes key-switching usable without special primes, atceil(log2(p_i) / w)times the keys and the work.wmust be below the bit size of every prime of the key’s ring.With
gadget_params.primes_per_digita(RNS gadget only), the primes form groups ofa(the last may be smaller) and elementJisP * e_J, the idempotent of groupJ: a key switch decomposes an element into its values modulo each group’s productQ_J, lifted by the fast base conversion, aboutatimes fewer keys and products. A digit is then up to abouta * Q_J / 2, whichPmust make up for: the key switch’s noise is aboutQ_J / Ptimes the error of the keys, scaled as for the per-prime gadget. Nothing checks thatPdoes.The key ring is level
lvl’s special ring and every one of its primes carries a gadget element;ringandprimesoverride that, for a key that lives in a fixed ring while the ciphertexts it consumes descend (MGSW).The elements are ordered as the key switch consumes them: by the base index of their prime, ascending, over the primes of level
lvl’s ring, then the primes it does not carry (the special ones). That is notring.primesorder unless the ring’s prime indices ascend. Groups follow the same order, the level’s primes and the others grouped apart.gadget_params.digitskeeps only the topdigitsdigits of every residue (all of them by default). Keeping fewer than a prime has is the approximate gadget decomposition: a residue is rounded to a multiple of2^(w * dropped),droppedthe digits left out, which adds at most half of that times the key. It needs a level over one prime when the level’s primes lose digits – over several, the error would be multiplied by a CRT idempotent, which is not small.
- quadratic_key_polys(key: MLWE_Key) list[RNSPolynomial]¶
The quadratic key terms of the tensored product, in slot order.
These are
-(s_i * s_j)for every pairi <= jin lexicographic order – the extended key thattensor_product()’s quadratic slots decrypt under (see that method for the layout). For rank 1 this is just[-(s_0 * s_0)].
- gen_rlk(key_out: MLWE_Key, quad_polys: MLWE_Key | list[RNSPolynomial], lvl: int | None = None, gadget_params: GadgetParams | None = None, n_threads: int = 0)¶
Relinearization key for the rank-r product.
quad_polysholds ther*(r+1)/2quadratic key terms in the slot order oftensor_product()(e.g.[-(s_0 * s_0)]for rank 1); pass theMLWE_Keyitself to have them derived byquadratic_key_polys(). The resulting key-switch set has these real keys plus r NULL slots for the linear components, consumed byrelinearize()/multiply().gadget_paramschooses the gadget (the RNS one by default); seeGadgetParamsandgadget_scalars().
- gen_ksk(key_out: MLWE_Key, key_in: MLWE_Key | list[RNSPolynomial], lvl: int | None = None, gadget_params: GadgetParams | None = None, n_threads: int = 0, hybrid: bool = True)¶
Key-switch key from
key_intokey_out, for one level or all.gadget_paramschooses the gadget (the RNS one by default); seeGadgetParamsandgadget_scalars(). The gadget is fixed here, travels with the key, and is whatkeyswitch()decomposes against.By default the key lives in the level’s special ring, and a key switch divides its products by the special primes. With
hybrid=Falseit lives in the level’s own ring and nothing is divided (a BV key switch), for akey_outthat must only be used at that modulus, such as a sparse key. Its noise grows with the gadget’s digits, so pair it with a small radix. Without special primes the two are the same.
- gen_ksk_automorphism_set(key_out: MLWE_Key, key_in: MLWE_Key, generators: list[int], lvl: int | None = None, gadget_params: GadgetParams | None = None, n_threads: int = 0)¶
One automorphism key per generator, shaped as
gen_ksk_automorphism()returns it. The keys of a level are drawn in one batch, which is what lets many small keys use the threads.
- automorphisms(c: CtT, gens: Sequence[int], ksks: Sequence[MLWE_Set | list[MLWE_Set]], n_threads: int = 0) list[CtT]¶
Applies each automorphism
gens[i]toc, with keyksks[i].Same results as
automorphism()per generator, up to noise, butcis decomposed once and the decomposition reused (hoisting), so each extra automorphism only costs its key products. All keys must share a gadget and a ring, as automorphism keys generated together for one level do.
- automorphism_batch(cts: Sequence[CtT], gens: Sequence[int], ksks: Sequence[MLWE_Set | list[MLWE_Set] | None], n_threads: int = 0) list[CtT]¶
automorphism(cts[i], gens[i], ksks[i])for everyi.The ciphertexts must share a level; they may be in either domain and are not modified. The results are in the coefficient domain. A generator of 1 copies the ciphertext, and its key may be
None.
- automorphism_sum(cts: Sequence[CtT], gens: Sequence[int], ksks: Sequence[MLWE_Set | list[MLWE_Set] | None], n_threads: int = 0) CtT¶
sum_i automorphism(cts[i], gens[i], ksks[i]).Cheaper than summing
automorphism_batch(): the key switches share one division by the special primes, so the sum also carries a single rounding error. The keys must share a ring and pass-through components, as automorphism keys for one level do. The ciphertexts must share a ring, level and rank; they may be in either domain and are not modified. The result is in the coefficient domain. A generator of 1 adds its ciphertext as is, and its key may beNone.
- gen_automorphism_mux_keys(key: MLWE_Key, selections: Sequence[tuple[int, int]], lvl: int, gadget_params: GadgetParams | None = None, n_threads: int = 0) list[MLWE_Set]¶
One
automorphism_mux()key per(gen, bit)inselections, for ciphertexts atlvlunderkey.Each key switches from
(bit * Aut_gen(s), bit)tos. Keys with bit 0 are drawn like the others, so the keys do not reveal the bits. All are drawn in one batch onn_threads(0: the library limit);gadget_paramsis as forgen_ksk().
- automorphism_mux(c: CtT, gens: Sequence[int], ksks: Sequence[MLWE_Set], n_threads: int = 0) CtT¶
sum_d b_d * automorphism(c, gens[d]),b_dthe bit encrypted inksks[d](gen_automorphism_mux_keys()).With exactly one bit set, this applies the selected automorphism without revealing which: the B-to-1 mux-rotate of [CHKS25].
cis decomposed once for all terms, and the sum is divided by the special primes once. The keys must be forc’s level and share a gadget. The result is in the coefficient domain;cis not modified.
- automorphism_mux_batch(cts: Sequence[CtT], gens: Sequence[int], ksks: Sequence[Sequence[MLWE_Set]], n_threads: int = 0, *, in_place: bool = False) list[CtT]¶
automorphism_mux()of eachcts[i]with keysksks[i], all over the samegens, in one native call. Within_place, the results overwritects.
- linear_combination(cts: Sequence[CtT], coefficients: Sequence[RNSPolynomial]) CtT¶
sum_i coefficients[i] * cts[i], with plaintext coefficients.Accumulated in one pass. All operands must be over one ring, and
ctsmust share type, level and rank. Operands not in the NTT domain are converted in place.
- linear_combinations(cts: Sequence[CtT], rows: Sequence[Sequence[RNSPolynomial | None]] | PlaintextMatrix | IntegerMatrix, n_threads: int = 0) list[CtT]¶
One
linear_combination()ofctsper row of coefficients (a plaintext matrix times a vector of ciphertexts).Noneskips a term. A matrix applied to many vectors can be prepared once as aPlaintextMatrix.With an
IntegerMatrix, the coefficients are integers. The results are in the domain the ciphertexts are in. When the ciphertexts are not all in one domain, they are moved to the NTT domain first. Each component is one integer-matrix product, as inRNSRing.integer_linear_combinations(). On the generic path instead, each nonzero weight is one pass over its ciphertext; that is the path taken undervfhe.arith.set_generic_onlyand while the execution tape records.
- trace(c: CtT, ksk: MLWE_Set | list[MLWE_Set]) CtT¶
The trace
Tr_(K/Q)ofc’s message: the result decrypts toNtimes its constant coefficient. Evaluated over the tower of power-of-two cyclotomics, one automorphism per level [AP13], with the keys ofgen_ksk_trace()’s default generators (N + 1, N/2 + 1, ..., 3).normalized_trace()gives the constant without the factor and with less noise.
- normalized_trace(c: CtT, ksk: MLWE_Set | list[MLWE_Set], n: int = 1) CtT¶
The normalized trace
(n / N) Tr_(K/K_n)[AP13] ofc,K_nthe subringZ[X^(N/n)], each level halved before its automorphism after [LY26]: the result decrypts to the coefficients ofc’s message at the multiples ofN / nand to zero elsewhere – withn = 1, to its constant coefficient, whichtrace()gives multiplied byN. Because of the halving, the noise is that oflog2(N / n)key switches, which later levels do not amplify.kskholds the automorphism keys for2^j + 1,j = 1, ..., log2 N(gen_ksk_trace()with those generators, as fortrace_pack()).
- trace_pack(vec: list[MLWE], ksk: MLWE_Set | list[MLWE_Set], n_threads: int = 0) MLWE¶
Packs the constant coefficients of the
len(vec)samples (a power of two, at one level) into one: it decrypts to the constant coefficient ofvec[k]’s message atk * N / len(vec), and to junk elsewhere. The packing of [CDKS21] with each level’s difference halved before its automorphism [LY26], so the values keep their scale and the noise grows withlog2 len(vec)key switches rather than withlen(vec)^2.kskholds the automorphism keys for2^j + 1,j = 1, ...(gen_ksk_trace()with those generators). The samples ofvecare overwritten; the result isvec[0]. Thelen(vec) / 2^jpackings of leveljare independent and run in parallel.
- extract_lwe(c: MLWE, idx: int) LWE¶
The LWE sample of coefficient
idxofc, under the keyMLWE_Key.extract_lwe_keygives.
- gen_packing_ksk(key_out: MLWE_Key, lwe_key: LWE_Key, lvl: int = 0, gadget_params: GadgetParams | None = None, n_threads: int = 0) MLWE_Set¶
The key
packing_keyswitchtakes: for every coefficients_ioflwe_key, encryptions ofs_itimes the gadget underkey_out, at levellvl(any dimension).gadget_paramsis as ingen_ksk.
- packing_keyswitch(extracted: list[LWE], packing_key: MLWE_Set, lvl: int = 0) MLWE¶
One sample at level
lvlwhose coefficientkdecrypts to whatextracted[k]does, under the keypacking_keywas generated for (bygen_packing_ksk). The samples may come from a ring of another dimension, but must be over the primes of that level.
- level_with_primes(ring: RNSRing) int¶
The level of this scheme over the primes of
ring, compared by value, soringmay be of another dimension.
- gen_ring_switch_key(key_out: MLWE_Key, key_in: MLWE_Key, lvl: int, gadget_params: GadgetParams | None = None, n_threads: int = 0, hybrid: bool = True) MLWE_Set¶
The key
ring_switch[GHPS12] takes fromkey_in, of a scheme overR_N, tokey_out, of this one overR_n, at levellvl. One dimension divides the other,kthe ratio; the ranks are free.Down (
N = k n): for each components_iofkey_in, keys fors_i^(0)andY s_i^(k - j),j = 1, ..., k - 1, wheres_i^(l)holds coefficientsl + k mofs_i. Up (n = k N): a key fors_i(X^k).gadget_params,n_threadsandhybridare as ingen_ksk.
- ring_switch(c: MLWE | Sequence[MLWE], ksk: MLWE_Set, n_threads: int = 0) MLWE¶
Ring switching [GHPS12]:
c, a sample of a scheme overR_N, as a sample of this one overR_nunder the keykskswitches to (gen_ring_switch_key), at the level withc’s primes.R_nisZ[X^k]insideR_Nor containsR_NasZ[Y^k], whichever the dimensions say.Down (
N = k n),cis read as a sample of rankk roverR_nand key-switched (where [GHPS12] key-switches into the subring and traces the ciphertext); the result decrypts to coefficientsk mof whatcdecrypts to, atm: exactly the message when it lies inZ[X^k], its other coefficients dropped otherwise. Up (n = k N), it decrypts tom(Y^k); given a list of up toksamples (one ring, one rank), tosum_i Y^i m_i(Y^k), coefficienti + k mholding coefficientmofm_i– withkof them, the inverse of the split going down. The only noise added is one key switch’s.
- sample(msg: RNSPolynomial, key: MLWE_Key, out: MLWE | None = None, lvl: int | None = None, seeded: bool | None = None) MLWE¶
Samples an MLWE ciphertext of the given message polynomial under the given key.
- Parameters:
msg – The message polynomial.
key – The MLWE key.
out – Optional MLWE object to store the result.
seeded – Expand the mask from a fresh 32-byte seed, kept as
MLWE.seed(default:seeded_encryption).
- Returns:
The sampled MLWE ciphertext.
- sample_batch(msgs: Sequence[RNSPolynomial], key: MLWE_Key, lvl: int = 0, n_threads: int = 0) list[MLWE]¶
sample()of each ofmsgs, at levellvl, in one native call.The messages must be over the level’s ring. Each sample is drawn as
sample_scaled()draws one: from a fresh mask seed, kept asMLWE.seed, and a fresh secret noise seed, all drawn in order on the calling thread, so the samples do not depend on the thread count. They come back in the NTT domain, asciphertext_type.
- sample_scaled(msgs: Sequence[RNSPolynomial], scalars: Sequence[Sequence[int]], key: MLWE_Key, lvl: int | None = None, n_threads: int = 0) list[MLWE]¶
Fresh samples of every message times every scalar, message-major.
Entry
i * len(scalars) + kencryptsmsgs[i] * scalars[k]underkeyand in its ring, where the messages must live. A scalar is one integer per prime of that ring, inring.primesorder, asgadget_scalars()gives them. Key generation samples through here.Each sample is a function of a mask seed, kept as
MLWE.seedassample()keeps it, and a secret noise seed, all drawn in order on the calling thread, so the samples do not depend on the thread count: over a seededrandomany count gives the same keys. They come back in NTT form, where keys are used.
- linear_decrypt(rlwe: MLWE, key: MLWE_Key, out: RNSPolynomial | None = None, ring: RNSRing | None = None)¶
The linear part of decrypting
rlweunderkey, in the NTT domain.This is
b - sum_i a_i * s_i: the encoded message plus the noise, before any rounding or decoding.With
ring(a quotient of the ciphertext’s ring), it is computed modulo that smaller modulus only.An extended product (rank
extended_rank, seemultiply()) is decrypted under the extended key oftensor_product()’s slot order,-(s_i * s_j)for the quadratic components ands_ifor the linear ones, which gives the product of its factors’ linear decryptions.
- tensor_product(in1: MLWE, in2: MLWE) list[RNSPolynomial]¶
Symmetric tensor product of the r+1 components of
in1andin2.Since
linear_decrypt(c) = b - sum_i a_i * s_i, the product of the two linear decryptions is quadratic in the key:b1*b2 - sum_i (a1_i*b2 + b1*a2_i) * s_i + sum_{i<=j} q_ij * s_i*s_j
with
q_ij = a1_i*a2_j + a1_j*a2_i(i < j) andq_ii = a1_i*a2_i. The returned polynomials follow the extended key’s slot order: ther*(r+1)/2quadratic componentsq_ij(pairsi <= j, lexicographic), then the r linear components, then the constant termb1*b2last. Their keys are-(s_i * s_j)for the quadratic slots (seequadratic_key_polys()) ands_ifor the linear ones, which is why relinearization key-switches the former and passes the latter through.At rank 1 the layout coincides with the convolution of the coefficient vectors
(a, b); at higher ranks it does not (distinct key terms would collide in a single index-sum slot).- Parameters:
in1 – The first MLWE ciphertext.
in2 – The second MLWE ciphertext.
- Returns:
A list of
extended_rank + 1RNSPolynomial objects.
- multiply(in1: CtT, in2: MLWE, ksk: MLWE_Set | list[MLWE_Set] | None = None, n_threads: int = 0) CtT¶
Tensors the two ciphertexts and (optionally) relinearizes.
- Parameters:
in1 – The first MLWE ciphertext.
in2 – The second MLWE ciphertext.
ksk – The relinearization key set. If
None, relinearization is skipped and the extended product (rankextended_rank) is returned; feed it torelinearize()to reduce it back to rank r.
- Returns:
A rank-r product when
kskis given, otherwise the extended product of rankextended_rank(withis_extendedset).
- multiply_batch(lhs: Sequence[CtT], rhs: Sequence[MLWE], ksk: MLWE_Set | list[MLWE_Set] | None = None, n_threads: int = 0, *, lvl: int | None = None) list[CtT]¶
multiply(lhs[i], rhs[i], ksk)for everyi. All ciphertexts must share one ring and level.With
lvl(andksk), each product is also round-divided to that level (MLWE.round_division()), whose ring must be a quotient of the operands’; the results are then in the coefficient domain.
- round_division_batch(cts: Sequence[CtT], lvl: int, n_threads: int = 0) list[CtT]¶
MLWE.round_division()of each (distinct) ciphertext to levellvl, in place.
- relinearize(c_ext: CtT, ksk: MLWE_Set | list[MLWE_Set], n_threads: int = 0) CtT¶
Relinearize an extended product back to rank r.
Reuses the GHS hybrid key-switch: the rlk key-switches the quadratic components and copies the linear ones through (their NULL slots).
- relinearize_batch(cts: Sequence[CtT], ksk: MLWE_Set | list[MLWE_Set], n_threads: int = 0) list[CtT]¶
relinearize()of each (distinct) extended product, all at one level, in one native call. The products are left in the coefficient domain, asrelinearize()leaves its input.
- class vfhe.mlwe.PlaintextMatrix(rows: Sequence[Sequence[RNSPolynomial | None]])¶
Plaintext coefficients for
MLWE_Scheme.linear_combinations(), checked and laid out once, for a matrix applied to many vectors of ciphertexts.Noneskips a term.The polynomials are moved to the NTT domain and must stay there while the matrix is in use.