use backend::hal::{ api::{VmpPMatAlloc, VmpPMatAllocBytes, VmpPMatPrepare}, layouts::{Backend, Data, DataMut, DataRef, Module, Scratch, VmpPMat}, }; use crate::layouts::{GGLWETensorKey, Infos, prepared::GGLWESwitchingKeyExec}; #[derive(PartialEq, Eq)] pub struct GGLWETensorKeyExec { pub(crate) keys: Vec>, } impl GGLWETensorKeyExec, B> { pub fn alloc(module: &Module, n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank: usize) -> Self where Module: VmpPMatAlloc, { let mut keys: Vec, B>> = Vec::new(); let pairs: usize = (((rank + 1) * rank) >> 1).max(1); (0..pairs).for_each(|_| { keys.push(GGLWESwitchingKeyExec::alloc( module, n, basek, k, rows, digits, 1, rank, )); }); Self { keys } } pub fn bytes_of(module: &Module, n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank: usize) -> usize where Module: VmpPMatAllocBytes, { let pairs: usize = (((rank + 1) * rank) >> 1).max(1); pairs * GGLWESwitchingKeyExec::bytes_of(module, n, basek, k, rows, digits, 1, rank) } pub fn from( module: &Module, other: &GGLWETensorKey, scratch: &mut Scratch, ) -> GGLWETensorKeyExec, B> where Module: VmpPMatAlloc + VmpPMatPrepare, { let mut tsk_exec: GGLWETensorKeyExec, B> = Self::alloc( module, other.n(), other.basek(), other.k(), other.rows(), other.digits(), other.rank(), ); tsk_exec.prepare(module, other, scratch); tsk_exec } } impl Infos for GGLWETensorKeyExec { type Inner = VmpPMat; fn inner(&self) -> &Self::Inner { &self.keys[0].inner() } fn basek(&self) -> usize { self.keys[0].basek() } fn k(&self) -> usize { self.keys[0].k() } } impl GGLWETensorKeyExec { pub fn rank(&self) -> usize { self.keys[0].rank() } pub fn rank_in(&self) -> usize { self.keys[0].rank_in() } pub fn rank_out(&self) -> usize { self.keys[0].rank_out() } pub fn digits(&self) -> usize { self.keys[0].digits() } } impl GGLWETensorKeyExec { // Returns a mutable reference to GLWESwitchingKey_{s}(s[i] * s[j]) pub fn at_mut(&mut self, mut i: usize, mut j: usize) -> &mut GGLWESwitchingKeyExec { if i > j { std::mem::swap(&mut i, &mut j); }; let rank: usize = self.rank(); &mut self.keys[i * rank + j - (i * (i + 1) / 2)] } } impl GGLWETensorKeyExec { // Returns a reference to GLWESwitchingKey_{s}(s[i] * s[j]) pub fn at(&self, mut i: usize, mut j: usize) -> &GGLWESwitchingKeyExec { if i > j { std::mem::swap(&mut i, &mut j); }; let rank: usize = self.rank(); &self.keys[i * rank + j - (i * (i + 1) / 2)] } } impl GGLWETensorKeyExec { pub fn prepare(&mut self, module: &Module, other: &GGLWETensorKey, scratch: &mut Scratch) where DataOther: DataRef, Module: VmpPMatPrepare, { #[cfg(debug_assertions)] { assert_eq!(self.keys.len(), other.keys.len()); } self.keys .iter_mut() .zip(other.keys.iter()) .for_each(|(a, b)| { a.prepare(module, b, scratch); }); } }