Containers
The containers/ directory provides vector-like container abstractions used to store plaintext and secret-shared values within cdough.
Contents:
a_shared_vector.h– Arithmetic shared vector container.b_shared_vector.h– Boolean shared vector container.class_access_vector.h– Vector base providing element-wise operator overloads.e_vector.h– Vector-of-vector wrapper for replicated sharing schemes.encoded_vector.h– Generic encoded vector implementation.encoding.h– Encoding trait helpers.gf2e_overloads.h– PlaceholderNTL::GF2Eoperator overloads (assert if called).mapped_iterator.h– Iterator adaptor for custom containers.dummy_vector.h– Dummy vector for tests and benchmarks.mapping_access_vector.h– Mapping access vector implementation.permutation.h– Container for local and secret-shared permutations.shared_vector.h– Abstract (untyped) secret-shared vector implementation.vector.h– Convenience alias to the default vector type.matrix/– Plaintext and secure matrix containers.tabular/- Encoded Table and Column classes.
-
template<typename T>
class Vector cdough’s wrapper of std::vector<T> that provides vectorized plaintext operations. A mock vector implementation which stores no data and returns nothing (or garbage) for all operations. Most functions do nothing at all, or just compute the appropriate length that their correct equivalent would output. This is useful for testing and profiling, since it is extremely fast and performs no data movement.
- Template Parameters:
T – The type of elements in the Vector (e.g., int, long, long long, etc.)
T – The nominal element type
Public Types
-
using value_type = T
-
using IteratorType = MappedIterator<T, typename std::vector<T>::iterator, typename std::vector<VectorSizeType>::iterator>
-
using value_type = T
-
using IteratorType = MappedIterator<T, typename std::vector<T>::iterator, typename std::vector<VectorSizeType>::iterator>
Public Functions
-
inline void setPrecision(const int fixed_point_precision)
Sets the fixed-point precision.
- Parameters:
fixed_point_precision – - the number of fixed-point fractional bits.
-
inline size_t getPrecision() const
Gets the fixed-point precision.
-
inline void matchPrecision(const Vector<T> &other)
Helper that sets this vector’s precision to match another Vector.
- Parameters:
other – The Vector whose precision should be copied.
-
inline size_t total_size() const
- Returns:
The total number of elements in the vector.
-
inline std::vector<T>::iterator begin()
NOTE: This method is used by the communicator.
- Returns:
An iterator pointing to the first element.
-
inline std::vector<T>::iterator end()
NOTE: This method is used by the communicator.
- Returns:
An iterator pointing to the last element.
-
inline Vector simple_subset_reference(const int _start_index, const int _step, const int _end_index) const
- data. In other words, composition will not work; new mapping pattern replaces the previous one.
This is the generic function in order create a new mapping for this vector. Note: that the function does not allocate a new memory location for data. Note: the mapping maps from the new index space to the original index space for
- Parameters:
_subset_offset – the index of the first element of the original vector to apply the pattern.
_subset_step – the index difference between the mapped to elements within each chunks.
_subset_included_size – the maximum size of each included chunk.
_subset_excluded_size – the maximum size of each excluded chunk. (included and excluded chunks alternate after offset).
_subset_direction – the direction of choosing elements (increasing index = 1) (decreasing index = -1).
_subset_repetition – number of times to repeat same mapped-to-elements after each other.
_subset_cycles – number of times concatenate the whole mapped-to-elements in the new reference.
_subset_offset – the index of the first element of the original vector to apply the pattern. (default = 0)
_subset_step – the index of the difference between each two included elements. (default = 1)
_subset_included_size – the size of the elements on which the pattern is applied. (default = total_size())
- Returns:
Vector that points to the same memory location as the new one but different mapping for the indices. Remaps the index space to choose a number of elements of the current vector. Note: returned Vector points to the same memory location.
- Returns:
Vector that has different index mapping to the original vector elements.
-
inline Vector alternating_subset_reference(const size_t _subset_included_size, const size_t _subset_excluded_size) const
Applies an alternating pattern to include and exclude elements. It applies the pattern starting with the element with
index = _subset_offset. It then keeps alternating elements as included in the pattern of or excluded from the pattern using the_subset_included_sizeand the_subset_excluded_sizefor each included or excluded chunk.- Parameters:
_subset_offset – the index of the first element to apply the pattern.
_subset_step – the difference two each two included elements within the included the chunks.
_subset_included_size – the size of a number of elements that we choosing from.
_subset_excluded_size – the size of a number of elements that we are totally not choosing.
- Returns:
Vectorthat points to the same memory location as the original vector but with different index mapping.
-
inline Vector reversed_alternating_subset_reference(const size_t _subset_included_size, const size_t _subset_excluded_size) const
-
inline Vector repeated_subset_reference(const size_t _subset_repetition) const
Applies a new indexing mapping to the current vector so that each element is repeated a number of times consecutively.
- Parameters:
_subset_repetition – the number of times each element is repeated.
- Returns:
Vectorthat points to the same memory location as the original vector but with different index mapping.
-
inline Vector cyclic_subset_reference(const size_t _subset_cycles) const
Applies a new indexing mapping such that after accessing the last element, we access the first element again and keep accessing the elements in cycles.
- Parameters:
_subset_cycles – the number of cycles the new indexing mapping will contain.
- Returns:
Vectorthat points to the same memory location as the original vector but with different index mapping.
-
inline Vector directed_subset_reference(const size_t _subset_direction) const
Applies a new mapping indexing that controls the order in which the elements accessed.
- Parameters:
_subset_direction – set to (1) to keep current order or (-1) to reverse the order.
- Returns:
Vectorthat points to the same memory location as the original vector but with different index mapping.
-
inline Vector simple_bit_compress(size_t start, size_t step, size_t end, size_t repetition) const
This function extracts bits from current vector and append them in sequence into another vector. The functions chooses the bits by getting the needed parameters to loop through the bits in each element.
- Parameters:
start – index of the first bit to be included (lowest significant).
step – difference in index between each two consecutive bits.
end – index of the last bit bit to be included (most significant)
repetition – number of times each bit will be included.
- Returns:
a new
Vectorthat has only the chosen bits in its elements (less size than input).
-
inline void simple_bit_compress(Vector &res, size_t position) const
simple_bit_compress, optimized for the (i, 1, i, 1) case. This version further operates on a passed vector, rather than returning a new Vector.
- Parameters:
res – vector to compress into
position – single bit position to compress (= start = end)
-
inline void simple_bit_decompress(const Vector &other, size_t start, size_t step, size_t end, size_t repetition)
Function to reverse the simple_bit_compress function. it takes an already compressed
Vectorand assign from it the corresponding bits to the this called onVector.- Parameters:
other – the vector that has the compressed bits.
start – index of the first bit to be included (lowest significant).
step – difference in index between each two consecutive bits.
end – index of the last bit bit to be included (most significant)
repetition – number of times each bit will be included.
-
inline void simple_bit_decompress(const Vector &other, const T &position)
Optimized version of simple_bit_compress for the single- position case.
Note: in testing, setBitMask was not noticeably faster than setBitValue
- Parameters:
other – vector to decompress into this
position – the bit position to decompress
-
inline Vector alternating_bit_compress(size_t start, size_t step, size_t included_size, size_t excluded_size, int direction) const
This function extracts bits from current vector and append them in sequence into another vector. The function chooses bits as follows. First it skips till the start index (from lowest significant). Then it splits the bits into sequences of included chunks and excluded chunks. From the included bits chunks, bits that
stepindex difference apart are chosen. If direction is set to1, picking starts from lowest significant bits. If it is set to-1, picking starts from most significant bits.- Parameters:
start – index of the first bit to start the included/excluded chunks pattern.
step – difference between each two consecutive bits in each included chunk.
included_size – size of each included chunk.
excluded_size – size of each excluded chunk.
direction – direction for picking up the bits in each included_size chunk.
1means least significant first.-1means most significant first.
- Returns:
a new
Vectorthat has only the chosen bits in its elements (less size than input).
-
inline Vector alternating_bit_compress(size_t start, size_t step, size_t included_size, size_t excluded_size) const
-
inline void alternating_bit_decompress(const Vector &other, size_t start, size_t step, size_t included_size, size_t excluded_size, int direction) const
Function to reverse the alternating_bit_compress function. it takes an already compressed
Vectorand assign from it the corresponding bits to the this called onVector.- Parameters:
other – the vector that has the compressed bits.
start – index of the first bit to start the included/excluded chunks pattern.
step – difference between each two consecutive bits in each included chunk.
included_size – size of each included chunk.
excluded_size – size of each excluded chunk.
direction – direction for picking up the bits in each included_size chunk.
1means least significant first.-1means most significant first.
-
inline Vector(size_t _size, T _init_val = 0)
This constructor allows for creating a new vector by just passing initialization parameters for inner `data` variable. @tparam T is a generic type to allow for different constructors for the variabledata.- Parameters:
args – is the packed parameters passed to
datainitializer. Creates a Vector ofsizevalues initialize toinit_val(0 by default).size – The size of the new Vector.
-
inline Vector(std::vector<T> &&_other)
Move constructor
- Parameters:
other – The std::vector<T> whose elements will be moved to the new Vector.
-
inline Vector(std::vector<T> &_other)
Copy constructor
- Parameters:
other – The std::vector<T> whose elements will be copied to the new Vector.
-
inline Vector(std::initializer_list<T> &&elements)
Constructs a new Vector from a list of
Telements.- Parameters:
elements – The list of elements of the new Vector.
-
inline Vector(const Vector &other)
This is a shallow copy constructor.
WARNING: The new vector will point to the same memory location used by
other. To copy the data into a separate memory location, create a new vector first then use assignment operator.- Parameters:
other – The vector that contains the std::vector<T> pointer to be copied.
-
inline Vector &operator=(const Vector &&other)
This is a deep move assignment operator. Applies the move assignment operator to T. Assigns the contents of the
othervector to the this vector. Assumesotherhas the same size as this vector.
NOTE: This method works relatively to the current batch.
- Parameters:
other – The Vector that contains the values to be assigned to this vector.
- Returns:
A reference to this vector after modification.
-
inline Vector &operator=(const Vector &other)
This is a deep copy assignment operator. Applies the copy assignment operator to T. Copies the contents of the
othervector to this vector. Assumesotherhas the same size as this vector.- Parameters:
other – the Vector that contains the values to be copied.
- Returns:
A reference to
thisVector after modification.
-
template<typename OtherT>
inline Vector &operator=(const Vector<OtherT> &other) Copy-and-cast assignment operator. Allows (down)casting elements from a vector of one type into another.
-
inline Vector simple_subset(size_t start, size_t size) const
Returns a new vector that contains all elements in the range [start, end].
NOTE: This method works relatively to the current batch.
- Parameters:
start – The index of the first element to be included in the output vector.
end – The index of the last element to be included in the output vector.
- Returns:
A new vector that contains the selected elements.
-
inline void mask(const T &n)
Masks each element in
thisvector by doing a bitwise logical AND withn.- Parameters:
n – The mask.
-
inline void zero()
Sets every element of this vector to zero.
-
inline Vector bit_level_shift(int log_level_size) const
Creates a new Vector whose i-th element is generated by:
splitting the bit representation of the i-th element of
thisVector into parts of sizelevel_size, andsetting all bits of the least significant half of each part equal to the LSB of the most significant part.
NOTE: This method is used in secure greater-than and works relatively to the current batch.
Moved from private so we can test this method externally.
- Parameters:
log_level_size – log2 of the maximum chunk size (indexes into
LEVEL_MASKS)- Returns:
A new vector that contains elements generated as described above.
-
inline size_t size() const
NOTE: This method works relatively to the current batch.
- Returns:
The number of elements in the vector.
-
inline Vector extend_lsb() const
Elementwise plaintext LSB extension: set all bits equal to the LSB. Note: this is only makes sense for bit shares.
-
inline T &operator[](int index)
Returns a mutable reference to the element at the given
index.
NOTE: This method works relatively to the current batch.
- Parameters:
index – The index of the target element.
- Returns:
A mutable reference to the element at the given
index.
-
inline const T &operator[](int index) const
Returns an immutable reference of the element at the given
index.
NOTE: This method works relatively to the current batch.
- Parameters:
index – The index of the target element.
- Returns:
Returns a read-only reference of the element at the given
index.
-
inline bool same_as(const Vector<T> &other) const
- whose i-th element equals the (i/n)-th bit of the (in)-th element of
Unpacks bits in the elements of `this` vector to create a new vector of size `n`
thisvector.- Parameters:
n – The number of bits to ‘unpack’.
other – The vector to compare
thiswith.
- Returns:
A new Vector that contains
nsingle-bit elements constructed as described above. Checks if the two input vectors (thisandother) contain the same elements.- Returns:
True if
thisvector contains the same elements withother, False otherwise.
-
inline bool starts_with(const Vector<T> &prefix)
Checks if the vector
prefixis a prefix of this vector.- Parameters:
prefix –
- Returns:
true if the argument is a prefix
- Returns:
false otherwise
-
inline void setPrecision(const int fixed_point_precision)
-
inline size_t getPrecision() const
Empty constructor
-
inline Vector(std::vector<T> &&_other)
Move constructor
- Parameters:
_other –
-
inline Vector(std::vector<T> &_other)
Copy constructor from vector
- Parameters:
_other –
-
inline Vector(VectorSizeType _size, T _init_val = {})
Creates a Vector of
sizevalues initialize toinit_val(0 by default).- Parameters:
_size – The size of the new Vector.
_init_val –
-
inline Vector(std::initializer_list<T> &&elements)
Constructs a new Vector from a list of
Telements.- Parameters:
elements – The list of elements of the new Vector.
-
template<std::floating_point FP>
inline Vector(const std::vector<FP> &_other, int fixed_point_precision = 16) Constructor that converts a vector of floating-point numbers to a vector of integers.
- Template Parameters:
FP – - The floating-point type to convert from.
- Parameters:
_other – - The vector of floating-point numbers to convert.
fixed_point_precision – - The number of fractional bits to use for the fixed-point conversion. Default is 16.
-
template<std::ranges::input_range IR>
inline Vector(IR _other) Copy constructor from range
- Parameters:
_other – The input_range whose elements will be copied to the new Vector.
-
inline Vector(const Vector &other)
-
inline Vector bit_arithmetic_right_shift(int shift_size) const
-
inline Vector bit_logical_right_shift(int shift_size) const
-
inline Vector bit_left_shift(int shift_size) const
-
inline Vector bit_xor() const
-
inline void prefix_sum()
-
inline Vector simple_subset(const VectorSizeType &start, const VectorSizeType &step, const VectorSizeType &end) const
-
inline void reset_batch()
-
inline void set_batch(const VectorSizeType &_start_ind, const VectorSizeType &_end_ind)
-
inline VectorSizeType total_size() const
-
inline IteratorType begin() const
-
inline IteratorType end() const
-
inline std::vector<T> as_std_vector() const
Return an empty C++ vector of the given length.
- Returns:
std::vector<T>
-
inline std::vector<T> _get_internal_data() const
Return an empty C++ vector of the given length.
- Returns:
std::vector<T>
-
inline bool has_mapping() const
-
inline Vector simple_subset_reference(const VectorSizeType _start_index, const VectorSizeType _step, const VectorSizeType _end_index) const
Return a dummy vector of the correct size.
- Parameters:
_start_index –
_step –
_end_index –
- Returns:
Vector
-
inline Vector simple_subset_reference(const VectorSizeType _start_index, const VectorSizeType _step) const
-
inline Vector included_reference(const Vector flag) const
Return a bounded dummy vector. Since included_reference is data-dependent, we can’t provide a cardinality-accurate dummy version.
- Parameters:
flag –
- Returns:
Vector
-
inline Vector alternating_subset_reference(const VectorSizeType _subset_included_size, VectorSizeType _subset_excluded_size) const
-
inline Vector reversed_alternating_subset_reference(const VectorSizeType _subset_included_size, VectorSizeType _subset_excluded_size) const
-
inline void simple_bit_decompress(const Vector &other, int start, int step, int end, int repetition)
-
inline Vector alternating_bit_compress(const VectorSizeType &start, const VectorSizeType &step, const VectorSizeType &included_size, const VectorSizeType &excluded_size, int direction) const
-
inline Vector alternating_bit_compress(const VectorSizeType &start, const VectorSizeType &step, const VectorSizeType &included_size, const VectorSizeType &excluded_size) const
-
inline void alternating_bit_decompress(const Vector &other, const VectorSizeType &start, const VectorSizeType &step, const VectorSizeType &included_size, const VectorSizeType &excluded_size, int direction) const
-
inline Vector<T> materialize() const
Dummy vectors have no mapping, so just return this vector.
- Returns:
Vector<T>
-
inline void materialize_inplace()
-
inline Vector mapping_reference(std::vector<VectorSizeType> map) const
Respect the size of the mapping reference.
- Parameters:
map –
- Returns:
Vector
-
template<typename S = VectorSizeType>
inline void apply_mapping(std::vector<S> new_mapping) To apply a mapping for a dummy vector, we only update the length.
- Template Parameters:
S –
- Parameters:
new_mapping –
-
inline void reverse()
-
inline void mask(const T &n)
-
inline void zero()
-
inline Vector bit_level_shift(int log_level_size) const
-
inline Vector reverse_bit_level_shift(int log_level_size) const
-
inline VectorSizeType size() const
-
inline void resize(size_t n)
-
inline void tail(size_t n)
-
inline Vector operator-() const
-
inline Vector operator~() const
-
inline Vector operator!() const
-
inline Vector ltz() const
-
inline Vector extend_lsb() const
-
inline bool same_as(const Vector<T> &other, bool print_warn = true) const
All dummy vectors are equal.
- Parameters:
other –
print_warn –
- Returns:
true Always returns true.
-
inline bool starts_with(const Vector<T> &prefix)
All dummy vectors are prefixes of each other. TODO: check size at least?
- Parameters:
prefix –
- Returns:
true Always returns true.
-
inline Vector(std::shared_ptr<std::vector<T>> _data, std::shared_ptr<std::vector<VectorSizeType>> _mapping = nullptr)
Construct a vector pointing to specific data and mapping Mostly used internally
Default mapping is the identity (null pointer)
-
inline Vector(std::vector<T> &&_other)
Move constructor
- Parameters:
_other – The std::vector<T> whose elements will be moved to the new Vector.
-
inline Vector(std::vector<T> &_other)
Copy constructor from vector
- Parameters:
_other – The std::vector<T> whose elements will be copied to the new Vector.
-
inline explicit Vector(VectorSizeType _size, T _init_val = {})
Creates a Vector of
sizevalues initialize toinit_val(0 by default).- Parameters:
_size – The size of the new Vector.
_init_val – default-initialized value
-
inline Vector(std::initializer_list<T> &&elements)
Constructs a new Vector from a list of
Telements.- Parameters:
elements – The list of elements of the new Vector.
-
template<std::ranges::input_range IR>
inline Vector(IR _other) Copy constructor from range
- Parameters:
_other – The input_range whose elements will be copied to the new Vector.
-
inline Vector(const Vector &other)
This is a shallow copy constructor.
WARNING: The new vector will point to the same memory location used by
other. To copy the data into a separate memory location, create a new vector first then use assignment operator.- Parameters:
other – The vector that contains the std::vector<T> pointer to be copied.
-
inline Vector(Vector &other)
This is a shallow copy constructor.
WARNING: The new vector will point to the same memory location used by
other. To copy the data into a separate memory location, create a new vector first then use assignment operator.- Parameters:
other – The vector that contains the std::vector<T> pointer to be copied.
-
inline Vector construct_like() const
Creates a new Vector with the same structure as this Vector, but with newly allocated empty vectors of the same size.
- Returns:
A new Vector with the same structure but empty contents.
-
inline Vector construct_like(const size_t &size) const
Creates a new Vector with the same structure as this Vector, but with newly allocated empty vectors of a different size.
- Parameters:
size – The size of the new Vector.
- Returns:
A new Vector with the same structure but empty contents.
-
template<std::floating_point FP>
inline Vector(const std::vector<FP> &_other, int fixed_point_precision = 16) Constructor that converts a vector of floating-point numbers to a vector of integers.
- Template Parameters:
FP – - The floating-point type to convert from.
- Parameters:
_other – - The vector of floating-point numbers to convert.
fixed_point_size_the – number of fractional bits to use for the fixed-point conversion. Default is 16.
-
inline void setPrecision(const int fixed_point_precision)
Sets the fixed-point precision.
- Parameters:
fixed_point_precision – - the number of fixed-point fractional bits.
-
inline size_t getPrecision() const
Gets the fixed-point precision.
-
inline Vector bit_arithmetic_right_shift(int shift_size) const
Creates a new Vector that contains all elements of
thisVector right-shifted byshift_size. Arithmetic shift is used: signed types will have their MSB copied. To shift in zero instead, usebit_logical_right_shift.
NOTE: This method works relatively to the current batch.
- Parameters:
shift_size – The number of bits to right-shift each element of
thisVector.- Returns:
A new Vector that contains the right-shifted elements.
-
inline Vector bit_logical_right_shift(int shift_size) const
Creates a new Vector that contains all elements of
thisVector right-shifted byshift_size. This performs logical shift: zeros are shifted into the MSB. To copy the sign, usebit_arithmetic_right_shiftNOTE: This method works relatively to the current batch.- Parameters:
shift_size – The number of bits to right-shift each element of
thisVector.- Returns:
A new Vector that contains the right-shifted elements.
-
inline Vector bit_left_shift(int shift_size) const
Creates a new Vector that contains all elements of
thisVector left-shifted byshift_size.
NOTE: This method works relatively to the current batch.
- Parameters:
shift_size – The number of bits to left-shift each element of
thisVector.- Returns:
A new Vector that contains the left-shifted elements.
-
inline Vector bit_xor() const
Creates a new Vector whose i-th element is a single bit generated by XORing all bits of the i-th element of
thisVector, 0 <= i < size(). (Basically parity check of each element.)
NOTE: This method works relatively to the current batch.
- Returns:
A new Vector that contains single-bit elements generated as described above.
-
inline void prefix_sum()
Compute a prefix sum of this vector. Operates in place; for immutable operation, first copy into a new vector.
-
inline void prefix_sum(const T &(*op)(const T&, const T&))
Arbitrary-operation prefix “sum”. Operation should be associative.
-
inline Vector chunkedSum(const VectorSizeType aggSize = 0) const
Sums each consecutive
aggSizevector elements and returns a new vector containing the aggregated sums.- Parameters:
aggSize – The number of elements to aggregate in each sum.
- Returns:
A new Vector that contains the aggregated sums.
-
inline Vector dot_product(const Vector &other, const VectorSizeType aggSize = 0) const
Computes the dot product of this vector with another vector, aggregating results in chunks of
aggSize. EachaggSizeconsecutive elements contribute to an exactly on dot product element in the result. The size of the resulting vector is determined by theaggSizeparameter.- Parameters:
other – The other vector to compute the dot product with.
aggSize – The number of elements to do dotproduct on for each result element.
- Returns:
A new Vector containing the aggregated dot product results.
-
inline Vector simple_subset(const VectorSizeType &start, const VectorSizeType &step, const VectorSizeType &end) const
Returns a new vector containing elements in the range [start, end] that are
steppositions apart.
NOTE: This method works relatively to the current batch.
- Parameters:
start – The index of the first element to be included in the output vector.
step – The distance between two consecutive elements.
end – The maximum possible index of the last element to be included in the output vector.
- Returns:
A new vector that contains the selected elements.
-
inline void reset_batch()
Sets the current batch equal to the whole vector.
-
inline void set_batch(const VectorSizeType &_start_ind, const VectorSizeType &_end_ind)
Sets start and end index of the current batch. If the start index is negative, the start index is set to zero. If the end index is greater than the Vector’s size, the end index is set the max possible index.
- Parameters:
_start_ind – The index of the first element in the current batch.
_end_ind – The index of the last element in the current batch.
-
inline VectorSizeType total_size() const
- Returns:
The total number of elements in the vector.
-
inline IteratorType begin() const
NOTE: This method is used by the communicator.
- Returns:
An iterator pointing to the first element.
-
inline IteratorType end() const
NOTE: This method is used by the communicator.
- Returns:
An iterator pointing to the last element.
-
inline std::vector<T> as_std_vector() const
Return a new C++ vector with the same data. This is not a reference to the underlying storage.
- Returns:
std::vector<T>
-
inline std::vector<T> _get_internal_data() const
Return the underlying storage of this Vector.
- Returns:
std::vector<T>
-
inline std::span<T> span()
Return a span with a view of the underlying data.
- Returns:
std::span<T>
-
inline std::span<T> batch_span()
Return an unmapped span to the current batch. Useful for protocols that need direct access to the underlying storage.
- Returns:
std::span<T>
-
inline std::span<const T> batch_span() const
Const version of the above.
- Returns:
std::span<const T>
-
inline bool has_mapping() const
Checks whether a mapping exists inside this Vector. Note that this function only checks for existence; thus, a vector with the trivial mapping would return
truehere.- Returns:
true if the Vector has a mapping
- Returns:
false if it does not
-
inline Vector simple_subset_reference(const VectorSizeType _start_index, const VectorSizeType _step, const VectorSizeType _end_index) const
Remaps the vector to reference a subset of the original vector. Returned Vector points to the same underlying storage.
Note: end index is inclusive. To access a single element, use
.simple_subset_reference(i, 1,
i)
- Parameters:
_start_index –
_step –
_end_index – inclusive end index
- Returns:
Vector
-
inline Vector simple_subset_reference(const VectorSizeType _start_index, const VectorSizeType _step) const
Simple subset reference with implicit end index (at the end of the Vector).
- Parameters:
_start_index –
_step –
- Returns:
Vector
-
inline Vector simple_subset_reference(const VectorSizeType _start_index) const
Simple subset reference with implicit step size (1) and end.
- Parameters:
_start_index –
- Returns:
Vector
-
inline Vector slice(const size_t start, const size_t end) const
Take a slice of a vector. This is the same as simple_subset_reference, but the end index is EXCLUSIVE. It also only supports a step size of 1.
The resulting slice will have size
end - start.sliceexpresses natural ranges, e.g.,slice(x, x + s)represents the slice starting atxhaving sizes.slice(x)is equivalent tosimple_subset_reference(x)slice(x, y)is equivalent tosimple_subset_reference(x, 1, y - 1)
- Parameters:
start –
end – exclusive end index
- Returns:
Vector
-
inline Vector slice(const size_t start) const
Take a slice with an implicit end index (at the end of the Vector).
- Parameters:
start –
- Returns:
Vector
-
inline Vector included_reference(const Vector flag) const
Return a view of this vector with only the nonzero positions of
flagincluded. For example, if the base vector is[ 1 2 3 4 5 6 ]and the flag vector is[ 0 0 1 1 0 1 ]then this access pattern returns[ 3 4 6 ].If flag is shorter than this vector, assume all remaining flag values are zero.
NOTE: should we ever need to parallelize this operation, it can be implemented by
(parallel) prefix sum over
flagvectormultiply prefix sum with original
flagvector, placing -1 at all locations where flag=0 and the prefix sum value where flag=1(parallel) copy from non-negative indices
I think this actually needs to be an
exclusive_sum, notinclusivebut this can also be implemented by seeding the prefix sum with -1.- Parameters:
flag –
- Returns:
Vector
-
inline Vector alternating_subset_reference(const VectorSizeType _subset_included_size, const VectorSizeType _subset_excluded_size) const
Applies an alternating pattern to include and exclude elements. Keep alternating elements as included in the pattern or excluded from the pattern using the
_subset_included_sizeand the_subset_excluded_sizefor each included or excluded chunk.- Parameters:
_subset_included_size – the size of a number of elements that we choosing from.
_subset_excluded_size – the size of a number of elements that we are totally not choosing.
- Returns:
Vectorthat points to the same memory location as the original vector but with different index mapping.
-
inline Vector reversed_alternating_subset_reference(const VectorSizeType _subset_included_size, VectorSizeType _subset_excluded_size) const
The same as above, but counting from the end of the Vector.
- Parameters:
_subset_included_size –
_subset_excluded_size –
- Returns:
Vector
-
inline Vector repeated_subset_reference(const VectorSizeType _subset_repetition) const
Applies a new indexing mapping to the current vector so that each element is repeated a number of times consecutively.
- Parameters:
_subset_repetition – the number of times each element is repeated.
- Returns:
Vectorthat points to the same memory location as the original vector but with different index mapping.
-
inline Vector repeated_subset_reference(const VectorSizeType _elements_count, const VectorSizeType _subset_repetition) const
Applies a new indexing mapping to the current vector so that each subset of elements is repeated a number of times consecutively.
- Parameters:
_elements_count – the number of elements in each subset.
_subset_repetition – the number of times each subset is repeated.
- Returns:
Vectorthat points to the same memory location as the original vector but with different index mapping.
-
inline Vector cyclic_subset_reference(const VectorSizeType _subset_cycles) const
Applies a new indexing mapping such that after accessing the last element, we access the first element again and keep accessing the elements in cycles.
- Parameters:
_subset_cycles – the number of cycles the new indexing mapping will contain.
- Returns:
Vectorthat points to the same memory location as the original vector but with different index mapping.
-
inline Vector directed_subset_reference(const int _subset_direction) const
Applies a new mapping indexing that controls the order in which the elements accessed.
- Parameters:
_subset_direction – set to (1) to keep current order or (-1) to reverse the order.
- Returns:
Vectorthat points to the same memory location as the original vector but with different index mapping.
-
inline Vector simple_bit_compress(int start, int step, int end, int repetition) const
This function extracts bits from current vector and append them in sequence into another vector. The functions chooses the bits by getting the needed parameters to loop through the bits in each element.
- Parameters:
start – index of the first bit to be included (lowest significant).
step – difference in index between each two consecutive bits.
end – index of the last bit bit to be included (most significant)
repetition – number of times each bit will be included.
- Returns:
a new
Vectorthat has only the chosen bits in its elements (less size than input).
-
inline void simple_bit_decompress(const Vector &other, int start, int step, int end, int repetition)
Function to reverse the simple_bit_compress function. it takes an already compressed
Vectorand assign from it the corresponding bits to the this called onVector.- Parameters:
other – the vector that has the compressed bits.
start – index of the first bit to be included (lowest significant).
step – difference in index between each two consecutive bits.
end – index of the last bit bit to be included (most significant)
repetition – number of times each bit will be included.
-
inline void pack_from(const Vector &source, const int &position)
Extracts the bit at a given position from each element of the source Vector and stores it in this Vector
- Parameters:
source – The Vector to take bits from
position – The bit position to take
-
inline void unpack_from(const Vector &source, const T &position)
The inverse of pack_from, takes a packed Vector and puts its bits at a position in this Vector. WARNING: Requires that
batch_startbe a multiple of the bit-length of a share ffor proper alignment.- Parameters:
source – The packed Vector to take bits from
position – The bit position to put the bits in
-
inline std::vector<Vector> bit_decomposition() const
This function decomposes each element of the current vector into its bits and appends them into k vectors, where k is the number of bits in the type T. Each of the output vectors contains the bits at a certain index from all elements in the input vector.
- Returns:
a vector of k vectors, each containing the bits at a certain index.
-
inline Vector alternating_bit_compress(const VectorSizeType &start, const VectorSizeType &step, const VectorSizeType &included_size, const VectorSizeType &excluded_size, int direction = 1) const
This function extracts bits from current vector and append them in sequence into another vector. The function chooses bits as follows. First it skips till the start index (from lowest significant). Then it splits the bits into sequences of included chunks and excluded chunks. From the included bits chunks, bits that
stepindex difference apart are chosen. If direction is set to1, picking starts from lowest significant bits. If it is set to-1, picking starts from most significant bits.- Parameters:
start – index of the first bit to start the included/excluded chunks pattern.
step – difference between each two consecutive bits in each included chunk.
included_size – size of each included chunk.
excluded_size – size of each excluded chunk.
direction – direction for picking up the bits in each included_size chunk.
1means least significant first.-1means most significant first. (default:1, LSB first.)
- Returns:
a new
Vectorthat has only the chosen bits in its elements (less size than input).
-
inline void alternating_bit_decompress(const Vector &other, const VectorSizeType &start, const VectorSizeType &step, const VectorSizeType &included_size, const VectorSizeType &excluded_size, int direction = 1) const
Function to reverse the alternating_bit_compress function. it takes an already compressed
Vectorand assign from it the corresponding bits to the this called onVector.- Parameters:
other – the vector that has the compressed bits.
start – index of the first bit to start the included/excluded chunks pattern.
step – difference between each two consecutive bits in each included chunk.
included_size – size of each included chunk.
excluded_size – size of each excluded chunk.
direction – direction for picking up the bits in each included_size chunk.
1means least significant first.-1means most significant first. (default:1)
-
inline Vector<T> materialize() const
Materialize a vector which might have an access pattern applied. If there is no mapping, just return the vector. Otherwise, copy the mapped vector into a new vector (which will have no map).
Useful for communication primitives, which require unmapped vectors.
- Returns:
Vector<T>
-
inline void materialize_inplace()
Materialize a Vector in place: construct a new Vector, copy the data over from this Vector into the new one, and reset the mapping. Externally, this function has no side effects, but may be necessary before communicating Vectors.
If this Vector does not have a mapping, it is already materialized, so we do nothing.
-
inline Vector mapping_reference(std::vector<VectorSizeType> map) const
Create a mapping reference, where the std::vector argument
mapwill become the new map. Not allowed if a mapping is already applied.- Parameters:
map – std::vector specifying the new map
- Returns:
Vector
-
template<typename S>
inline Vector mapping_reference(std::vector<S> map) const Create a mapping reference with a
std::vector<S>map, for arbitrary typeS.- Template Parameters:
S –
- Parameters:
map –
- Returns:
Vector
-
template<typename S>
inline Vector mapping_reference(Vector<S> map) const Create a mapping reference, where the Vector argument
mapwill become the new map. Not allowed if a mapping is already applied.- Parameters:
map – cdough Vector specifying the new map
- Returns:
Vector
-
template<typename S = VectorSizeType>
inline void apply_mapping(std::vector<S> new_mapping) Compose mappings. Apply the new mapping on top of an existing mapping, should one exist.
Specifically, assume
xis the underlying storage. Then letx1be the vector with mappingm1applied;x1[i] = x[m1[i]].Applying map
m2with this function givesx2, such thatx2[i] = x[m1[m2[i]]].The new mapping specified must be the same size as, or smaller than, the old one (this function cannot expand a vector).
- Template Parameters:
S –
- Parameters:
new_mapping –
-
inline void reverse()
Use iterators to reverse this Vector in place.
-
inline Vector &operator=(const Vector &&other)
This is a deep move assignment operator. Applies the move assignment operator to T. Assigns the contents of the
othervector to the this vector. Assumesotherhas the same size as this vector.
NOTE: This method works relatively to the current batch.
- Parameters:
other – The Vector that contains the values to be assigned to this vector.
- Returns:
A reference to this vector after modification.
-
inline Vector &operator=(const Vector &other)
This is a deep copy assignment operator. Applies the copy assignment operator to T. Copies the contents of the
othervector to this vector. Assumesotherhas the same size as this vector.- Parameters:
other – the Vector that contains the values to be copied.
- Returns:
A reference to
thisVector after modification.
-
template<typename OtherT>
inline Vector &operator=(const Vector<OtherT> &other) Copy-and-cast assignment operator. Allows (down)casting elements from a vector of one type into another.
-
inline Vector simple_subset(const VectorSizeType &start, const VectorSizeType &size) const
Returns a new vector that contains all elements in the range [start, start + size].
NOTE: This method works relatively to the current batch.
- Parameters:
start – The index of the first element to be included in the output vector.
size – The number of elements to include
- Returns:
A new vector that contains the selected elements.
-
inline void mask(const T &n)
Masks each element in
thisvector by doing a bitwise logical AND withn. TODO: factor out into common macro for other operations using define_binary_vector_element_assignment_op- Parameters:
n – The mask.
-
inline void zero()
Sets every element of this vector to zero. Don’t modify the mapping. (If a mapping is applied, only mapped values will be zero’d.)
NOTE: this method works relative to the current batch.
-
inline VectorSizeType size() const
NOTE: This method works relatively to the current batch.
- Returns:
The number of elements in the vector.
-
inline void resize(size_t n)
Resize this vector.
If a mapping is applied, resize both the mapping and the underlying data. Point new indices to new storage.
If no mapping is applied, just resize the underlying data.
This method resets the current batch.
- Parameters:
n –
-
inline void tail(size_t n)
Resize this vector to its last \(n\) elements. If there is a mapping, erase all but the last \(n\) elements of the mapping. Otherwise, erase the underlying data. For the head of a Vector, just use
resize.- Parameters:
n –
-
inline void concatenate(const Vector &other)
Concatenate
thisvector withotherby resizingthisand placingotherinto the new positions.- Parameters:
other –
-
inline Vector operator-() const
Elementwise plaintext negation.
-
inline Vector operator~() const
Elementwise plaintext boolean complement.
-
inline Vector operator!() const
Elementwise plaintext boolean negation.
-
inline Vector ltz() const
Elementwise plaintext less-than-zero comparison.
-
inline Vector extend_lsb() const
Elementwise plaintext LSB extension: set all bits equal to the LSB. Note: this is only makes sense for bit shares.
-
inline Vector extract_valid(Vector valid)
Extract the valid elements from a Vector, as denoted by the passed flag vector. Basically a selection function. Used in table operations to filter out invalid rows.
- Parameters:
valid –
- Returns:
Vector
-
inline std::pair<Vector, Vector> divrem(const T d)
Perform division-with remainder in a single loop, to optimize cache performance.
- Parameters:
d –
- Returns:
std::pair<Vector, Vector> a pair of
(quotient, remainder)
-
inline T &operator[](const VectorSizeType &index)
Returns a mutable reference to the element at the given
index. NOTE: This method works relatively to the current batch.- Parameters:
index – The index of the target element.
- Returns:
A mutable reference to the element at the given
index.
-
inline const T &operator[](const VectorSizeType &index) const
Returns an immutable reference of the element at the given
index.NOTE: This method works relatively to the current batch.
- Parameters:
index – The index of the target element.
- Returns:
Returns a read-only reference of the element at the given
index.
-
inline bool same_as(const Vector<T> &other, bool print_warn = true) const
Checks if the two input vectors (
thisandother) contain the same elements.- Parameters:
other –
print_warn – Print a warning if the Vectors do not match. Useful for test scripts but should be disabled in protocols or production code. This setting can also be controlled at compile time by the directive
DEBUG_VECTOR_SAME_AS. (Default:true)
- Returns:
true the Vectors are the same
- Returns:
false they are not
-
inline bool starts_with(const Vector<T> &prefix)
Checks if the vector
prefixis a prefix of this vector.- Parameters:
prefix –
- Returns:
true if the argument is a prefix
- Returns:
false otherwise
-
inline bool all_true()
Returns true if all elements of this vector are truthy, and false otherwise.
- Returns:
true
- Returns:
false
-
inline Vector matrixRightMultiplyWithColumnMatrixVectorized(Vector rhs, const size_t lhs_rows, const size_t lhs_cols, const size_t rhs_rows, const size_t rhs_cols) const
Matrix right multiplication with a column matrix, vectorized version. Both
thisandrhsmust not have any mapping applied.- Parameters:
rhs – The right-hand side column matrix, stored as a vector.
lhs_rows – Number of rows in the left-hand side matrix (
this).lhs_cols – Number of columns in the left-hand side matrix (
this).rhs_rows – Number of rows in the right-hand side column matrix (
rhs).rhs_cols – Number of columns in the right-hand side column matrix (
rhs).
- Returns:
Vector The resulting matrix after multiplication, stored as a vector output is in row-major order.
-
inline Vector conv2DVectorized(Vector rhs, const size_t instancesCount, const size_t inputHeight, const size_t inputWidth, const size_t filterHeight, const size_t filterWidth, const size_t strideHeight, const size_t strideWidth, const size_t paddingHeight, const size_t paddingWidth) const
2D convolution, vectorized implementation.
Input layout: The input consists of mutiple instances concatenated after each other. Hence, the input size = instancesCount * inputHeight * inputWidth. Each instance has multiple channels interleaved per spatial location.
For example, for 2x2 input with 2 channels: [ch1(0,0), ch2(0,0), ch1(0,1), ch2(0,1), ch1(1,0), ch2(1,0), ch1(1,1), ch2(1,1)]
Filter layout: the filter is expected to have multiple channels. Hence, the filter size = channels * filterHeight * filterWidth. For example, the the physical layout for 2x2 filter with 2 channels:
[f_ch1(0,0), f_ch2(0,0), f_ch1(1,0), f_ch2(1,0), g_ch1(0,1), g_ch2(0,1), g_ch1(1,1), g_ch2(1,1)]
Output layout: (same layout as input but different height and width). The output consists of mutiple instances concatenated after each other. Hence, the output size = instancesCount * outputHeight * outputWidth * channels. Each instance has multiple channels interleaved per spatial location.
For example, for 2x2 output with 2 channels: [f(0,0), g(0,0), f(0,1), g(0,1), f(1,0), g(1,0), f(1,1), g(1,1)]
- Parameters:
rhs – The filter vector.
instancesCount – Number of instances in the input.
inputHeight – Height of each input instance.
inputWidth – Width of each input instance.
filterHeight – Height of the filter.
filterWidth – Width of the filter.
strideHeight – Stride along height.
strideWidth – Stride along width.
paddingHeight – Padding along height.
paddingWidth – Padding along width.
-
inline Vector conv2DLeftVectorization(const size_t instancesCount, const size_t inputHeight, const size_t inputWidth, const size_t filterHeight, const size_t filterWidth, const size_t strideHeight, const size_t strideWidth, const size_t paddingHeight, const size_t paddingWidth) const
2D convolution left vectorization.
It extracts elements needed for 2D convolution from an lhs and order them in a way that allows for efficient matrix multiplication with the filter rhs.
Input layout: The input consists of mutiple instances concatenated after each other. Hence, the input size = instancesCount * inputHeight * inputWidth. Each instance has multiple channels interleaved per spatial location.
Input example: For example, for 2x2 input with 2 channels: [ch1(0,0), ch1(0,1), ch1(0,2), ch1(0,3), ch1(1,0), ch2(1,1), ch1(1,2), ch1(1,3)]
Output Example for (2,2) filter, (1,1) stride, (0,0) padding: [ch1(0,0), ch1(0,1), ch1(1,0), ch1(1,1), ch1(0,1), ch1(0,2), ch1(1,1), ch1(1,2), ch1(0,2), ch1(0,3), ch1(1,2), ch1(1,3)]
- Parameters:
instancesCount – Number of instances in the input.
inputHeight – Height of each input instance.
inputWidth – Width of each input instance.
filterHeight – Height of the filter.
filterWidth – Width of the filter.
strideHeight – Stride along height.
strideWidth – Stride along width.
paddingHeight – Padding along height.
paddingWidth – Padding along width.
-
inline Vector sumPoolingVectorized(const size_t instancesCount, const size_t channels, const size_t inputHeight, const size_t inputWidth, const size_t poolHeight, const size_t poolWidth, const size_t strideHeight, const size_t strideWidth, const size_t paddingHeight, const size_t paddingWidth) const
2D sum pooling, vectorized implementation.
Input layout: The input consists of mutiple instances concatenated after each other. Hence, the input size = instancesCount * inputHeight * inputWidth. Each instance has multiple channels interleaved per spatial location.
Input layout: The input consists of mutiple instances concatenated after each other. Hence, the input size = instancesCount * inputHeight * inputWidth * channels. Each instance has multiple channels interleaved per spatial location.
For example, for 2x2 input with 2 channels: [ch1(0,0), ch2(0,0), ch1(0,1), ch2(0,1), ch1(1,0), ch2(1,0), ch1(1,1), ch2(1,1)]
Output layout: same layout as input but with different height and width.
- Parameters:
instancesCount – Number of instances in the input.
channels – Number of channels per instance.
inputHeight – Height of each input instance.
inputWidth – Width of each input instance.
poolHeight – Height of the pooling window.
poolWidth – Width of the pooling window.
strideHeight – Stride along height.
strideWidth – Stride along width.
paddingHeight – Padding along height.
paddingWidth – Padding along width.
-
inline Vector matrixSeparateChannels(const size_t channels) const
Separate interleaved channels in a matrix.
Input layout: The input consists of mutiple instances concatenated after each other. {ch1(0,0), ch2(0,0), … chN(0,0), ch1(0,1), ch2(0,1), … chN(0,1), ..}
Output layout: The output consists of separated channels concatenated in the same vector. {ch1(0,0), ch1(0,1), … ch1(n,m)}, {ch2(0,0), ch2(0,1), … ch2(n,m)}, … {chN(0,0), chN(0,1), … chN(n,m)}
- Parameters:
channels – Number of channels in the input matrix.
- Returns:
Vector The resulting vector with separated channels.
-
inline Vector matrixInterleaveChannels(const size_t channels) const
Interleave channels in a matrix. It takes a matrix where channels are separated and make it such that channels are interleaved.
Input layout: The input consists of separated channels concatenated in the same vector. {ch1(0,0), ch1(0,1), … ch1(n,m)}, {ch2(0,0), ch2(0,1), … ch2(n,m)}, … {chN(0,0), chN(0,1), … chN(n,m)}
Output layout: The output consists of mutiple instances concatenated after each other. {ch1(0,0), ch2(0,0), … chN(0,0), ch1(0,1), ch2(0,1), … chN(0,1), ..}
- Parameters:
channels – Number of channels in the input matrix.
- Returns:
Vector The resulting vector with interleaved channels.
Public Members
-
std::shared_ptr<VectorDataBase<T>> data
A (shared) pointer to the actual vector contents.
NOTE: Shallow copying of this object creates two instances that share the same data.
Public Static Attributes
-
static const int LEVEL_MASK_SIZE = 7
-
static const uint64_t constexpr LEVEL_MASKS[LEVEL_MASK_SIZE] = {0xffffffffffffffff, 0xaaaaaaaaaaaaaaaa, 0x4444444444444444, 0x1010101010101010, 0x0100010001000100, 0x0001000000010000, 0x0000000100000000,}
Mask for level 2^i (64 bits). Gives LSB of the most significant half of each chunk.
Private Types
-
using Unsigned_type = typename std::make_unsigned<T>::type
-
using Unsigned_type = typename UnsignedTypeSelector<T>::type
An alias for unsigned
T.
Private Functions
-
inline Vector reverse_bit_level_shift(int level_size) const
Creates a new Vector whose i-th element is generated by:
splitting the bit representation of the i-th element of
thisVector into parts of sizelevel_size, andsetting all bits of the most significant half of each part equal to the MSB of the least significant half.
NOTE: This method is bit_level_shift but from right to left, and is used in the parallel prefix adder for boolean addition.
- Parameters:
level_size – The number of bits (2^k, k>0) of each part within the bit representation of an element.
- Returns:
A new vector that contains elements generated as described above.
-
inline Vector bit_arithmetic_right_shift(int shift_size) const
Creates a new Vector that contains all elements of
thisVector right-shifted byshift_size. Arithmetic shift is used: signed types will have their MSB copied. To shift in zero instead, usebit_logical_right_shift.
NOTE: This method works relatively to the current batch.
- Parameters:
shift_size – The number of bits to right-shift each element of
thisVector.- Returns:
A new Vector that contains the right-shifted elements.
-
inline Vector bit_logical_right_shift(int shift_size) const
Creates a new Vector that contains all elements of
thisVector right-shifted byshift_size. This performs logical shift: zeros are shifted into the MSB. To copy the sign, usebit_arithmetic_right_shiftNOTE: This method works relatively to the current batch.- Parameters:
shift_size – The number of bits to right-shift each element of
thisVector.- Returns:
A new Vector that contains the right-shifted elements.
-
inline Vector bit_left_shift(int shift_size) const
Creates a new Vector that contains all elements of
thisVector left-shifted byshift_size.
NOTE: This method works relatively to the current batch.
- Parameters:
shift_size – The number of bits to left-shift each element of
thisVector.- Returns:
A new Vector that contains the left-shifted elements.
-
inline Vector bit_xor() const
Creates a new Vector whose i-th element is a single bit generated by XORing all bits of the i-th element of
thisVector, 0 <= i < size(). (Basically parity check of each element.)
NOTE: This method works relatively to the current batch.
- Returns:
A new Vector that contains single-bit elements generated as described above.
-
inline Vector simple_subset(int start, int step, int end) const
Returns a new vector containing elements in the range [start, end] that are
steppositions apart.
NOTE: This method works relatively to the current batch.
- Parameters:
start – The index of the first element to be included in the output vector.
step – The distance between two consecutive elements.
end – The maximum possible index of the last element to be included in the output vector.
- Returns:
A new vector that contains the selected elements.
-
inline void reset_batch()
Sets the current batch equal to the whole vector.
-
inline void set_batch(int _start_ind, int _end_ind)
Sets start and end index of the current batch. If the start index is negative, the start index is set to zero. If the end index is greater than the Vector’s size, the end index is set the max possible index.
- Parameters:
_start_ind – The index of the first element in the current batch.
_end_ind – The index of the last element in the current batch.
Private Members
-
int batch_start = 0
-
int batch_end = 0
-
const int MAX_BITS_NUMBER = std::numeric_limits<Unsigned_type>::digits
-
size_t precision = 0
Fixed-point precision (number of fractional bits)
-
VectorSizeType length = 0
-
T element
A single element of the correct type so that we can properly handle the overload of operator[] which returns a T&. Note that this means dummy Vectors do actually store a single element, which may persist across calls (but is not guaranteed to do so). Code like.
a[0] = 5
will store
5in the first index ofa. Later on, accessing a different element ofamay or may not return5.
-
const size_t MAX_BITS_NUMBER = std::numeric_limits<Unsigned_type>::digits
Number of bits to represent
T.
-
VectorSizeType batch_start = 0
The start index of the batch that is currently being processed
-
VectorSizeType batch_end = 0
The end index of the batch that is currently being processed
-
std::shared_ptr<std::vector<T>> data
A (shared) pointer to the actual vector contents. NOTE: Shallow copying of this object creates two instances that share the same data.
-
std::shared_ptr<std::vector<VectorSizeType>> mapping
A (shared) pointer to the vector storing the index mapping for this vector. Can be null, in which case the mapping is defaulted to the identity mapping
Friends
- friend class EVector
- friend class service::RunTime
- friend class cdough::service::Task_1
- friend class cdough::service::Task_2
- friend class cdough::service::Task_ARGS_RTR_1
- friend class cdough::service::Task_ARGS_RTR_2
- friend class cdough::service::Task_ARGS_VOID_1
- friend class cdough::service::Task_ARGS_VOID_2
- friend class EVector
- friend class cdough::service::Task_1
- friend class cdough::service::Task_2
- friend class cdough::service::Task_ARGS_RTR_1
- friend class cdough::service::Task_ARGS_RTR_2
- friend class cdough::service::Task_ARGS_VOID_1
- friend class cdough::service::Task_ARGS_VOID_2
- friend class EVector
- friend class cdough::service::Task_1
- friend class cdough::service::Task_2
- friend class cdough::service::Task_ARGS_RTR_1
- friend class cdough::service::Task_ARGS_RTR_2
- friend class cdough::service::Task_ARGS_VOID_1
- friend class cdough::service::Task_ARGS_VOID_2
A secret-shared vector with share and container types. A SharedVector is an “encoded view” of a plaintext vector as seen from an untrusted party. Different parties in a MPC protocol have different “views” of the same plaintext vector and views may vary significantly across protocols. Currently, cdough supports two techniques to construct a SharedVector: arithmetic and boolean secret sharing. Using these techniques, a secret value \(s\) is encoded using \(n > 1\) random “shares” such that:
\(s = s_1 + s_2 + ... + s_n~\texttt{mod}~2^\ell\), where \(\ell\) is the length of \(s\) in bits (Arithmetic)
\(s = s_1 \oplus s_2 \oplus ... \oplus s_n\), where \(\oplus\) denotes the bitwise XOR operation (Boolean)
Let \(v = \{4, 12, 84\}\) be a plaintext vector that is secret-shared by 2 parties using arithmetic sharing. From the viewpoint of each party, vector \(v\) will look like this:
\[\begin{split}\begin{align} v = \{-1, 12, 100\} \quad & \textit{(encoded view of party 1)}\\ v = \{5, 0, -16]\} \quad & \textit{(encoded view of party 2)} \end{align}\end{split}\]These two vectors are in practice SharedVectors containing random numbers that add up to the numbers in the original vector (which remains hidden from the parties). To reconstruct the original vector in this example, the parties must “open” their SharedVector to a single entity (i.e., a learner) to apply the elementwise addition. The methods to construct and open SharedVectors are defined in Protocol.
- Template Parameters:
Share – Share data type.
Container – Share container type.
Engine – Secure computation engine type.
Subclassed by cdough::ASharedVector< T, AInnerContainer< T >, RunTime >, cdough::ASharedVector< int, cdough::EVector< int, EVector::replicationNumber >, Engine >, cdough::ASharedVector< int, cdough::EVector< int, E::replicationNumber >, Eng >, cdough::ASharedVector< int, cdough::EVector< int, E::replicationNumber >, Engine >, cdough::BSharedVector< T, BInnerContainer< T >, RunTime >, cdough::BSharedVector< int, cdough::EVector< int, EVector::replicationNumber >, Engine >, cdough::BSharedVector< T, Container, Engine >, cdough::BSharedVector< int, cdough::EVector< int, E::replicationNumber >, Eng >, cdough::BSharedVector< int, cdough::EVector< int, E::replicationNumber >, Engine >, cdough::BSharedVector< PadWidth< typename E::ShareT >, cdough::EVector< PadWidth< typename E::ShareT >, E::replicationNumber >, Engine >
Public Functions
Creates a SharedVector of size
_sizeand initializes it with zeros.- Parameters:
_size – The size of the SharedVector.
eType – The encoding of the SharedVector.
eng – The secure computation engine.
Creates a SharedVector of size
_sizeand initializes it with the contents of the file_input_file.- Parameters:
_size – The size of the SharedVector.
_input_file – The file containing the contents of the SharedVector.
eType – The encoding of the SharedVector.
eng – The secure computation engine.
Writes the secret shares of the shared vector to a file.
- Parameters:
_output_file – The file to write the secret shares to.
This is a shallow copy constructor from Container.
- Parameters:
_shares – The Container whose contents will be pointed at by the SharedVector.
eType – encoding
eng – The secure computation engine.
This is a move constructor from SharedVector.
- Parameters:
secretShares – The SharedVector whose contents will be moved to the new SharedVector.
Copy constructor from EncodedVector.
- Parameters:
_shares – The EncodedVector object whose contents will be copied to the new SharedVector.
eng – The secure computation engine.
Opens the shared vector to all computing parties. For malicious protocols, also runs checks.
- Returns:
The opened (plaintext) vector.
- Returns:
The size of the shared vector in number of elements.
Resize a shared vector. If the new vector is larger, the tail end will be initialized to zero. If the new vector is smaller, the end of the current vector will be removed (
headsemantics).- Parameters:
n –
Resize this vector have its last
nelements. Does not copy.- Parameters:
n –
Concatenate
thisvector withotherby resizingthisand placingotherinto the new positions.- Parameters:
other –
Create a deep copy (allocate new space and copy all elements) of a shared vector.
- Returns:
std::unique_ptr<SharedVector>
Copy-assignment between shared vector. Copies shares from
otherintothis. Pass to the engine to enable multithreaded execution.- Parameters:
other –
- Returns:
Move-assignment between shared vectors. Takes ownership of other’s vector. This is not passed to the engine because no data is copied.
- Parameters:
other –
- Returns:
Cast-and-copy assignment. Create a SharedVector from another one of a different underlying type. (Replication number and encoding must still match.) This allows us to up/down-cast vectors.
- Template Parameters:
T2 –
- Parameters:
other –
- Returns:
Transforms this vector into an Container object.
NOTE: This method is useful for developers who need access to the underlying shares of the
SharedVector that are only exposed through the Container. Use it if you are certain about what you are doing.- Returns:
An Container object with the same contents as
thisshared vector.
Get the secure computation engine.
- Returns:
Engine&
Compute a prefix sum over this shared vector.
WARNING: this does not call down to the protocol primitive but instead performs a local prefix sum over the actual underlying vector. This will not cause any issues now, since for all current protocols, add_a is trivial. But this is not necessarily true in general.
Sets the fixed-point precision.
- Parameters:
fixed_point_precision – - the number of fixed-point fractional bits.
Gets the fixed-point precision.
Public Members
Private Types
A SharedVector that contains arithmetic shares and supports secure arithmetic operations.
- Template Parameters:
Share – Share data type.
EVector – Share container type.
Engine – Secure computation engine type.
Public Functions
Creates an ASharedVector of size
_sizeand initializes it with zeros.Note: This constructor is deprecated from public API [last resort].
- Parameters:
_size – The size of the ASharedVector.
eng – The secure computation engine.
Creates an ASharedVector of size
_sizeand initializes it with secret shares in the given file.- Parameters:
_size – The size of the ASharedVector.
_input_file – The file that contains the secret shares.
eng – The secure computation engine.
This is a shallow copy constructor from EVector contents.
- Parameters:
_shares – The EVector whose contents will be pointed by the ASharedVector.
eng – The secure computation engine.
This is a move constructor from EVector contents.
- Parameters:
_shares – The EVector whose contents will be moved to the new ASharedVector.
eng – The secure computation engine.
This is a move constructor from another ASharedVector.
- Parameters:
other – The ASharedVector whose contents will be moved to the new ASharedVector.
This is a copy constructor from another ASharedVector.
- Parameters:
other – The ASharedVector whose contents will be moved to the new ASharedVector.
Copy constructor from SharedVector contents.
- Parameters:
_shares – The SharedVector object whose contents will be copied to the new ASharedVector.
Move constructor that creates an ASharedVector from a unique pointer to an EncodedVector object.
- Parameters:
base – The pointer to the SharedVector object whose contents will be moved to the new ASharedVector.
Shallow copy constructor that creates an ASharedVector from a unique pointer to an EncodedVector object.
- Parameters:
base – The SharedVector object whose contents will be pointed by the new ASharedVector.
Move constructor that creates an ASharedVector from a pointer to another ASharedVector
object.
NOTE: This constructor is implicitly called by the two constructors above.
- Parameters:
_base – The ASharedVector that will be moved as a whole (contents + state) to the new ASharedVector.
Construct a new ASharedVector object like another ASharedVector but with a different size.
- Parameters:
size – The size of the new ASharedVector.
- Returns:
ASharedVector The newly constructed ASharedVector.
Reuse underlying SharedVector implementation for access patterns.
Convert from ASharedVector to BSharedVector. Each party redistributes boolean shares of their additive shares, then uses a boolean addition circuit to “add” those shares back together. In the end we are left with an XOR-sharing of the same value.
Other protocols, such as using preprocessed shared bits, are possible.
Convert from ASharedVector to BSharedVector, but only for the most significant bit of each element (sign).
Note: size of the resulting BSharedVector is n/MAX_BITS_NUMBER.
- Returns:
std::unique_ptr the resulting BSharedVector containing only the MSBs.
Elementwise secure arithmetic addition. Returns a unique ptr.
Elementwise secure arithmetic subtraction. Returns a unique ptr.
Elementwise secure arithmetic multiplication. Returns a unique ptr.
Elementwise secure arithmetic negation. Returns a unique ptr.
Multiply by a public floating-point constant (local, no MPC protocol). Scales the float to a fixed-point integer using this vector’s precision, multiplies each share locally, and truncates.
Division by public constant. Call the underlying protocol’s
div_const_afunctionality, then perform error correction (if configured to do so using the compiler directive USE_DIVISION_CORRECTION).- Parameters:
c –
- Returns:
std::unique_ptr<ASharedVector>
Auto-conversion private elementwise division. Since our current integer division algorithm only supports BSharedVector inputs, convert
thisandotherto binary before callingBSharedVector::operator/. Do not convert the result back.- Parameters:
other –
- Returns:
std::unique_ptr<BSharedVector>
Computes the dot product of this vector with another vector. Each
aggSizeconsecutive elements contribute to an exactly on dot product element in the result. The size of the resulting vector is determined by theaggSizeparameter.NOTE: This function is efficient when doing dot products with small
aggSizevalues, For largeraggSizevalues including the entire vector in the dot product, we will need to to do batching different in the engine. Currently, whole vector dot product will be executed single-threaded because each threads takes multiple.- Parameters:
other – The second operand of the dot product.
aggSize – The size of each dot product.
- Returns:
A unique pointer to a new ASharedVector that contains the result of the dot product.
Secure matrix right multiplication with a column matrix, vectorized implementation. Expects the left-hand side matrix to be in row-major order. Expects the right-hand side matrix to be in column-major order.
- Parameters:
other – The right-hand side column matrix.
lhs_rows – Number of rows in the left-hand side matrix.
lhs_cols – Number of columns in the left-hand side matrix.
rhs_rows – Number of rows in the right-hand side matrix.
rhs_cols – Number of columns in the right-hand side matrix.
- Returns:
std::unique_ptr<ASharedVector>
Secure 2D convolution, vectorized implementation.
Input layout: The input consists of mutiple instances concatenated after each other. Hence, the input size = instancesCount * inputHeight * inputWidth. Each instance has multiple channels interleaved per spatial location.
For example, for 2x2 input with 2 channels: [ch1(0,0), ch2(0,0), ch1(0,1), ch2(0,1), ch1(1,0), ch2(1,0), ch1(1,1), ch2(1,1)]
Filter layout: the filter is expected to have multiple channels. Hence, the filter size = channels * filterHeight * filterWidth. For example, the the physical layout for 2x2 filter with 2 channels:
[f_ch1(0,0), f_ch2(0,0), f_ch1(1,0), f_ch2(1,0), g_ch1(0,1), g_ch2(0,1), g_ch1(1,1), g_ch2(1,1)]
Output layout: (same layout as input but different height and width). The output consists of mutiple instances concatenated after each other. Hence, the output size = instancesCount * outputHeight * outputWidth * channels. Each instance has multiple channels interleaved per spatial location.
For example, for 2x2 output with 2 channels: [f(0,0), g(0,0), f(0,1), g(0,1), f(1,0), g(1,0), f(1,1), g(1,1)]
- Parameters:
other – The filter matrix.
instancesCount – Number of instances in the input batch.
inputHeight – Height of each input instance.
inputWidth – Width of each input instance.
filterHeight – Height of each filter channel.
filterWidth – Width of each filter channel.
strideHeight – Stride height.
strideWidth – Stride width.
paddingHeight – Padding height.
paddingWidth – Padding width.
- Returns:
std::unique_ptr<ASharedVector>
Secure sum pooling. Aggregates values within pooling windows by summing them. Aggregation is performed over multiple instances with multiple channels. Each layer is pooled independently.
Input layout: The input consists of mutiple instances concatenated after each other. Hence, the input size = instancesCount * inputHeight * inputWidth * channels. Each instance has multiple channels interleaved per spatial location.
For example, for 2x2 input with 2 channels: [ch1(0,0), ch2(0,0), ch1(0,1), ch2(0,1), ch1(1,0), ch2(1,0), ch1(1,1), ch2(1,1)]
Output layout: same layout as input but with different height and width.
- Parameters:
instancesCount – Number of instances in the input batch.
channels – Number of channels in each instance.
inputHeight – Height of each input instance.
inputWidth – Width of each input instance.
poolHeight – Height of the pooling window.
poolWidth – Width of the pooling window.
strideHeight – Stride height.
strideWidth – Stride width.
paddingHeight – Padding height.
paddingWidth – Padding width.
- Returns:
std::unique_ptr<ASharedVector> The resulting pooled ASharedVector.
Negate this vector in place.
Secure comparison: greater than. Note: If you do not need secure multiplication/addition after comparison, consider using BSharedVector instead. It uses conversion and BSharedVector’s comparison operator under the hood. It keeps the results in the ASharedVector world after comparison.
- Parameters:
other – The other ASharedVector to compare against.
- Returns:
std::unique_ptr<ASharedVector>
Secure comparison: greater than or equal to zero. Note: If you do not need secure multiplication/addition after comparison, consider using BSharedVector instead. It uses conversion and BSharedVector’s comparison operator under the hood. It keeps the results in the ASharedVector world after comparison.
- Returns:
std::unique_ptr<ASharedVector>
Compute chunked sums over groups of consecutive elements. Simply calls down to the underlying EVector’s chunkedSum method.
- Parameters:
aggSize – The number of elements to aggregate in each sum.
- Returns:
ASharedVector containing the chunked sums.
A SharedVector that contains boolean shares and supports secure boolean operations.
- Template Parameters:
Share – Share data type.
EVector – Share container type.
Engine – Secure computation engine type.
Public Types
Public Functions
Bit packing. Operates in place by packing the bit at index
positionfrom BSharedVectorsourceintothisBSharedVector.- Parameters:
source –
position –
Bit unpacking. Operates in place by unpacking the bit at index
positionfrom BSharedVectorsourceintothis.- Parameters:
source –
position –
Decomposes each element of this BSharedVector into its bits, returning a vector of BSharedVectors, each containing one bit position across all elements.
- Returns:
A vector of BSharedVectors, where the i-th BSharedVector contains the i-th bits of each element in
this.
Arithmetic right shift. Operates in place by putting the output into
this. Respects the sign bit.- Parameters:
in – input
shift_size – The number of bits to right-shift each element of
thisvector.
Logical right shift. Operates in place. Does not respect the sign bit.
- Parameters:
in – input
shift_size – The number of bits to right-shift each element of
thisvector.
Bit left shift. Operates in place. Does not respect the sign bit.
- Parameters:
in –
shift_size –
Compute the parity of the input BSharedVector and place the result into
this.- Parameters:
in – input shared vector
Elementwise LSB extension. This method operates in place, copying the LSB of each
inelement intothis.- Parameters:
in –
Returns the popcount (AKA Hamming weight) of
thisas astd::unique_ptrto aASharedVector. Uses a round-optimal concatenation approach, unpackingthisinto the LSB of a newBSharedVectorand then taking itschunkedSum.- Returns:
A pointer to a new ASharedVector with the popcount of
this
Creates a BSharedVector of size
_sizeand initializes it with zeros.Note: This constructor is deprecated from public API [last resort].
- Parameters:
_size – The size of the BSharedVector.
Creates a BSharedVector of size
_sizeand initializes it with secret shares in the given file.- Parameters:
_size – The size of the BSharedVector.
_input_file – The file that contains the secret shares.
This is a shallow copy constructor from EVector.
- Parameters:
_shares – The EVector whose contents will be pointed by the BSharedVector.
eng – The engine to be used.
This is a move constructor from EVector.
- Parameters:
_shares – The EVector whose contents will be moved to the new BSharedVector.
eng – The engine to be used.
This is a move constructor from another BSharedVector.
- Parameters:
other – The BSharedVector whose contents will be moved to the new BSharedVector.
This is a copy constructor from another BSharedVector.
- Parameters:
other – The BSharedVector whose contents will be copied to the new BSharedVector.
Copy constructor from a SharedVector.
- Parameters:
_shares – The SharedVector object whose contents will be copied to the new BSharedVector.
Move constructor that creates a BSharedVector from a unique pointer to a SharedVector object.
- Parameters:
base – The pointer to the SharedVector object whose contents will be moved to the new BSharedVector.
Shallow copy constructor that creates a BSharedVector from a unique pointer to a SharedVector object.
- Parameters:
base – The SharedVector object whose contents will be pointed by the new BSharedVector.
Move constructor that creates a BSharedVector from a pointer to another BSharedVector
object.
NOTE: This constructor is implicitly called by the two constructors above.
- Parameters:
_base – The BSharedVector that will be moved as a whole (contents + state) to the new BSharedVector.
Construct a new BSharedVector object like another BSharedVector but with a different size.
- Parameters:
size – The size of the new BSharedVector.
- Returns:
ASharedVector The newly constructed BSharedVector.
Convert the LSB of each element of this BSharedVector to an arithmetic sharing. This is substantially more efficient than a full-width conversion and suffices for most applications.
- Returns:
Full-width conversion from BSharedVector to ASharedVector. Generates an online shared-bit correlation (random value shared in both domains), and then uses a boolean adder to mask.
The first loop is technically preprocessing, which would speed things up a lot.
- Returns:
This is a conversion from BSharedVector to ASharedVector. It is insecure. It is only used in the generation of dummy permutations.
Public Static Attributes
Private Types
Private Functions
-
template<typename Share, int ReplicationNumber, int Bitwidth = 0>
class EVector EVector is an abstraction similar to the EncodedVector, i.e., an “encoded view” of a plaintext vector as seen by an untrusted party. In contrast to EncodedVector, EVector provides access to the underlying encodings of the secret values.
While EncodedVector targets end-users, EVector is the abstraction provided to Protocol developers who need access to the underlying encodings in order to define new secure primitives, such as Protocol::add_a(), Protocol::and_b(), etc.
- Template Parameters:
Share – Share type.
ReplicationNumber – The number of shares that each party sees for each secret value.
Bitwidth – The bitwidth of the underlying Data type. Default is 0 (e.g. 8 for uint8_t).
Public Types
Public Functions
Provides an interface to initialize the data object with existing data.
NOTE: the copy constructor of
Vector<T> is shallow; if this is initialized by another Vector<T> object, both will point to data in the same memory location.- Parameters:
contents – The vector of vectors to initialize the data object with.
Initializes the EVector with a given vector of vectors and a fixed-point precision.
- Parameters:
contents – - The vector of vectors to initialize the data object with.
fixed_point_precision – - The fixed-point fractional bits to set for this EVector.
Initializes the EVector with a given initializer list of Vector<Share>.
- Parameters:
l – The initializer list to initialize the EVector with.
- Throws:
std::invalid_argument – if the size of the initializer list doesn’t match ReplicationNumber.
-
inline explicit EVector(size_t size)
EVector<T,N> constructor that allocates
ReplicationNumbernew Vectors, each one of sizesize.- Parameters:
size – The size of Vector<T> in this EVector<T,N>.
-
inline EVector(const EVector &other)
This is a shallow copy constructor (i.e., only copies the vector pointer but not its contents).
WARNING: The new vector will point to the same memory location as used by
other. To copy the data into a separate memory location, create a new vector first then use the assignment operator.- Parameters:
other – The other EVector whose contents this vector will point to.
-
inline EVector &operator=(const EVector &&other)
This is a deep move assignment. Applies the move assignment operator to Vector<T>. Assigns the values of the current batch from the
othervector to the current batch of this vector. Assumesotherhas the same size and replication factor as this vector.
-
inline void setPrecision(const int fixed_point_precision)
Sets the fixed-point precision.
- Parameters:
fixed_point_precision – - the number of fixed-point fractional bits.
-
inline size_t getPrecision() const
Gets the fixed-point precision.
-
inline void matchPrecision(const EVector &other)
Helper that sets this vector’s precision to match another EVector.
- Parameters:
other – The EVector whose precision should be copied.
-
inline void output(const std::string &_output_file_path)
-
inline EVector &operator=(const EVector &other)
This is a deep copy assignment. Applies the copy assignment operator to Vector<T>. Copies the values of the current batch from the
othervector to the current batch of this vector. Assumesotherhas the same size and replication factor as this vector.
-
template<typename Other, int R, int Tag2>
inline EVector &operator=(const cdough::EVector<Other, R, Tag2> &other) Type-conversion assignment.
-
inline EVector(size_t size, const std::string &_input_file_path)
EVector<T,N> constructor that allocates
ReplicationNumbernew Vectors, each one of sizesize, and initializes them with the contents of the file_input_file_path. The file contains the secret shares of the EVector. Each line in the file containsReplicationNumbervalues separated by a space.- Parameters:
size – The size of Vector<T> in this EVector<T,N>.
_input_file_path – The path to the file containing the contents of the EVector.
-
inline size_t size() const
Returns the current batch size, i.e., the number of secret values that are being processed in the current round. The default batch size is the actual vector size.
NOTE: cdough parties apply operations on EVectors in batches. Each batch corresponds to a range of elements in the vector.
- Returns:
The current batch size.
-
inline int getReplicationNumber() const
-
inline EVector construct_like() const
Creates a new EVector with the same structure as this EVector, but with newly allocated empty vectors of the same size.
- Returns:
A new EVector with the same structure but empty contents.
-
inline EVector construct_like(size_t size) const
Creates a new EVector with the same structure as this EVector, but with newly allocated empty vectors of a different size.
-
template<typename ...T>
inline EVector matrixRightMultiplyWithColumnMatrixVectorized(const EVector &other, T... args) const
-
inline bool has_mapping() const
-
inline Vector<Share> &operator()(int column)
Returns a mutable reference to a column of the EVector. EVector is implemented as a column-first 2D vector, where:
row i corresponds to k >= 1 encodings of the i-th secret value, 0 <= i < n.
column j stores the j-th encoding, 0 <= j < k, of each secret value in the vector.
The above column-first representation aims to facilitate the implementation of vectorized secure primitives. The number of secret values n in EVector is defined by the user but the number of encodings k per secret value depends on the Protocol. For example, in Replicated_3PC, each secret value \(s\) is encoded with three shares \(s_1\), \(s_2\), and \(s_3\) and each party receives k=2 of the 3 shares, namely:
Party 0 receives shares \(s_1\) and \(s_2\).
Party 1 receives shares \(s_2\) and \(s_3\).
Party 2 receives shares \(s_3\) and \(s_1\).
Assuming a plaintext vector \(v = \{s^1, s^2, ..., s^{n}\}\) with n values that are secret-shared by three parties, the respective EVectors in Replicated_3PC look as shown below:
\(v = \{~\{s^1_1, s^2_1,~...~s^{n}_1\},~\{s^1_2, s^2_2,~...,~s^{n}_2\}~\}\) (Party 1)
\(v = \{~\{s^1_2, s^2_2,~...~s^{n}_2\},~\{s^1_3, s^2_3,~...,~s^{n}_3\}~\}\) (Party 2)
\(v = \{~\{s^1_3, s^2_3,~...~s^{n}_3\},~\{s^1_1, s^2_1,~...,~s^{n}_1\}~\}\) (Party 3)
In this case, calling \(v(1)\) from Party 2 will return a reference to the internal vector at index j=1 that includes the third share \(s_3\) of each secret value:
\(\{s^1_3, s^2_3,~...,~s^{n}_3\}\)
- Parameters:
column – The column index.
- Returns:
A mutable reference to a vector of encodings at the given index.
-
inline const Vector<Share> &operator()(int column) const
Returns a read-only reference to a column of the EVector. For more information, see the version of the same operator that returns a mutable reference.
- Parameters:
column – The column index.
- Returns:
A read-only reference to a vector of encodings at the given index.
Public Static Attributes
-
static const int replicationNumber = ReplicationNumber
Protected Functions
-
inline size_t total_size() const
Returns the size of EVector
, i.e., the total number of secret values in the original (plaintext) vector.
NOTE: The output of
total_size() cannot be less than the output of size().- Returns:
The size of EVector.
Private Members
-
size_t precision
Friends
- friend class BSharedVector
- friend class ASharedVector
- friend class service::RunTime
- friend class cdough::service::Task_1
- friend class cdough::service::Task_2
- friend class EVector
- friend class Protocol
-
template<typename EVector, typename Engine>
class ElementwisePermutation Public Functions
-
inline ElementwisePermutation(size_t size, Engine &engine)
Default constructor which creates an identity permutation of a given size.
By default, this constructs an arithmetic sharing of the identity permutation. This constructor simply calls the next constructor with the default AShared sharing type.
- Parameters:
size – The size of the permutation.
-
inline ElementwisePermutation(size_t size, Encoding encoding, Engine &engine)
Constructor which creates an identity permutation of a given size with a given encoding.
- Parameters:
size – The size of the permutation.
encoding – The encoding type of the underlying SharedVector (arithmetic or binary).
-
inline ElementwisePermutation(ElementwisePermutation &permutation)
Copy constructor which takes another ElementwisePermutation as input.
- Parameters:
permutation – The permutation to copy.
Constructor which takes a SharedVector as input and assigns it to the underlying SharedVector
.
The second template argument is named argEVector to distinguish it from the
EVector that this class is templated by. This function copies the underlying data to a 32 bit SharedVector, which requires that the input vector has a bitwidth <= 32.- Parameters:
v – The SharedVector to copy.
-
inline ElementwisePermutation &operator=(const ElementwisePermutation &other)
Copy assignment operator.
Note: does not affect the engine because assignmnent concerns values only.
- Parameters:
other – The permutation to copy.
Assignment operator from a SharedVector The second template argument is named argEVector to distinguish it from the EVector that this class is templated by. This function copies the underlying data to a 32 bit SharedVector, which requires that the input vector has a bitwidth <= 32.
Note: does not affect the engine because assignmnent concerns values only.
- Parameters:
other – The SharedVector to copy.
-
inline size_t size()
Gets the size of the underlying SharedVector.
Gets the underlying SharedVector as an ASharedVector.
Gets the underlying SharedVector as an BSharedVector.
-
inline cdough::Encoding getEncoding()
Gets the encoding type of the underlying SharedVector.
-
inline Vector<int> open()
Open the underlying SharedVector.
-
inline ElementwisePermutation shuffle()
Shuffle the underlying SharedVector
- Returns:
The shuffled permutation.
-
inline ElementwisePermutation reverse()
Reverse the direction of the permutation.
Each element (with some value x) will now become size - 1 - x. Multiply by -1 then add (size - 1).
- Returns:
A permutation such that when applied to a vector, the permuted vector will be the reverse of the vector permuted under the original permutation.
-
inline ElementwisePermutation invert()
Find the inverse of the permutation (different than applying an inverse permutation).
- Returns:
The inverse of the permutation.
-
inline ElementwisePermutation b2a()
Convert a binary shared ElementwisePermutation to an arithmetic shared ElementwisePermutation
.
Apply a random permutation, open the result, secret share it arithmetically, then unapply the random permutation.
- Returns:
An ElementwisePermutation with an arithmetic sharing of the input permutation.
-
inline ElementwisePermutation negate()
Convert a permutation with negative location values to one with positive location values.
The input is has values from -1 to -n. We want to negate them (so 1 to n) and then shift down by 1 (0 to n-1).
- Returns:
An ElementwisePermutation with the correct range of values.
Public Members
Private Types
-
inline ElementwisePermutation(size_t size, Engine &engine)
Tabular
A secret-shared column with share and container types.
- Template Parameters:
Share – Share data type.
EVector – Container data type.
Engine – Secure computation engine type.
Public Functions
Allocates a shared column with the given encoding and initializes it with zeros.
- Parameters:
_size – The column’s size in number of elements.
eType – The column’s encoding (e.g., A-Shared, B-Shared, etc.).
Move constructor from an encoded vector.
- Parameters:
_shares – The encoded vector whose contents will be moved to the new column.
col_name – new name for the column
Move constructor from an encoded column.
- Parameters:
other – The encoded column whose contents will be moved to the new column.
Move assignment operator (shallow move) from an encoded column.
- Parameters:
other – The encoded column whose contents will be moved to the new column.
Zero out this column.
- Returns:
The column’s size in number of elements.
- Returns:
The column’s fixed-point precision (from the underlying encoded vector).
Make a deep copy of this column. Deep-copies the underlying vector.
- Returns:
std::unique_ptr<EncodedColumn>
Elementwise less-than-zero of a BShared column. Will cause an assertion error if called on an AShared column.
- Returns:
std::unique_ptr<EncodedColumn>
Boolean adder or Arithmetic add/subtract.
Elementwise secure arithmetic subtraction.
- Parameters:
other – The second operand of subtraction.
- Returns:
A unique pointer to an EncodedColumn that contains encoded results of the elementwise subtractions.
Boolean adder or Arithmetic add/subtract with constant.
Private division between two columns. The division algorithm only supports BShared inputs, so automatically convert (by calling
a2b) if any input is AShared. Output will always be BShared.- Parameters:
other –
- Returns:
std::unique_ptr<EncodedColumn> encoded as a BShared column
Column * Column.
Column * Constant.
Unary negation.
Public division with constant.
Binary assignment operators over AShared columns.
Binary operators between BShared columns.
Elementwise secure bitwise OR.
- Parameters:
other – The second operand of OR.
- Returns:
A unique pointer to an EncodedColumn that contains encoded results of the elementwise ORs.
Elementwise secure bitwise XOR.
- Parameters:
other – The second operand of XOR.
- Returns:
A unique pointer to an EncodedColumn that contains encoded results of the elementwise XORs.
Assignment operators between BShared columns.
Binary operators with an element.
Unary operators on BShared columns.
Elementwise secure boolean negation.
- Returns:
A unique pointer to an EncodedColumn with all results of
thisEncodedColumn negated.
Shift operators on BShared columns.
Elementwise shifts.
- Parameters:
y – shift amount
- Returns:
std::unique_ptr<EncodedColumn>
Elementwise secure greater-than.
- Parameters:
other – The second operand of greater-than.
- Returns:
A unique pointer to an EncodedColumn that contains encoded results of the elementwise greater-than comparisons.
Elementwise secure less-than.
- Parameters:
other – The second operand of less-than.
- Returns:
A unique pointer to an EncodedColumn that contains encoded results of the elementwise less-than comparisons.
Elementwise secure greater-or-equal.
- Parameters:
other – The second operand of greater-or-equal.
- Returns:
A unique pointer to an EncodedColumn that contains encoded results of the elementwise greater-or-equal comparisons.
Elementwise secure less-or-equal.
- Parameters:
other – The second operand of less-or-equal.
- Returns:
A unique pointer to an EncodedColumn that contains encoded results of the elementwise less-or-equal comparisons.
Elementwise secure equality.
- Parameters:
other – The second operand of equality.
- Returns:
A unique pointer to an EncodedColumn that contains encoded results of the elementwise equality comparisons.
Elementwise secure inequality.
- Parameters:
other – The second operand of inequality.
- Returns:
A unique pointer to an EncodedColumn that contains encoded results of the elementwise inequality comparisons.
Public Static Attributes
Protected Functions
Private Types
Friends
- friend class EncodedTable
-
template<typename Share, typename SharedColumn, typename A, typename B, typename EncodedVector, typename DataTable>
class EncodedTable An EncodedTable is a relational table that contains encoded data organized in columns. cdough users can perform vectorized secure operations directly on table columns via a Pandas-like interface, as shown below:
// cdough program (executed by an untrusted party) t["col3"] = t["col1"] * t["col2"];
The above line performs a secure elementwise multiplication between two columns
col1andcol2in tabletand stores the result in a third columncol3.- Template Parameters:
SharedColumn – Secret-shared column type.
A – A-shared vector type.
B – B-shared vector type.
EncodedVector – Encoded vector type.
DataTable – Plaintext table type.
Public Functions
-
inline EncodedTable(const std::string &_tableName, const std::vector<std::string> &_columns, int _rows, Engine &eng)
Constructs a table and initializes it with zeros.
- Parameters:
_tableName – The name of the table.
_columns – The column names.
_rows – The number of rows to allocate.
eng – The engine to use for this table.
Constructs a table from encoded columns.
- Parameters:
contents – The table columns.
-
inline EncodedTable(const EncodedTable &other)
Copy constructor.
-
inline EncodedTable &operator=(const EncodedTable &other)
Copy assignment operator.
-
inline EncodedTable &operator=(EncodedTable &&other) noexcept
Move assignment operator.
-
inline void configureValid()
Configured the valid column. If it does not exist, create it. If it does exist, re-initialize and make all rows valid.
-
template<typename T>
inline void filter(T &&e) Update the valid column based on the value of a provided column or expression (i.e., bitwise-and the input with valid)
This accepts either a column, or a unique pointer to a column.
- Template Parameters:
T –
- Parameters:
e – the expression to filter on. Rows evaluating to a boolean
truewill remain valid; those evaluating to a booleanfalsewill be marked invalid.
-
template<typename T>
inline void filter(std::unique_ptr<T> e) Update the valid column based on the value of an expression, passed as a unique pointer. Compound operators are only supported on columns, not pointers to columns, so dereference.
- Template Parameters:
T –
- Parameters:
e –
-
inline EncodedColumn &operator[](const std::string &name)
Returns a mutable reference to the column with the given name.
- Parameters:
name – The name of the column.
- Returns:
A reference to the column (throws an error if the column is not found).
Get column
nameas a BSharedVector.- Parameters:
name –
- Returns:
B
Get column
nameas an ASharedVector.- Parameters:
name –
- Returns:
A
Get column
nameas an untyped SharedVector.- Parameters:
name –
- Returns:
B::SharedVector_t
Reads secret shares for a column from a file. The file contain one line for each element in the column. Each line contains the replicated secret shares separated by a space. Note: this function does not affect valid bit.
- Parameters:
columnName – The name of the column.
inputFile – The file containing the secret shares.
-
inline void inputCSVTableData(const std::string &_file_path, int _input_party)
Reads secret shares for a column from a file. The file contains a csv table with the data.
- Parameters:
_file_path – The file containing the table data.
_input_party – The party that has the file.
Reads table secret shares from a csv file. Each column is secret shared using columns names as follows: [column_name]_[replication_index]. For example, column “A” with replication index 0 is secret shared using column name “[A]_0” and same for “[A]_1”, “[A]_2”, etc. depending on the replication number for the protocol. Note: this function updates the valid bit so that unread rows are assigned zero.
- Parameters:
_file_path – The file containing the table secret shares.
Outputs the table secret shares to a csv file. Each column is outputted using columns names as follows: [column_name]_[replication_index]. For example, column “A” with replication index 0 is outputted using column name “[A]_0” and same for “[A]_1”, “[A]_2”, etc. depending on the replication number for the protocol.
TODO: create directory if does not exist
- Parameters:
_file_path – The file to write the table secret shares to.
Output the secret shares of a column to a file. The file will contain one line for each element in the column. Each line will contain the replicated secret shares separated by a space.
- Parameters:
columnName – The name of the column.
outputFile – The file to write the secret shares to.
-
inline void finalize(bool do_shuffle = true)
Shuffle the table and mask invalid rows. Call
finalizebefore revealing the outputs to untrusted parties.- Parameters:
do_shuffle – whether to shuffle the table before revealing. default true. If not shuffled (or sorted in a known order), inference attacks may be possible.
-
inline DataTable open()
Opens the encoded table to all computing parties.
- Returns:
The opened (plaintext) table.
-
inline LabeledDataTable open_with_schema(bool remove_invalid = true)
Opens the encoded table to all computing parties and includes the schema.
- Returns:
A LabeledDataTable pair (a.k.a. pair<DataTable, vector<string>>) Access the column-major data via the first element of the pair, and the schema via the second. Both will be in the same order
-
inline void addColumns(const std::vector<std::string> &columns_, int rows_)
Creates table columns based on a schema.
- Parameters:
columns_ – The schema.
rows_ – The column length.
-
inline void addColumns(const std::vector<std::string> &columns_)
Create table columns given a list of names. All rows will have the same length as the current table.
- Parameters:
columns_ –
-
inline void addColumn(const std::string &column, const int rows_, std::optional<int> precision = std::nullopt)
Allocates a column of a given size and initializes it with zeros.
The default column encoding is A-shared. To create a B-shared column, you must enclose the column’s name with square brackets, i.e.
column=[name].- Parameters:
column – The name of the column to allocate.
rows_ – The column size in number of elements.
precision – Fixed-point precision (default 0).
-
inline void addColumn(const std::string &column)
Add a single column with the given name, with the default number of rows.
- Parameters:
column –
-
inline void deleteColumns(const std::vector<std::string> cols)
Remove provided columns from the table.
- Parameters:
cols – Vector of column names to remove
-
inline void project(const std::vector<std::string> cols)
Projection operation, i.e. only keep columns in the provided list.
- Parameters:
cols – Vector of column names to keep
-
inline std::string name() const
- Returns:
The table name.
-
inline size_t size() const
- Returns:
The table cardinality.
-
inline std::map<std::string, std::shared_ptr<EncodedColumn>> getSchema() const
Get the schema.
- Returns:
std::map<std::string, std::shared_ptr<EncodedColumn>>
-
inline std::vector<std::string> getColumnNames()
Get the column names.
- Returns:
std::vector<std::string>
-
inline SortInput_t prepare_sort_input(const std::vector<std::pair<std::string, SortOrder>> &spec, const std::vector<std::string> &to_be_sorted_columns, const SortingProtocol protocol = DEFAULT_SORT_PROTO)
Prepare the sorting input for the given specification.
- Parameters:
spec – The names of the columns to sort by along with a sorting direction.
to_be_sorted_columns – The non-sort columns to be sorted according to the sort columns.
protocol – The sorting protocol to use.
- Returns:
SortInput_t The sorting input to be passed to table_sort.
-
inline EncodedTable &sort(const std::vector<std::pair<std::string, SortOrder>> spec)
Sorts
thistable in place given a specification of columns and sorting directions using the default sorting protocol.- Parameters:
spec – The names of the columns to sort by along with a sorting direction.
- Returns:
-
inline EncodedTable &sort(const std::vector<std::pair<std::string, SortOrder>> spec, const SortingProtocol protocol)
Sorts
thistable in place given a specification of columns and sorting directions.- Parameters:
spec – The names of the columns to sort by along with a sorting direction.
protocol – The sorting protocol to use.
- Returns:
-
inline EncodedTable &sort(const std::vector<std::string> columns, SortOrder allOrder = ASC)
Sort all given columns in the same direction using the default sorting protocol.
- Parameters:
columns – The list of BSharedVColumns to sort on.
allOrder – The direction to sort all sort columns.
- Returns:
-
inline EncodedTable &sort(const std::vector<std::string> columns, SortOrder allOrder, const SortingProtocol protocol)
Sort all given columns in the same direction.
- Parameters:
columns – The list of BSharedVColumns to sort on.
allOrder – The direction to sort all sort columns.
protocol – The sorting protocol to use.
- Returns:
-
inline EncodedTable &sort(const std::vector<std::pair<std::string, SortOrder>> spec, const std::vector<std::string> &to_be_sorted_columns, const SortingProtocol protocol = DEFAULT_SORT_PROTO)
Sort the table given a specification.
- Parameters:
spec – The names of the columns to sort by along with a sorting direction.
to_be_sorted_columns – The non-sort columns to be sorted according to the sort columns.
protocol – The sorting protocol to use.
- Returns:
-
inline std::pair<int, int> get_perm_counts(const std::vector<std::pair<std::string, SortOrder>> spec, const SortingProtocol protocol = DEFAULT_SORT_PROTO)
Get the permutation counts for the given specification.
- Parameters:
spec – The specification of the columns to sort by along with a sorting direction.
- Returns:
The number of permutations and pairs required.
-
inline EncodedTable &shuffle()
Shuffles each column according to the same permutation.
-
inline EncodedTable &convert_a2b(const std::string &input_a, const std::string &output_b)
Convert column
input_ato binary and store the result inoutput_b- Parameters:
input_a –
output_b –
- Returns:
-
inline EncodedTable &convert_b2a_bit(const std::string &input_b, const std::string &output_a)
Convert the single-bit column
input_bto arithmetic and store the result inoutput_a- Parameters:
input_b –
output_a –
- Returns:
-
inline EncodedTable &aggregate(const std::vector<std::string> &_keys, AggregationSpec agg_spec, AggregationOptions opt = {})
perform odd-even aggregation.
- Parameters:
_keys – column names to perform aggregation over (i.e., group by)
agg_spec – the aggregation specification, a vector of tuples of (input, output, function).
opt – See
AggregationOptions
- Returns:
-
inline EncodedTable &distinct(const std::vector<std::string> &_keys, const std::string &_res)
Distinct operation on provided columns. Requires equivalent rows to be adjacent to be considered for the distinct.
- Parameters:
_keys – Column names on which to run distinct
_res – Column name to mark the result
- Returns:
-
inline EncodedTable &distinct(const std::vector<std::string> &_keys)
Single-argument wrapper around the base distinct operation. Performs other operations required for the distinct to work correctly.
- Parameters:
_keys – Column names on which to run distinct
- Returns:
Compute a tumbling window on the table.
- Parameters:
_time_a –
window_size –
_res –
- Returns:
Compute a gap session window on the table.
- Parameters:
_keys –
_time_a –
_time_b –
_window_id –
_gap –
_do_sorting –
- Returns:
Compute a threshold session window on the table.
- Parameters:
_keys –
_function_res –
_time_b –
_window_id –
_threshold –
_do_sorting –
_mark_valid –
- Returns:
-
inline void prefix_sum(std::string key)
Compute an (arithmetic) prefix sum on the column
key. NOTE: this ignores the valid vector, so may include invalid rows in the prefix sum. Only call this function if all rows are guaranteed to be valid, or invalid rows have already been zeroed out.- Parameters:
key –
-
inline EncodedTable &zero(const std::vector<std::string> &keys)
Zero out the specified columns.
- Parameters:
keys –
- Returns:
-
inline void head(size_t n)
Resize this table to have
nrows. Warn ifnis larger than the current size.NOTE: this does not create a copy. For that, use
deepcopyfirst.- Parameters:
n –
-
inline void tail(const size_t n)
Resize this table to only have its last
nrows. Warn ifnis larger than the current size.NOTE: this does not create a copy. For that, use
deepcopyfirst.- Parameters:
n –
-
inline void cut(size_t start, size_t end)
Destructively resize this table to only have rows in the range [start, end).
NOTE: this modifies the table in place. For a non-destructive version, use
deepcopyfirst.- Parameters:
start – Start index (inclusive)
end – End index (exclusive)
-
inline void resize(size_t n)
Resize this table to have
nrows. If n is larger than the current size, extend the table with invalid rows.- Parameters:
n –
Resize this table to the next power-of-two size. Required for aggregation, bitonic sort / merge.
By default, just resize the table, setting all padded values to 0. However, can optionally pad with a specified value; this is necessary for e.g. bitonic merge.
-
inline void deleteTable()
Delete the table. Memory will be released; it cannot be used again.
Used in larger queries where a table is no longer needed. Preferably, handle this automatically using scoping.
-
inline void renameColumn(std::string old_name, std::string new_name)
Rename a column in the EncodedTable.
This function allows you to change the name of an existing column in the table’s schema. It checks for the existence of the old column name and ensures that the new column name does not already exist in the schema.
Usage:
EncodedTable table(...); table.renameColumn("old_column_name", "new_column_name");
- Parameters:
old_name – The current name of the column to be renamed.
new_name – The new name to assign to the column.
- Throws:
std::runtime_error – if the old column name does not exist.
std::runtime_error – if the new column name already exists.
-
inline EncodedTable deepcopy()
Deep copy the table. Useful if you want to make changes to a table but also maintain the original data.
-
inline EncodedTable concatenate(EncodedTable &other, bool power_of_two = false)
concatenate two tables by appending. Rows from
otherare placed below those from the current table. Shared columns (i.e., those with the same column name) are merged. An additional column,[~TABLE_ID], will be added to denote which original table a given row came from.A new table will be created and returned; the existing tables will be unaffected.
If columns with the same name exist in both tables, but are not join keys, one of them should be renamed to prevent conflicts.
- Parameters:
other – the table to append
power_of_two – whether to add the table out to the next power of two
- Returns:
-
EncodedTable inner_join(EncodedTable &right, std::vector<std::string> keys, AggregationSpec agg_spec = {}, JoinOptions opt = {})
Inner join.
- Parameters:
right –
keys –
agg_spec –
opt –
- Returns:
TABLE_T
-
EncodedTable left_outer_join(EncodedTable &right, std::vector<std::string> keys, AggregationSpec agg_spec = {}, JoinOptions opt = {})
- Parameters:
right –
keys –
agg_spec –
opt –
- Returns:
TABLE_T
-
EncodedTable right_outer_join(EncodedTable &right, std::vector<std::string> keys, AggregationSpec agg_spec = {}, JoinOptions opt = {})
- Parameters:
right –
keys –
agg_spec –
opt –
- Returns:
TABLE_T
-
EncodedTable full_outer_join(EncodedTable &right, std::vector<std::string> keys, AggregationSpec agg_spec = {}, JoinOptions opt = {})
- Parameters:
right –
keys –
agg_spec –
opt –
- Returns:
TABLE_T
-
EncodedTable semi_join(EncodedTable &right, std::vector<std::string> keys)
Semi-join between this table and
right. Under the hood, performsright.inner_join(this). See the paper for more details on why this is correct.- Parameters:
right –
keys –
- Returns:
TABLE_T
-
EncodedTable anti_join(EncodedTable &right, std::vector<std::string> keys)
Anti-join between this table and
right. Under the hood, permsright.right_outer_join(this), along with some special handling of the valid bit. See the paper for more details on why this is correct.- Parameters:
right –
keys –
- Returns:
TABLE_T
-
EncodedTable uu_join(EncodedTable &right, std::vector<std::string> keys, AggregationSpec agg_spec = {}, JoinOptions opt = {}, const SortingProtocol protocol = DEFAULT_SORT_PROTO)
Unique key inner join. Execute a more optimized algorithm which only works if both tables have unique (compound) keys. Under oblivious compute, this condition of course cannot be checked, so it is the responsibility of the developer to verify application of this function is appropriate. Calling
uu_joinon tables with non-unique keys will return incorrect results.This effectively performs a private set intersection over
keys.- Parameters:
right –
keys –
agg_spec – Aggregation specification used for listing columns to copy from left table to output.
opt – aggregation options
protocol – which sorting protocol to use
- Returns:
TABLE_T
-
EncodedTable cartesian_join(EncodedTable &right, std::string key)
Perform a Cartesian product (quadratic) join between
thisandright. Used for benchmarking; for most applications, use inner_join. All columns are copied from both tables. A warning will be printed if duplicate columns exist. Columns from the left table take precedence.This function only supports a join on a single column. The VALID bit is automatically updated based on the results of the join. The output table will have exactly
L.size() * R.size()rows. No constraints are placed on the join keys.In general, this method is functionally equivalent to
L.inner_join(right, { key }, ...)
assuming the only aggregations are
copy<>calls.Warning. The resulting intermediate table may be too large to fit inside a standard C++ vector. If this happens, the system will throw an exception of type
std::length_error.- Parameters:
right –
key –
- Returns:
-
inline EncodedTable &extend_lsb(const std::string &_b_col)
Extend the LSB of a column. All other bits are ignored. A value ending with a binary
1will become all1s; namely,-1for signed types. values ending with a0will become 0. This function should be used to convert boolean 0/1 values into bitmasks, for selectively modifying certain columns.However, for actually hiding of invalid values, see
mask, above, to set those columns to the table-defined masking value.- Parameters:
_b_col – Column name to extend LSB for.
- Returns:
-
inline EncodedTable &mask()
Mask all columns using the VALID column.
- Returns:
Public Members
-
std::string tableName
Name of this table. Used for output and organization.
Public Static Functions
-
static inline bool isReserved(const std::string name)
Checks if a column is reserved/internal or not.
- Returns:
bool
Checks if a column with name
namecontains boolean shares.
NOTE: Names of columns that include boolean shares are within square brackets, i.e.,
[column_name].- Parameters:
name – The name of the column.
- Returns:
True if the column is B-shared, False otherwise.
-
static inline Vector<Share> get_column(std::pair<DataTable, std::vector<std::string>> table, std::string c)
Given an opened, labeled table, return the associated column. NOTE: Once we replace LabeledDataTable with a better-implemented class this can go away.
We need this to be a member function because it needs to know the correct template arguments for DataTable and Share.
Given an opened, labeled table, return the associated column. We need this to be a member function because it needs to know the correct template arguments for DataTable and Share.
TODO: Replace LabeledDataTable with a better-implemented class so this can go away.
- Parameters:
table –
c – column name
- Returns:
* Vector<Share>
Private Types
Private Functions
-
inline EncodedTable &mask(const std::string &mask_column_name, const std::vector<std::string> &keys)
Mask the contents of multiple columns using the type’s mask value (usually the maximum value). This is useful for obliviously hiding rows that are not selected for output by some prior process.
Rows which have a
1in the mask column will remain untouched. Rows which have a0in the mask column will be set to MASK_VALUE.Will NOT mask the mask-column itself.
- Parameters:
mask_column_name – the column to use as the mask
keys – which other columns to mask
- Returns:
-
inline EncodedTable &mask(const std::string &mask_column_name)
Mask all columns (except the mask itself)
- Parameters:
mask_column_name –
- Returns:
-
EncodedTable _join(EncodedTable &right, std::vector<std::string> keys, AggregationSpec agg_spec, JoinOptions opt)
Internal join implementation.
Arbitrary join between this table and
right. assumes primary key-foreign key relationship, but does not enforce.Used to implement EncodedTable::inner_join, EncodedTable::left_outer_join, EncodedTable::right_outer_join, EncodedTable::full_outer_join, EncodedTable::semi_join, and EncodedTable::anti_join
- Parameters:
right – the other table
keys – the set of key(s) to join on, with a primary (this table) / foreign key (
righttable) relationshipagg_spec – an aggregation specification, a vector of tuples consisting of
{input-column, output-column, aggregation-type}opt – See
JoinOptions
- Returns:
TABLE_T
-
template<typename T>
inline void copy_column_typed(EncodedTable &t, std::string from, std::string to, VectorSizeType start_index = 0) Copy column from table
tinto this table. This table’s schema is assumed to already contain a column of the correct name.- Template Parameters:
T – the type of the vector
ASharedVectororBSharedVector- Parameters:
t – source table
from – the table to copy from
to – column name to copy
start_index – the row in this table where the copied column should be placed (default 0)
-
inline void copy_column(EncodedTable &t, std::string from, std::string to, VectorSizeType start_index = 0)
Untyped copy column - see copy_column_typed<T>
- Parameters:
t –
from –
to –
start_index –
-
inline void copy_column(EncodedTable &t, std::string name, VectorSizeType start_index = 0)
Copy column
namefrom tabletinto this table using the same name.- Parameters:
t –
name –
start_index –
Utilities & Base Classes
-
class EncodedVector
A EncodedVector is the main programming abstraction in cdough. All secure operators are applied to encoded vectors, i.e., they take one or more encoded vectors as input and generate one or more encoded vectors as output. cdough computing parties perform secure operations on their encoded vectors as if they were performing plaintext operations on the original (secret) vectors. For example, given two secret vectors v1 and v2, cdough parties can execute the elementwise addition of the secret vectors by simply running v1 + v2 using their local encoded vectors. This way, the cdough program looks identical to the respective plaintext program, as shown below:
Plaintext program (not secure)
cdough program (secure)// Executed by a trusted party auto w = v1 + v2; // These are C++ vectors and '+' is the elementwise plaintext addition
// Executed by an untrusted party auto w = v1 + v2; // These are EncodedVectors and '+' is the elementwise secure addition
Subclassed by cdough::SharedVector< Share, EVector, Engine >, cdough::SharedVector< int, cdough::EVector< int, EVector::replicationNumber >, Engine >, cdough::SharedVector< T, E, Engine >, cdough::SharedVector< T, Container, Engine >
Public Functions
-
inline EncodedVector(const Encoding &eType)
Constructor
- Parameters:
eType – The vector’s encoding (e.g., A-shared, B-shared, etc.)
-
inline virtual ~EncodedVector()
-
virtual VectorSizeType size() const = 0
-
virtual void setPrecision(const int fixed_point_precision) = 0
Gets the fixed-point precision. Virtual to let subclasses override.
-
virtual size_t getPrecision() const = 0
Gets the fixed-point precision. Virtual to let subclasses override.
Friends
- friend class EncodedColumn
-
inline EncodedVector(const Encoding &eType)
-
class EncodedColumn
An encoded table column that supports vectorized secure operations. Internally stores an encoded vector, and passes all operations down to that vector.
Subclassed by cdough::relational::SharedColumn< T, GenericInnerContainer< T >, RunTime >, cdough::relational::SharedColumn< Share, EVector, Engine >
Public Functions
-
inline virtual ~EncodedColumn()
-
virtual size_t size() const = 0
- Returns:
The column’s size in number of elements.
-
virtual size_t getPrecision() const = 0
Gets the fixed-point precision. Virtual to let subclasses override.
-
virtual void zero() = 0
-
virtual std::unique_ptr<EncodedColumn> deepcopy() = 0
-
virtual std::unique_ptr<EncodedColumn> ltz() = 0
-
virtual std::unique_ptr<EncodedColumn> operator+(const EncodedColumn &other) const = 0
Elementwise secure arithmetic addition.
- Parameters:
other – The second operand of addition.
- Returns:
A unique pointer to an EncodedColumn that contains encoded results of the elementwise additions.
-
virtual std::unique_ptr<EncodedColumn> operator+(int64_t other) const = 0
-
virtual EncodedColumn &operator+=(const EncodedColumn &other) = 0
-
virtual std::unique_ptr<EncodedColumn> operator-(const EncodedColumn &other) const = 0
Elementwise secure arithmetic subtraction.
- Parameters:
other – The second operand of subtraction.
- Returns:
A unique pointer to an EncodedColumn that contains encoded results of the elementwise subtractions.
-
virtual std::unique_ptr<EncodedColumn> operator-(int64_t other) const = 0
-
virtual EncodedColumn &operator-=(const EncodedColumn &other) = 0
-
virtual std::unique_ptr<EncodedColumn> operator-() const = 0
Elementwise secure arithmetic negation.
- Returns:
A unique pointer to an EncodedColumn with all elements of
thisEncodedColumn negated.
-
virtual std::unique_ptr<EncodedColumn> operator*(const EncodedColumn &other) const = 0
Elementwise secure arithmetic multiplication.
- Parameters:
other – The second operand of multiplication.
- Returns:
A unique pointer to an EncodedColumn that contains encoded results of the elementwise multiplications.
-
virtual std::unique_ptr<EncodedColumn> operator*(int64_t other) const = 0
-
virtual EncodedColumn &operator*=(const EncodedColumn &other) = 0
-
virtual std::unique_ptr<EncodedColumn> operator/(const EncodedColumn &other) const = 0
Elementwise secure schoolbook (binary) division.
- Parameters:
other –
- Returns:
std::unique_ptr<EncodedColumn>
-
virtual std::unique_ptr<EncodedColumn> operator/(int64_t other) const = 0
-
virtual std::unique_ptr<EncodedColumn> operator^(const EncodedColumn &other) const = 0
Elementwise secure bitwise XOR.
- Parameters:
other – The second operand of XOR.
- Returns:
A unique pointer to an EncodedColumn that contains encoded results of the elementwise XORs.
-
virtual std::unique_ptr<EncodedColumn> operator^(int64_t other) const = 0
-
virtual EncodedColumn &operator^=(const EncodedColumn &other) = 0
-
virtual std::unique_ptr<EncodedColumn> operator&(const EncodedColumn &other) const = 0
Elementwise secure bitwise AND.
- Parameters:
other – The second operand of AND.
- Returns:
A unique pointer to an EncodedColumn that contains encoded results of the elementwise ANDs.
-
virtual std::unique_ptr<EncodedColumn> operator&(int64_t other) const = 0
-
virtual EncodedColumn &operator&=(const EncodedColumn &other) = 0
-
virtual std::unique_ptr<EncodedColumn> operator&&(const EncodedColumn &other) const = 0
-
virtual std::unique_ptr<EncodedColumn> operator|(const EncodedColumn &other) const = 0
Elementwise secure bitwise OR.
- Parameters:
other – The second operand of OR.
- Returns:
A unique pointer to an EncodedColumn that contains encoded results of the elementwise ORs.
-
virtual std::unique_ptr<EncodedColumn> operator|(int64_t other) const = 0
-
virtual EncodedColumn &operator|=(const EncodedColumn &other) = 0
-
virtual std::unique_ptr<EncodedColumn> operator||(const EncodedColumn &other) const = 0
-
virtual std::unique_ptr<EncodedColumn> operator~() const = 0
Elementwise secure boolean completion.
- Returns:
A unique pointer to an EncodedColumn with all elements of
thisEncodedColumn complemented.
-
virtual std::unique_ptr<EncodedColumn> operator!() const = 0
Elementwise secure boolean negation.
- Returns:
A unique pointer to an EncodedColumn with all results of
thisEncodedColumn negated.
-
virtual std::unique_ptr<EncodedColumn> operator<<(int64_t y) const = 0
Elementwise shifts.
- Parameters:
y – shift amount
- Returns:
std::unique_ptr<EncodedColumn>
-
virtual std::unique_ptr<EncodedColumn> operator>>(int64_t y) const = 0
-
virtual std::unique_ptr<EncodedColumn> operator==(const EncodedColumn &other) const = 0
Elementwise secure equality.
- Parameters:
other – The second operand of equality.
- Returns:
A unique pointer to an EncodedColumn that contains encoded results of the elementwise equality comparisons.
-
virtual std::unique_ptr<EncodedColumn> operator==(int64_t other) const = 0
-
virtual std::unique_ptr<EncodedColumn> operator!=(const EncodedColumn &other) const = 0
Elementwise secure inequality.
- Parameters:
other – The second operand of inequality.
- Returns:
A unique pointer to an EncodedColumn that contains encoded results of the elementwise inequality comparisons.
-
virtual std::unique_ptr<EncodedColumn> operator!=(int64_t other) const = 0
-
virtual std::unique_ptr<EncodedColumn> operator>(const EncodedColumn &other) const = 0
Elementwise secure greater-than.
- Parameters:
other – The second operand of greater-than.
- Returns:
A unique pointer to an EncodedColumn that contains encoded results of the elementwise greater-than comparisons.
-
virtual std::unique_ptr<EncodedColumn> operator>(int64_t other) const = 0
-
virtual std::unique_ptr<EncodedColumn> operator>=(const EncodedColumn &other) const = 0
Elementwise secure greater-or-equal.
- Parameters:
other – The second operand of greater-or-equal.
- Returns:
A unique pointer to an EncodedColumn that contains encoded results of the elementwise greater-or-equal comparisons.
-
virtual std::unique_ptr<EncodedColumn> operator>=(int64_t other) const = 0
-
virtual std::unique_ptr<EncodedColumn> operator<(const EncodedColumn &other) const = 0
Elementwise secure less-than.
- Parameters:
other – The second operand of less-than.
- Returns:
A unique pointer to an EncodedColumn that contains encoded results of the elementwise less-than comparisons.
-
virtual std::unique_ptr<EncodedColumn> operator<(int64_t other) const = 0
-
virtual std::unique_ptr<EncodedColumn> operator<=(const EncodedColumn &other) const = 0
Elementwise secure less-or-equal.
- Parameters:
other – The second operand of less-or-equal.
- Returns:
A unique pointer to an EncodedColumn that contains encoded results of the elementwise less-or-equal comparisons.
-
virtual std::unique_ptr<EncodedColumn> operator<=(int64_t other) const = 0
-
virtual EncodedColumn &operator=(std::unique_ptr<EncodedColumn> &&other) = 0
Column assignment.
- Parameters:
other – The unique pointer to the column whose contents will be moved to
thiscolumn.- Returns:
A reference to
thiscolumn after modification.
Public Members
-
std::unique_ptr<EncodedVector> contents
The column’s contents (i.e., an encoded vector).
-
std::string name
The column’s name
Friends
- friend class EncodedTable
-
inline virtual ~EncodedColumn()
-
namespace cdough
Enums
-
enum Encoding
Vector encoding types.
Values:
-
enum Encoding
-
namespace cdough
-
template<typename T, std::random_access_iterator D, std::random_access_iterator M>
class MappedIterator - #include <mapped_iterator.h>
Public Functions
-
inline MappedIterator()
-
inline MappedIterator(std::vector<T>::iterator _dataIter, std::vector<VectorSizeType>::iterator _mappingIter)
-
inline T &operator[](difference_type i) const
-
inline MappedIterator &operator++()
-
inline MappedIterator operator++(int)
-
inline MappedIterator &operator--()
-
inline MappedIterator operator--(int)
-
inline MappedIterator &operator+=(difference_type n)
-
inline MappedIterator operator+(difference_type n) const
-
inline MappedIterator &operator-=(difference_type n)
-
inline MappedIterator operator-(difference_type n) const
-
inline difference_type operator-(const MappedIterator &other) const
-
inline bool operator<(const MappedIterator &other) const
-
inline bool operator>(const MappedIterator &other) const
-
inline bool operator<=(const MappedIterator &other) const
-
inline bool operator>=(const MappedIterator &other) const
-
inline bool operator==(const MappedIterator &other) const
Friends
-
inline friend MappedIterator operator+(difference_type n, const MappedIterator &other)
-
inline MappedIterator()
-
template<typename T, std::random_access_iterator D, std::random_access_iterator M>
Defines
-
define_binary_vector_op(_op_)
-
define_unary_vector_op(_op_)
-
define_binary_vector_element_op(_op_)
-
define_binary_vector_assignment_op(_op_)
-
namespace cdough
Functions
-
template<typename T>
static inline T getBit(const T &share, int bitIndex) Extracts the bit at
bitIndexfrom the given element. Use dedicated hardware instruction if available.- Parameters:
share – The vector element whose bit we want to extract.
bitIndex – The zero-based index (0 is the LSB).
- Returns:
The extracted bit as a single-bit T element.
-
template<typename T>
static inline void setBit(T &share, const T &bit, int bitIndex) Sets the bit at
bitIndexin elementshareequal to the LSB of elementbit.- Parameters:
share – The element whose bit we want to update.
bit – The element whose LSB must be copied into
share.bitIndex – The zero-based index (0 is the LSB) of the bit to be updated in element
share.
-
template<typename T>
static inline void clrBit(T &share, int bitIndex) Clear the bit at position
bitIndex(i.e., set it to zero)- Template Parameters:
T –
- Parameters:
share –
bitIndex –
-
template<typename T>
static inline void setBitValue(T &share, const T &value, int bitIndex) Set the the bit at the given index to the value provided.
- Template Parameters:
T –
- Parameters:
share – Vector element to modify
value – binary value to set the specified bit to
bitIndex – which bit to modify
-
template<typename T>
static inline void setBitMask(T &share, const bool &value, const std::make_unsigned_t<T> &mask) Conditionally set bits in
share, masked bymask, based on the booleanvalueflag.Optimized version from https://graphics.stanford.edu/~seander/bithacks.html
It’s not immediately clear to me that this is faster, but perhaps better on certain processors, or with certain optimizations enabled.
- Parameters:
share – the element to operate on
value – whether the bits should be set or cleared
mask – which bits to modify
Same as BSharedVector::compare_rows() but works with plaintext data. Used for testing.
Compares two
MxNarrays row-wise by applyingMgreater-than comparisons onNkeys.NOTE: The i-th row, let l, from the left array is greater than the i-th row, let r, from the right array if l’s first key is greater than r’s first key, or the first keys are the same and l’s second key is greater than r’s second key, or the first two keys are the same and so forth, for all keys.
- Template Parameters:
Share – Share data type.
- Parameters:
x_vec – The left column-first array with
Mrows andNcolumns.y_vec – The right column-first array with
Mrows andNcolumns.inverse – A vector of
Nboolean values that denotes the order of comparison per key (ifinverse[i]=True, then rows fromx_vecandy_vecare swapped in the comparison on the i-th column.
- Returns:
A new vector that contains the result bits of the
Mgreater-than comparisons.
Same as BSharedVector::swap() but works with plaintext data. Used for testing.
Swaps rows of two
MxNarrays in place using the providedbits.- Template Parameters:
Share – Share data type.
- Parameters:
x_vec – The left column-first array with
Mrows andNcolumns.y_vec – The right column-first array with
Mrows andNcolumns.bits – The vector that contains the ‘M’ bits to use for swapping (if bits[i]=True, the i-th rows will be swapped).
Same as BSharedVector::swap() but works with plaintext data. Used for testing.
Swaps rows of two
MxNarrays in place using the providedbits.- Template Parameters:
Share – Share data type.
- Parameters:
x_vec – The left column-first array with
Mrows andNcolumns.y_vec – The right column-first array with
Mrows andNcolumns.bits – The vector that contains the ‘M’ bits to use for swapping (if bits[i]=True, the i-th rows will be swapped).
-
template<typename T>
class Vector - #include <class_access_vector.h>
cdough’s wrapper of std::vector<T> that provides vectorized plaintext operations. A mock vector implementation which stores no data and returns nothing (or garbage) for all operations. Most functions do nothing at all, or just compute the appropriate length that their correct equivalent would output. This is useful for testing and profiling, since it is extremely fast and performs no data movement.
- Template Parameters:
T – The type of elements in the Vector (e.g., int, long, long long, etc.)
T – The nominal element type
Public Types
-
using value_type = T
Public Functions
-
inline void setPrecision(const int fixed_point_precision)
Sets the fixed-point precision.
- Parameters:
fixed_point_precision – - the number of fixed-point fractional bits.
-
inline size_t getPrecision() const
Gets the fixed-point precision.
-
inline void matchPrecision(const Vector<T> &other)
Helper that sets this vector’s precision to match another Vector.
- Parameters:
other – The Vector whose precision should be copied.
-
inline size_t total_size() const
- Returns:
The total number of elements in the vector.
-
inline std::vector<T>::iterator begin()
NOTE: This method is used by the communicator.
- Returns:
An iterator pointing to the first element.
-
inline std::vector<T>::iterator end()
NOTE: This method is used by the communicator.
- Returns:
An iterator pointing to the last element.
-
inline Vector simple_subset_reference(const int _start_index, const int _step, const int _end_index) const
- data. In other words, composition will not work; new mapping pattern replaces the previous one.
This is the generic function in order create a new mapping for this vector. Note: that the function does not allocate a new memory location for data. Note: the mapping maps from the new index space to the original index space for
- Parameters:
_subset_offset – the index of the first element of the original vector to apply the pattern.
_subset_step – the index difference between the mapped to elements within each chunks.
_subset_included_size – the maximum size of each included chunk.
_subset_excluded_size – the maximum size of each excluded chunk. (included and excluded chunks alternate after offset).
_subset_direction – the direction of choosing elements (increasing index = 1) (decreasing index = -1).
_subset_repetition – number of times to repeat same mapped-to-elements after each other.
_subset_cycles – number of times concatenate the whole mapped-to-elements in the new reference.
_subset_offset – the index of the first element of the original vector to apply the pattern. (default = 0)
_subset_step – the index of the difference between each two included elements. (default = 1)
_subset_included_size – the size of the elements on which the pattern is applied. (default = total_size())
- Returns:
Vector that points to the same memory location as the new one but different mapping for the indices. Remaps the index space to choose a number of elements of the current vector. Note: returned Vector points to the same memory location.
- Returns:
Vector that has different index mapping to the original vector elements.
-
inline Vector simple_subset_reference(const int _start_index, const int _step) const
-
inline Vector simple_subset_reference(const int _start_index) const
-
inline Vector alternating_subset_reference(const size_t _subset_included_size, const size_t _subset_excluded_size) const
Applies an alternating pattern to include and exclude elements. It applies the pattern starting with the element with
index = _subset_offset. It then keeps alternating elements as included in the pattern of or excluded from the pattern using the_subset_included_sizeand the_subset_excluded_sizefor each included or excluded chunk.- Parameters:
_subset_offset – the index of the first element to apply the pattern.
_subset_step – the difference two each two included elements within the included the chunks.
_subset_included_size – the size of a number of elements that we choosing from.
_subset_excluded_size – the size of a number of elements that we are totally not choosing.
- Returns:
Vectorthat points to the same memory location as the original vector but with different index mapping.
-
inline Vector reversed_alternating_subset_reference(const size_t _subset_included_size, const size_t _subset_excluded_size) const
-
inline Vector repeated_subset_reference(const size_t _subset_repetition) const
Applies a new indexing mapping to the current vector so that each element is repeated a number of times consecutively.
- Parameters:
_subset_repetition – the number of times each element is repeated.
- Returns:
Vectorthat points to the same memory location as the original vector but with different index mapping.
-
inline Vector cyclic_subset_reference(const size_t _subset_cycles) const
Applies a new indexing mapping such that after accessing the last element, we access the first element again and keep accessing the elements in cycles.
- Parameters:
_subset_cycles – the number of cycles the new indexing mapping will contain.
- Returns:
Vectorthat points to the same memory location as the original vector but with different index mapping.
-
inline Vector directed_subset_reference(const size_t _subset_direction) const
Applies a new mapping indexing that controls the order in which the elements accessed.
- Parameters:
_subset_direction – set to (1) to keep current order or (-1) to reverse the order.
- Returns:
Vectorthat points to the same memory location as the original vector but with different index mapping.
-
inline Vector simple_bit_compress(size_t start, size_t step, size_t end, size_t repetition) const
This function extracts bits from current vector and append them in sequence into another vector. The functions chooses the bits by getting the needed parameters to loop through the bits in each element.
- Parameters:
start – index of the first bit to be included (lowest significant).
step – difference in index between each two consecutive bits.
end – index of the last bit bit to be included (most significant)
repetition – number of times each bit will be included.
- Returns:
a new
Vectorthat has only the chosen bits in its elements (less size than input).
-
inline void simple_bit_compress(Vector &res, size_t position) const
simple_bit_compress, optimized for the (i, 1, i, 1) case. This version further operates on a passed vector, rather than returning a new Vector.
- Parameters:
res – vector to compress into
position – single bit position to compress (= start = end)
-
inline void simple_bit_decompress(const Vector &other, size_t start, size_t step, size_t end, size_t repetition)
Function to reverse the simple_bit_compress function. it takes an already compressed
Vectorand assign from it the corresponding bits to the this called onVector.- Parameters:
other – the vector that has the compressed bits.
start – index of the first bit to be included (lowest significant).
step – difference in index between each two consecutive bits.
end – index of the last bit bit to be included (most significant)
repetition – number of times each bit will be included.
-
inline void simple_bit_decompress(const Vector &other, const T &position)
Optimized version of simple_bit_compress for the single- position case.
Note: in testing, setBitMask was not noticeably faster than setBitValue
- Parameters:
other – vector to decompress into this
position – the bit position to decompress
-
inline Vector alternating_bit_compress(size_t start, size_t step, size_t included_size, size_t excluded_size, int direction) const
This function extracts bits from current vector and append them in sequence into another vector. The function chooses bits as follows. First it skips till the start index (from lowest significant). Then it splits the bits into sequences of included chunks and excluded chunks. From the included bits chunks, bits that
stepindex difference apart are chosen. If direction is set to1, picking starts from lowest significant bits. If it is set to-1, picking starts from most significant bits.- Parameters:
start – index of the first bit to start the included/excluded chunks pattern.
step – difference between each two consecutive bits in each included chunk.
included_size – size of each included chunk.
excluded_size – size of each excluded chunk.
direction – direction for picking up the bits in each included_size chunk.
1means least significant first.-1means most significant first.
- Returns:
a new
Vectorthat has only the chosen bits in its elements (less size than input).
-
inline Vector alternating_bit_compress(size_t start, size_t step, size_t included_size, size_t excluded_size) const
-
inline void alternating_bit_decompress(const Vector &other, size_t start, size_t step, size_t included_size, size_t excluded_size, int direction) const
Function to reverse the alternating_bit_compress function. it takes an already compressed
Vectorand assign from it the corresponding bits to the this called onVector.- Parameters:
other – the vector that has the compressed bits.
start – index of the first bit to start the included/excluded chunks pattern.
step – difference between each two consecutive bits in each included chunk.
included_size – size of each included chunk.
excluded_size – size of each excluded chunk.
direction – direction for picking up the bits in each included_size chunk.
1means least significant first.-1means most significant first.
-
inline Vector(size_t _size, T _init_val = 0)
This constructor allows for creating a new vector by just passing initialization parameters for inner `data` variable. @tparam T is a generic type to allow for different constructors for the variabledata.- Parameters:
args – is the packed parameters passed to
datainitializer. Creates a Vector ofsizevalues initialize toinit_val(0 by default).size – The size of the new Vector.
-
inline Vector(std::vector<T> &&_other)
Move constructor
- Parameters:
other – The std::vector<T> whose elements will be moved to the new Vector.
-
inline Vector(std::vector<T> &_other)
Copy constructor
- Parameters:
other – The std::vector<T> whose elements will be copied to the new Vector.
-
inline Vector(std::initializer_list<T> &&elements)
Constructs a new Vector from a list of
Telements.- Parameters:
elements – The list of elements of the new Vector.
-
inline Vector(const Vector &other)
This is a shallow copy constructor.
WARNING: The new vector will point to the same memory location used by
other. To copy the data into a separate memory location, create a new vector first then use assignment operator.- Parameters:
other – The vector that contains the std::vector<T> pointer to be copied.
-
inline Vector(std::shared_ptr<VectorDataBase<T>> other)
-
inline Vector &operator=(const Vector &&other)
This is a deep move assignment operator. Applies the move assignment operator to T. Assigns the contents of the
othervector to the this vector. Assumesotherhas the same size as this vector.
NOTE: This method works relatively to the current batch.
- Parameters:
other – The Vector that contains the values to be assigned to this vector.
- Returns:
A reference to this vector after modification.
-
inline Vector &operator=(const Vector &other)
This is a deep copy assignment operator. Applies the copy assignment operator to T. Copies the contents of the
othervector to this vector. Assumesotherhas the same size as this vector.- Parameters:
other – the Vector that contains the values to be copied.
- Returns:
A reference to
thisVector after modification.
-
template<typename OtherT>
inline Vector &operator=(const Vector<OtherT> &other) Copy-and-cast assignment operator. Allows (down)casting elements from a vector of one type into another.
-
inline Vector simple_subset(size_t start, size_t size) const
Returns a new vector that contains all elements in the range [start, end].
NOTE: This method works relatively to the current batch.
- Parameters:
start – The index of the first element to be included in the output vector.
end – The index of the last element to be included in the output vector.
- Returns:
A new vector that contains the selected elements.
-
inline void mask(const T &n)
Masks each element in
thisvector by doing a bitwise logical AND withn.- Parameters:
n – The mask.
-
inline void zero()
Sets every element of this vector to zero.
-
inline Vector bit_level_shift(int log_level_size) const
Creates a new Vector whose i-th element is generated by:
splitting the bit representation of the i-th element of
thisVector into parts of sizelevel_size, andsetting all bits of the least significant half of each part equal to the LSB of the most significant part.
NOTE: This method is used in secure greater-than and works relatively to the current batch.
Moved from private so we can test this method externally.
- Parameters:
log_level_size – log2 of the maximum chunk size (indexes into
LEVEL_MASKS)- Returns:
A new vector that contains elements generated as described above.
-
inline size_t size() const
NOTE: This method works relatively to the current batch.
- Returns:
The number of elements in the vector.
-
inline Vector operator-() const
Elementwise plaintext negation.
-
inline Vector operator~() const
Elementwise plaintext boolean complement.
-
inline Vector operator!() const
Elementwise plaintext boolean negation.
-
inline Vector ltz() const
Elementwise plaintext less-than-zero comparison.
-
inline Vector extend_lsb() const
Elementwise plaintext LSB extension: set all bits equal to the LSB. Note: this is only makes sense for bit shares.
-
inline T &operator[](int index)
Returns a mutable reference to the element at the given
index.
NOTE: This method works relatively to the current batch.
- Parameters:
index – The index of the target element.
- Returns:
A mutable reference to the element at the given
index.
-
inline const T &operator[](int index) const
Returns an immutable reference of the element at the given
index.
NOTE: This method works relatively to the current batch.
- Parameters:
index – The index of the target element.
- Returns:
Returns a read-only reference of the element at the given
index.
-
inline bool same_as(const Vector<T> &other) const
- whose i-th element equals the (i/n)-th bit of the (in)-th element of
Unpacks bits in the elements of `this` vector to create a new vector of size `n`
thisvector.- Parameters:
n – The number of bits to ‘unpack’.
other – The vector to compare
thiswith.
- Returns:
A new Vector that contains
nsingle-bit elements constructed as described above. Checks if the two input vectors (thisandother) contain the same elements.- Returns:
True if
thisvector contains the same elements withother, False otherwise.
Public Members
-
std::shared_ptr<VectorDataBase<T>> data
A (shared) pointer to the actual vector contents.
NOTE: Shallow copying of this object creates two instances that share the same data.
Public Static Attributes
-
static const int LEVEL_MASK_SIZE = 7
-
static const uint64_t constexpr LEVEL_MASKS[LEVEL_MASK_SIZE] = {0xffffffffffffffff, 0xaaaaaaaaaaaaaaaa, 0x4444444444444444, 0x1010101010101010, 0x0100010001000100, 0x0001000000010000, 0x0000000100000000,}
Mask for level 2^i (64 bits). Gives LSB of the most significant half of each chunk.
Private Types
-
using Unsigned_type = typename std::make_unsigned<T>::type
Private Functions
-
inline Vector reverse_bit_level_shift(int level_size) const
Creates a new Vector whose i-th element is generated by:
splitting the bit representation of the i-th element of
thisVector into parts of sizelevel_size, andsetting all bits of the most significant half of each part equal to the MSB of the least significant half.
NOTE: This method is bit_level_shift but from right to left, and is used in the parallel prefix adder for boolean addition.
- Parameters:
level_size – The number of bits (2^k, k>0) of each part within the bit representation of an element.
- Returns:
A new vector that contains elements generated as described above.
-
inline Vector bit_arithmetic_right_shift(int shift_size) const
Creates a new Vector that contains all elements of
thisVector right-shifted byshift_size. Arithmetic shift is used: signed types will have their MSB copied. To shift in zero instead, usebit_logical_right_shift.
NOTE: This method works relatively to the current batch.
- Parameters:
shift_size – The number of bits to right-shift each element of
thisVector.- Returns:
A new Vector that contains the right-shifted elements.
-
inline Vector bit_logical_right_shift(int shift_size) const
Creates a new Vector that contains all elements of
thisVector right-shifted byshift_size. This performs logical shift: zeros are shifted into the MSB. To copy the sign, usebit_arithmetic_right_shiftNOTE: This method works relatively to the current batch.- Parameters:
shift_size – The number of bits to right-shift each element of
thisVector.- Returns:
A new Vector that contains the right-shifted elements.
-
inline Vector bit_left_shift(int shift_size) const
Creates a new Vector that contains all elements of
thisVector left-shifted byshift_size.
NOTE: This method works relatively to the current batch.
- Parameters:
shift_size – The number of bits to left-shift each element of
thisVector.- Returns:
A new Vector that contains the left-shifted elements.
-
inline Vector bit_xor() const
Creates a new Vector whose i-th element is a single bit generated by XORing all bits of the i-th element of
thisVector, 0 <= i < size(). (Basically parity check of each element.)
NOTE: This method works relatively to the current batch.
- Returns:
A new Vector that contains single-bit elements generated as described above.
-
inline Vector simple_subset(int start, int step, int end) const
Returns a new vector containing elements in the range [start, end] that are
steppositions apart.
NOTE: This method works relatively to the current batch.
- Parameters:
start – The index of the first element to be included in the output vector.
step – The distance between two consecutive elements.
end – The maximum possible index of the last element to be included in the output vector.
- Returns:
A new vector that contains the selected elements.
-
inline void reset_batch()
Sets the current batch equal to the whole vector.
-
inline void set_batch(int _start_ind, int _end_ind)
Sets start and end index of the current batch. If the start index is negative, the start index is set to zero. If the end index is greater than the Vector’s size, the end index is set the max possible index.
- Parameters:
_start_ind – The index of the first element in the current batch.
_end_ind – The index of the last element in the current batch.
Private Members
-
int batch_start = 0
-
int batch_end = 0
-
const int MAX_BITS_NUMBER = std::numeric_limits<Unsigned_type>::digits
-
size_t precision = 0
Fixed-point precision (number of fractional bits)
Friends
- friend class EVector
- friend class service::RunTime
- friend class cdough::service::Task_1
- friend class cdough::service::Task_2
- friend class cdough::service::Task_ARGS_RTR_1
- friend class cdough::service::Task_ARGS_RTR_2
- friend class cdough::service::Task_ARGS_VOID_1
- friend class cdough::service::Task_ARGS_VOID_2
-
namespace service
-
template<typename T>
Defines
-
define_binary_vector_op(_op_)
Define a binary operation between two vectors, such as
a - b.
-
define_unary_vector_op(_op_)
Define a unary operation with one vector, such as
~a.
-
define_binary_vector_element_op(_op_)
Define a binary operation with a vector and an element, such as
a * 2.
-
define_binary_vector_assignment_op(_op_)
Define a Vector assignment operator with a Vector, such as
a &= b.
-
define_binary_vector_element_assignment_op(_op_)
Define a Vector assignment operator with an element, such as
a += 1.
-
_bextr_u64(x, y, z)
-
namespace cdough
Functions
-
template<typename T>
static inline T getBit(const T &share, int bitIndex) Extracts the bit at
bitIndexfrom the given element. Use a dedicated hardware instruction if available (x86 SSE only).- Parameters:
share – The vector element whose bit we want to extract.
bitIndex – The zero-based index (0 is the LSB).
- Returns:
The extracted bit as a single-bit T element.
-
template<typename T>
static inline void setBit(T &share, const T &bit, int bitIndex) Sets the bit at
bitIndexin elementshareequal to the LSB of elementbit.- Parameters:
share – The element whose bit we want to update.
bit – The element whose LSB must be copied into
share.bitIndex – The zero-based index (0 is the LSB) of the bit to be updated in element
share.
-
template<typename T>
static inline void clrBit(T &share, int bitIndex) Clear the bit at position
bitIndex(i.e., set it to zero)- Template Parameters:
T –
- Parameters:
share –
bitIndex –
-
template<typename T>
static inline void setBitValue(T &share, const T &value, int bitIndex) Set the the bit at the given index to the value provided.
- Template Parameters:
T –
- Parameters:
share – Vector element to modify
value – binary value to set the specified bit to
bitIndex – which bit to modify
-
template<typename T>
static inline void setBitMask(T &share, const bool &value, const std::make_unsigned_t<T> &mask) Conditionally set bits in
share, masked bymask, based on the booleanvalueflag.Optimized version from https://graphics.stanford.edu/~seander/bithacks.html
It’s not immediately clear to me that this is faster, but perhaps better on certain processors, or with certain optimizations enabled.
- Parameters:
share – the element to operate on
value – whether the bits should be set or cleared
mask – which bits to modify
-
template<typename Share>
static Vector<Share> compare_rows(const std::vector<Vector<Share>*> &x_vec, const std::vector<Vector<Share>*> &y_vec, const std::vector<bool> &inverse) Same as BSharedVector::compare_rows() but works with plaintext data. Used for testing.
Compares two
MxNarrays row-wise by applyingMgreater-than comparisons onNkeys.NOTE: The i-th row, let l, from the left array is greater than the i-th row, let r, from the right array if l’s first key is greater than r’s first key, or the first keys are the same and l’s second key is greater than r’s second key, or the first two keys are the same and so forth, for all keys.
- Template Parameters:
Share – Share data type.
- Parameters:
x_vec – The left column-first array with
Mrows andNcolumns.y_vec – The right column-first array with
Mrows andNcolumns.inverse – A vector of
Nboolean values that denotes the order of comparison per key (ifinverse[i]=True, then rows fromx_vecandy_vecare swapped in the comparison on the i-th column.
- Returns:
A new vector that contains the result bits of the
Mgreater-than comparisons.
-
template<typename Share>
static void swap(std::vector<Vector<Share>*> &x_vec, std::vector<Vector<Share>*> &y_vec, const Vector<Share> &bits) Same as BSharedVector::swap() but works with plaintext data. Used for testing.
Swaps rows of two
MxNarrays in place using the providedbits.- Template Parameters:
Share – Share data type.
- Parameters:
x_vec – The left column-first array with
Mrows andNcolumns.y_vec – The right column-first array with
Mrows andNcolumns.bits – The vector that contains the ‘M’ bits to use for swapping (if bits[i]=True, the i-th rows will be swapped).
-
template<typename Share>
static void swap(Vector<Share> &x_vec, Vector<Share> &y_vec, const Vector<Share> &bits) Same as BSharedVector::swap() but works with plaintext data. Used for testing.
Swaps rows of two
MxNarrays in place using the providedbits.- Template Parameters:
Share – Share data type.
- Parameters:
x_vec – The left column-first array with
Mrows andNcolumns.y_vec – The right column-first array with
Mrows andNcolumns.bits – The vector that contains the ‘M’ bits to use for swapping (if bits[i]=True, the i-th rows will be swapped).
-
template<typename T>
struct is_ntl_gf2e : public std::false_type - #include <mapping_access_vector.h>
-
template<>
struct is_ntl_gf2e<NTL::GF2E> : public std::false_type, public std::true_type - #include <mapping_access_vector.h>
-
template<typename T>
class Vector - #include <class_access_vector.h>
-
namespace service
-
template<typename T>
Defines
-
define_binary_vector_op(_op_)
Defines a dummy binary operator.
-
define_unary_vector_op(_op_)
Defines a dummy unary operator.
-
define_binary_vector_element_op(_op_)
Defines a dummy binary operator between a Vector and some other type.
-
define_binary_vector_assignment_op(_op_)
Defines a dummy binary assignment operator.
-
namespace cdough
Functions
-
template<typename Share>
static Vector<Share> compare_rows(const std::vector<Vector<Share>*> &x_vec, const std::vector<Vector<Share>*> &y_vec, const std::vector<bool> &inverse) Return an arbitrary row as a dummy Vector.
- Template Parameters:
Share –
- Parameters:
x_vec –
y_vec –
inverse –
- Returns:
Vector<Share>
-
template<typename T>
class Vector - #include <class_access_vector.h>
-
namespace service
-
template<typename Share>
-
namespace NTL
Functions
-
inline GF2E operator&(const GF2E &lhs, const GF2E&)
-
inline GF2E operator|(const GF2E &lhs, const GF2E&)
-
inline GF2E operator^(const GF2E &lhs, const GF2E&)
-
inline GF2E operator&(const GF2E &lhs, long)
-
inline GF2E operator|(const GF2E &lhs, long)
-
inline GF2E operator^(const GF2E &lhs, long)
-
inline GF2E &operator&=(GF2E &lhs, const GF2E&)
-
inline GF2E &operator|=(GF2E &lhs, const GF2E&)
-
inline GF2E &operator^=(GF2E &lhs, const GF2E&)
-
inline GF2E &operator&=(GF2E &lhs, long)
-
inline GF2E &operator|=(GF2E &lhs, long)
-
inline GF2E &operator^=(GF2E &lhs, long)
-
inline GF2E operator~(const GF2E &value)
-
inline bool operator!(const GF2E &value)
-
inline GF2E operator%(const GF2E &lhs, const GF2E&)
-
inline GF2E operator%(const GF2E &lhs, long)
-
inline GF2E &operator%=(GF2E &lhs, const GF2E&)
-
inline GF2E &operator%=(GF2E &lhs, long)
-
inline GF2E operator>>(const GF2E &lhs, long)
-
inline GF2E operator<<(const GF2E &lhs, long)
-
inline GF2E &operator>>=(GF2E &lhs, long)
-
inline GF2E &operator<<=(GF2E &lhs, long)
-
inline bool operator>(const GF2E&, const GF2E&)
-
inline bool operator>=(const GF2E&, const GF2E&)
-
inline bool operator<(const GF2E&, const GF2E&)
-
inline bool operator<=(const GF2E&, const GF2E&)
-
inline bool operator>(const GF2E&, long)
-
inline bool operator>=(const GF2E&, long)
-
inline bool operator<(const GF2E&, long)
-
inline bool operator<=(const GF2E&, long)
-
inline GF2E operator&(const GF2E &lhs, const GF2E&)
Matrix
-
namespace cdough
-
namespace matrix
-
namespace matrix
Defines
-
define_binary_matrix_matrix_op(_op_)
-
define_binary_matrix_element_op(_op_)
-
define_binary_matrix_matrix_inplace_op(_op_)
-
define_binary_matrix_element_inplace_op(_op_)
-
namespace cdough
-
namespace matrix
-
namespace hybrid
Typedefs
-
using HeightWidth = std::pair<size_t, size_t>
-
template<typename T, template<typename> class V, template<typename, template<typename> class> class ImplementedMatrix>
class Matrix - #include <matrix.h>
Matrix class.
This class provides the common Matrix interface between both secure and plaintext matrices. The Matrix class is a wrapper around a 1D data abstraction. The matrix utilizes its computational capabilities from the underlying vector type.
Note: we should not use for-loop functions in this class because the secure matrix inherits from it.
- Template Parameters:
T – Data type
V – Vector type
ImplementedMatrix – The derived matrix class
Public Functions
-
inline Matrix(const V<T> &data, size_t rows, size_t cols, const bool &columnWise = false)
Construct a new Matrix object.
- Parameters:
data – 1D data vector
rows – Number of rows
cols – Number of columns
columnWise – Whether the data is stored in column-wise order
-
inline virtual ~Matrix()
-
inline size_t rows() const
Get number of rows.
- Returns:
size_t Number of rows
-
inline size_t cols() const
Get number of columns.
- Returns:
size_t Number of columns
-
inline const V<T> &data() const
Get underlying data vector (const)
- Returns:
const V<T>& for the Underlying data vector
-
inline bool isColumnWise() const
Check if the matrix is stored in column-wise order.
- Returns:
true if the matrix is column-wise, false otherwise
-
inline ImplementedMatrix<T, V> matrixRightMultiplyWithColumnMatrixVectorized(const ImplementedMatrix<T, V> &rhs) const
Vectorized Matrix right multiplication with a column matrix. Expects the left-hand side matrix to be in row-major order. Expects the right-hand side matrix to be in column-major order.
- Parameters:
rhs – The right-hand side column matrix.
- Returns:
ImplementedMatrix<T, V> The resulting matrix
-
inline ImplementedMatrix<T, V> matrixRightMultiplyVectorized(const ImplementedMatrix<T, V> &rhs)
Vectorized matrix right multiplication with a matrix. Expects the left-hand side matrix to be in row-major order.
- Parameters:
rhs – The right-hand side matrix.
- Returns:
ImplementedMatrix<T, V> The resulting matrix
-
inline ImplementedMatrix<T, V> conv2DVectorized(const ImplementedMatrix<T, V> &rhs, size_t instancesCount, const HeightWidth &filterSize, const HeightWidth &stride, const HeightWidth &padding) const
Secure 2D convolution. Expects the input matrix to be in row-major order. Expects the filter matrix to be in row-major order. Assumes input to has 1 channel (equivalent to many but interleaved). Output has multiple channels.
Input layout: The input consists of mutiple instances concatenated after each other. Hence, the input size = instancesCount * inputHeight * inputWidth. Each instance has multiple channels interleaved per spatial location. For example, for 2x2 input with 2 channels: [ch1(0,0), ch2(0,0), ch1(0,1), ch2(0,1), ch1(1,0), ch2(1,0), ch1(1,1), ch2(1,1)]
Filter layout: the filter is expected to have multiple channels. Hence, the filter size = channels * filterHeight * filterWidth. For example, the the physical layout for 2x2 filter with 2 channels [f_ch1(0,0), f_ch2(0,0), f_ch1(1,0), f_ch2(1,0), g_ch1(0,1), g_ch2(0,1), g_ch1(1,1), g_ch2(1,1)]
Output layout: (same layout as input but different height and width). The output consists of mutiple instances concatenated after each other. Hence, the output size = instancesCount * outputHeight * outputWidth * channels. Each instance has multiple channels interleaved per spatial location. For example, for 2x2 output with 2 channels: [ch1(0,0), ch2(0,0), ch1(0,1), ch2(0,1), ch1(1,0), ch2(1,0), ch1(1,1), ch2(1,1)]
- Parameters:
rhs – The filter matrix.
instancesCount – Number of instances in the input batch.
filterSize – Height and width of the filter.
stride – Height and width of the stride.
padding – Height and width of the padding.
- Returns:
ImplementedMatrix<T, V> The resulting matrix
-
inline ImplementedMatrix<T, V> fullyConnectedVectorized(const ImplementedMatrix<T, V> &weights, const ImplementedMatrix<T, V> &bias) const
Vectorized fully connected layer. Expects the input matrix to be in row-major order. Expects the weights matrix to be in column-major order. Expects the bias matrix to be in row-major order.
It performs matrix multiplication between input and weights, then adds the bias to each instance in the output. res = input.matMult(weights) + bias
- Parameters:
weights – The weights matrix.
bias – The bias matrix.
- Returns:
ImplementedMatrix<T, V> The resulting matrix
-
inline ImplementedMatrix<T, V> avgPoolingVectorized(size_t instancesCount, size_t channelsNum, const HeightWidth &inputSize, const HeightWidth &filterSize, const HeightWidth &stride, const HeightWidth &padding) const
Average Pooling, vectorized implementation.
Expects the input matrix to be in row-major order.
Input layout: The input consists of mutiple instances concatenated after each other. Hence, the input size = instancesCount * inputHeight * inputWidth. Each instance has multiple channels interleaved per spatial location.
For example, for 2x2 input with 2 channels: [ch1(0,0), ch2(0,0), ch1(0,1), ch2(0,1), ch1(1,0), ch2(1,0), ch1(1,1), ch2(1,1)]
- Parameters:
instancesCount – Number of instances in the input batch.
channelsNum – Number of channels in the input.
inputSize – Height and width of each input channel.
filterSize – Height and width of the pooling filter.
stride – Height and width of the stride.
padding – Height and width of the padding.
- Returns:
ImplementedMatrix<T, V> The resulting matrix
-
inline ImplementedMatrix<T, V> reLUVectorized() const
Vectorized ReLU activation, vectorized implementation.
- Returns:
ImplementedMatrix<T, V> The resulting matrix after ReLU
-
inline const ImplementedMatrix<T, V> reshapeRef(size_t rows, size_t columns) const
Reshape the matrix to new dimensions (rows, columns) It does not change the underlying data or create a copy. It changes the dimensions only. It returns a new matrix object referencing the same data memory location.
- Parameters:
rows – New number of rows
columns – New number of columns
- Returns:
ImplementedMatrix<T, V> The reshaped matrix
-
inline ImplementedMatrix<T, V> separateChannels(size_t channels) const
separateChannels vectorized implementation. It takes a matrix where channels are interleaved and make it such that each channel is separated.
Input layout: The input consists of mutiple instances concatenated after each other. {ch1(0,0), ch2(0,0), … chN(0,0), ch1(0,1), ch2(0,1), … chN(0,1), ..}
Output layout: {ch1(0,0), ch1(0,1), … ch1(n,m)}, {ch2(0,0), ch2(0,1), … ch2(n,m)}, … {chN(0,0), chN(0,1), … chN(n,m)}
- Parameters:
channels – Number of channels to separate
- Returns:
ImplementedMatrix<T, V> The resulting matrix
-
inline ImplementedMatrix<T, V> interleaveChannels(size_t channels) const
interleaveChannels vectorized implementation. It takes a matrix where channels are separated and make it such that channels are interleaved.
Input layout: {ch1(0,0), ch1(0,1), … ch1(n,m)}, {ch2(0,0), ch2(0,1), … ch2(n,m)}, … {chN(0,0), chN(0,1), … chN(n,m)}
Output layout: The output consists of mutiple instances concatenated after each other. {ch1(0,0), ch2(0,0), … chN(0,0), ch1(0,1), ch2(0,1), … chN(0,1), ..}
- Parameters:
channels – Number of channels to diffuse
- Returns:
ImplementedMatrix<T, V> The resulting matrix
-
template<typename T2>
inline auto operator+(const ImplementedMatrix<T2, V> &y) const
-
template<typename T2>
inline auto operator-(const ImplementedMatrix<T2, V> &y) const
-
template<typename T2>
inline auto operator*(const ImplementedMatrix<T2, V> &y) const
-
template<typename T2>
inline auto operator>(const ImplementedMatrix<T2, V> &y) const
-
template<typename T2>
inline auto operator<(const ImplementedMatrix<T2, V> &y) const
-
template<typename T2>
inline auto operator>=(const ImplementedMatrix<T2, V> &y) const
-
template<typename T2>
inline auto operator<=(const ImplementedMatrix<T2, V> &y) const
-
template<typename T2>
inline auto operator==(const ImplementedMatrix<T2, V> &y) const
-
template<typename T2>
inline auto operator!=(const ImplementedMatrix<T2, V> &y) const
-
template<typename T2>
inline auto &operator+=(const ImplementedMatrix<T2, V> &y)
-
template<typename T2>
inline auto &operator-=(const ImplementedMatrix<T2, V> &y)
-
template<typename T2>
inline auto &operator*=(const ImplementedMatrix<T2, V> &y)
-
using HeightWidth = std::pair<size_t, size_t>
-
namespace hybrid
-
namespace matrix
-
namespace cdough
-
namespace matrix
-
namespace hybrid
-
template<typename T, template<typename> class V>
class PlainMatrix : public cdough::matrix::hybrid::Matrix<T, V, PlainMatrix> - #include <plain_matrix.h>
Plain Matrix class.
This class implements a plaintext matrix.
- Template Parameters:
T – Data type
V – Vector type
Public Functions
-
inline PlainMatrix(const V<T> &data, size_t rows, size_t cols, const bool &columnWise = false)
Construct a new Plain Matrix object.
- Parameters:
data – 1D data vector
rows – Number of rows
cols – Number of columns
columnWise – Whether the data is stored in column-wise order
-
inline PlainMatrix(size_t rows, size_t cols, const bool &columnWise = false)
Construct a new Plain Matrix object.
- Parameters:
rows – Number of rows
cols – Number of columns
columnWise – Whether the data is stored in column-wise order
-
inline virtual ~PlainMatrix()
-
inline auto same_as(const PlainMatrix &other) const
Check if two matrices are the same.
- Parameters:
other – The other matrix to compare with
- Returns:
true if the matrices are the same, false otherwise
-
inline void print() const
Prints the matrix.
Public Static Functions
-
template<typename Generator>
static inline PlainMatrix RandomMatrix(Generator &generator, size_t rows, size_t cols, const T &mod = std::numeric_limits<T>::max()) Generate a random plain matrix, output can be modulo
modif specified.- Template Parameters:
Generator – Randomness generator type
- Parameters:
generator – Randomness generator
rows – Number of rows
cols – Number of columns
mod – Modulus for the random values
- Returns:
PlainMatrix<T, V> The generated random matrix
-
template<typename Generator>
static inline PlainMatrix RandomColumnMatrix(Generator &generator, size_t rows, size_t cols, const T &mod = std::numeric_limits<T>::max()) Generate a random plain column-wise matrix.
- Template Parameters:
Generator – Randomness generator type
- Parameters:
generator – Randomness generator
rows – Number of rows
cols – Number of columns
mod – Modulus for the random values
- Returns:
PlainMatrix<T, V> The generated random column-wise matrix
-
template<typename T, template<typename> class V>
-
namespace hybrid
-
namespace matrix
-
namespace cdough
-
namespace matrix
-
namespace hybrid
-
template<typename T, template<typename> class V>
class SecureMatrix : public cdough::matrix::hybrid::Matrix<T, V, SecureMatrix> - #include <secure_matrix.h>
Secure Matrix class.
This class implements a secure matrix.
- Template Parameters:
T – Data type
V – Vector type
Public Functions
-
inline SecureMatrix(const V<T> &data, size_t rows, size_t cols, const bool &columnWise = false)
Construct a new Secure Matrix object.
- Parameters:
data – 1D data vector
rows – Number of rows
cols – Number of columns
columnWise – Whether the data is stored in column-wise order
-
inline virtual ~SecureMatrix()
-
inline void setPrecision(size_t precision)
Set the precision for fixed-point representation.
- Parameters:
precision – Number of bits for the fractional part
-
inline auto open() const
Open the secure matrix and return a plaintext matrix.
- Returns:
PlainMatrix<T, V> The opened plaintext matrix
-
template<typename T, template<typename> class V>
-
namespace hybrid
-
namespace matrix