Skip to content

Matrix algebra

concrete_fhe_toolkit.ml.matrix

Encrypted matrix operations and linear algebra.

matrix_transpose

matrix_transpose(matrix: Union[ndarray, List[List[Any]]]) -> Union[np.ndarray, List[List[Any]]]

Transpose an encrypted 2D matrix (swap rows and columns).

Parameters:

Name Type Description Default
matrix Union[ndarray, List[List[Any]]]

The matrix to transpose.

required

Returns:

Type Description
Union[ndarray, List[List[Any]]]

Union[np.ndarray, List[List[Any]]]: Transposed matrix.

Example
from concrete_fhe_toolkit.ml.matrix import matrix_transpose

# Inside an FHE circuit
# A_T = matrix_transpose(enc_matrix_A)
Source code in src/concrete_fhe_toolkit/ml/matrix.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
def matrix_transpose(matrix: Union[np.ndarray, List[List[Any]]]) -> Union[np.ndarray, List[List[Any]]]:
    """Transpose an encrypted 2D matrix (swap rows and columns).

    Args:
        matrix (Union[np.ndarray, List[List[Any]]]): The matrix to transpose.

    Returns:
        Union[np.ndarray, List[List[Any]]]: Transposed matrix.

    Example:
        ```python
        from concrete_fhe_toolkit.ml.matrix import matrix_transpose

        # Inside an FHE circuit
        # A_T = matrix_transpose(enc_matrix_A)
        ```
    """
    _matrix_shape(matrix)
    return np.transpose(_ensure_tensor(matrix))

dot_product

dot_product(array1: Union[ndarray, List[Any]], array2: Union[ndarray, List[Any]]) -> Any

Calculate the dot product of two encrypted arrays (vectors).

This is the fundamental operation for linear layers and convolution.

Parameters:

Name Type Description Default
array1 Union[ndarray, List[Any]]

The first encrypted array.

required
array2 Union[ndarray, List[Any]]

The second encrypted array.

required

Returns:

Name Type Description
Any Any

The scalar dot product.

Example
from concrete_fhe_toolkit.ml.matrix import dot_product

# Inside an FHE circuit
# score = dot_product(enc_weights, enc_features)
Source code in src/concrete_fhe_toolkit/ml/matrix.py
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def dot_product(array1: Union[np.ndarray, List[Any]], array2: Union[np.ndarray, List[Any]]) -> Any:
    """Calculate the dot product of two encrypted arrays (vectors).

    This is the fundamental operation for linear layers and convolution.

    Args:
        array1 (Union[np.ndarray, List[Any]]): The first encrypted array.
        array2 (Union[np.ndarray, List[Any]]): The second encrypted array.

    Returns:
        Any: The scalar dot product.

    Example:
        ```python
        from concrete_fhe_toolkit.ml.matrix import dot_product

        # Inside an FHE circuit
        # score = dot_product(enc_weights, enc_features)
        ```
    """
    return np.dot(array1, array2)

matrix_add

matrix_add(matrix1: Union[ndarray, List[List[Any]]], matrix2: Union[ndarray, List[List[Any]]]) -> Union[np.ndarray, List[List[Any]]]

Perform element-wise addition of two encrypted matrices of the same dimensions.

Parameters:

Name Type Description Default
matrix1 Union[ndarray, List[List[Any]]]

The first matrix.

required
matrix2 Union[ndarray, List[List[Any]]]

The second matrix.

required

Returns:

Type Description
Union[ndarray, List[List[Any]]]

Union[np.ndarray, List[List[Any]]]: The resulting matrix.

Example
from concrete_fhe_toolkit.ml.matrix import matrix_add

# Inside an FHE circuit
# C = matrix_add(enc_matrix_A, enc_matrix_B)
Source code in src/concrete_fhe_toolkit/ml/matrix.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def matrix_add(matrix1: Union[np.ndarray, List[List[Any]]], matrix2: Union[np.ndarray, List[List[Any]]]) -> Union[np.ndarray, List[List[Any]]]:
    """Perform element-wise addition of two encrypted matrices of the same dimensions.

    Args:
        matrix1 (Union[np.ndarray, List[List[Any]]]): The first matrix.
        matrix2 (Union[np.ndarray, List[List[Any]]]): The second matrix.

    Returns:
        Union[np.ndarray, List[List[Any]]]: The resulting matrix.

    Example:
        ```python
        from concrete_fhe_toolkit.ml.matrix import matrix_add

        # Inside an FHE circuit
        # C = matrix_add(enc_matrix_A, enc_matrix_B)
        ```
    """
    _same_matrix_shape(matrix1, matrix2)
    return np.add(matrix1, matrix2)

matrix_subtract

matrix_subtract(matrix1: Union[ndarray, List[List[Any]]], matrix2: Union[ndarray, List[List[Any]]]) -> Union[np.ndarray, List[List[Any]]]

Perform element-wise subtraction of two encrypted matrices of the same dimensions.

Parameters:

Name Type Description Default
matrix1 Union[ndarray, List[List[Any]]]

The matrix to subtract from.

required
matrix2 Union[ndarray, List[List[Any]]]

The matrix to subtract.

required

Returns:

Type Description
Union[ndarray, List[List[Any]]]

Union[np.ndarray, List[List[Any]]]: The resulting matrix.

Example
from concrete_fhe_toolkit.ml.matrix import matrix_subtract

# Inside an FHE circuit
# C = matrix_subtract(enc_matrix_A, enc_matrix_B)
Source code in src/concrete_fhe_toolkit/ml/matrix.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
def matrix_subtract(matrix1: Union[np.ndarray, List[List[Any]]], matrix2: Union[np.ndarray, List[List[Any]]]) -> Union[np.ndarray, List[List[Any]]]:
    """Perform element-wise subtraction of two encrypted matrices of the same dimensions.

    Args:
        matrix1 (Union[np.ndarray, List[List[Any]]]): The matrix to subtract from.
        matrix2 (Union[np.ndarray, List[List[Any]]]): The matrix to subtract.

    Returns:
        Union[np.ndarray, List[List[Any]]]: The resulting matrix.

    Example:
        ```python
        from concrete_fhe_toolkit.ml.matrix import matrix_subtract

        # Inside an FHE circuit
        # C = matrix_subtract(enc_matrix_A, enc_matrix_B)
        ```
    """
    _same_matrix_shape(matrix1, matrix2)
    return np.subtract(matrix1, matrix2)

matrix_multiply

matrix_multiply(matrix1: Union[ndarray, List[List[Any]]], matrix2: Union[ndarray, List[List[Any]]]) -> Union[np.ndarray, List[List[Any]]]

Perform matrix multiplication (dot product) of two encrypted matrices.

Note: Matrix multiplication involves many multiplications and additions, so the resulting FHE circuit may be deep. Use with appropriately scaled values.

Parameters:

Name Type Description Default
matrix1 Union[ndarray, List[List[Any]]]

The left-hand side matrix.

required
matrix2 Union[ndarray, List[List[Any]]]

The right-hand side matrix.

required

Returns:

Type Description
Union[ndarray, List[List[Any]]]

Union[np.ndarray, List[List[Any]]]: The multiplied matrix.

Example
from concrete_fhe_toolkit.ml.matrix import matrix_multiply

# Inside an FHE circuit
# C = matrix_multiply(enc_matrix_A, enc_matrix_B)
Source code in src/concrete_fhe_toolkit/ml/matrix.py
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
def matrix_multiply(matrix1: Union[np.ndarray, List[List[Any]]], matrix2: Union[np.ndarray, List[List[Any]]]) -> Union[np.ndarray, List[List[Any]]]:
    """Perform matrix multiplication (dot product) of two encrypted matrices.

    Note: Matrix multiplication involves many multiplications and additions, 
    so the resulting FHE circuit may be deep. Use with appropriately scaled values.

    Args:
        matrix1 (Union[np.ndarray, List[List[Any]]]): The left-hand side matrix.
        matrix2 (Union[np.ndarray, List[List[Any]]]): The right-hand side matrix.

    Returns:
        Union[np.ndarray, List[List[Any]]]: The multiplied matrix.

    Example:
        ```python
        from concrete_fhe_toolkit.ml.matrix import matrix_multiply

        # Inside an FHE circuit
        # C = matrix_multiply(enc_matrix_A, enc_matrix_B)
        ```
    """
    return np.matmul(matrix1, matrix2)

matrix_elementwise_multiply

matrix_elementwise_multiply(matrix1: Union[ndarray, List[List[Any]]], matrix2: Union[ndarray, List[List[Any]]]) -> Union[np.ndarray, List[List[Any]]]

Perform Hadamard (element-wise) multiplication of two encrypted matrices.

Parameters:

Name Type Description Default
matrix1 Union[ndarray, List[List[Any]]]

The first matrix.

required
matrix2 Union[ndarray, List[List[Any]]]

The second matrix.

required

Returns:

Type Description
Union[ndarray, List[List[Any]]]

Union[np.ndarray, List[List[Any]]]: The resulting matrix.

Example
from concrete_fhe_toolkit.ml.matrix import matrix_elementwise_multiply

# Inside an FHE circuit
# C = matrix_elementwise_multiply(enc_matrix_A, enc_matrix_B)
Source code in src/concrete_fhe_toolkit/ml/matrix.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def matrix_elementwise_multiply(matrix1: Union[np.ndarray, List[List[Any]]], matrix2: Union[np.ndarray, List[List[Any]]]) -> Union[np.ndarray, List[List[Any]]]:
    """Perform Hadamard (element-wise) multiplication of two encrypted matrices.

    Args:
        matrix1 (Union[np.ndarray, List[List[Any]]]): The first matrix.
        matrix2 (Union[np.ndarray, List[List[Any]]]): The second matrix.

    Returns:
        Union[np.ndarray, List[List[Any]]]: The resulting matrix.

    Example:
        ```python
        from concrete_fhe_toolkit.ml.matrix import matrix_elementwise_multiply

        # Inside an FHE circuit
        # C = matrix_elementwise_multiply(enc_matrix_A, enc_matrix_B)
        ```
    """
    _same_matrix_shape(matrix1, matrix2)
    return np.multiply(matrix1, matrix2)

matrix_vector_multiply

matrix_vector_multiply(matrix: Union[ndarray, List[List[Any]]], array: Union[ndarray, List[Any]]) -> Union[np.ndarray, List[Any]]

Multiply an encrypted matrix by an encrypted vector.

Often used to evaluate a linear layer: output = W * input.

Parameters:

Name Type Description Default
matrix Union[ndarray, List[List[Any]]]

The encrypted matrix.

required
array Union[ndarray, List[Any]]

The encrypted array or list of elements.

required

Returns:

Type Description
Union[ndarray, List[Any]]

Union[np.ndarray, List[Any]]: The resulting vector.

Example
from concrete_fhe_toolkit.ml.matrix import matrix_vector_multiply

# Inside an FHE circuit
# output_vec = matrix_vector_multiply(enc_weight_matrix, enc_input_vec)
Source code in src/concrete_fhe_toolkit/ml/matrix.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
def matrix_vector_multiply(matrix: Union[np.ndarray, List[List[Any]]], array: Union[np.ndarray, List[Any]]) -> Union[np.ndarray, List[Any]]:
    """Multiply an encrypted matrix by an encrypted vector.

    Often used to evaluate a linear layer: output = W * input.

    Args:
        matrix (Union[np.ndarray, List[List[Any]]]): The encrypted matrix.
        array (Union[np.ndarray, List[Any]]): The encrypted array or list of elements.

    Returns:
        Union[np.ndarray, List[Any]]: The resulting vector.

    Example:
        ```python
        from concrete_fhe_toolkit.ml.matrix import matrix_vector_multiply

        # Inside an FHE circuit
        # output_vec = matrix_vector_multiply(enc_weight_matrix, enc_input_vec)
        ```
    """
    return np.matmul(matrix, array)

matrix_exp

matrix_exp(matrix: Union[ndarray, List[List[Any]]], exponent: int) -> Union[np.ndarray, List[List[Any]]]

Calculate the power of an encrypted square matrix.

This uses the highly efficient Square-and-Multiply (Binary Exponentiation) algorithm to reduce the number of FHE matrix multiplications required.

Parameters:

Name Type Description Default
matrix Union[ndarray, List[List[Any]]]

The square encrypted matrix.

required
exponent int

The public integer exponent to raise the matrix to.

required

Returns:

Type Description
Union[ndarray, List[List[Any]]]

The exponentiated encrypted matrix.

Raises:

Type Description
ValueError

If the matrix is not square or the exponent is negative.

Example
from concrete_fhe_toolkit.ml.matrix import matrix_exp

# Inside an FHE circuit
# M_cubed = matrix_exp(enc_matrix, 3)
Source code in src/concrete_fhe_toolkit/ml/matrix.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
def matrix_exp(matrix: Union[np.ndarray, List[List[Any]]], exponent: int) -> Union[np.ndarray, List[List[Any]]]:
    """Calculate the power of an encrypted square matrix.

    This uses the highly efficient Square-and-Multiply (Binary Exponentiation)
    algorithm to reduce the number of FHE matrix multiplications required.

    Args:
        matrix: The square encrypted matrix.
        exponent: The public integer exponent to raise the matrix to.

    Returns:
        The exponentiated encrypted matrix.

    Raises:
        ValueError: If the matrix is not square or the exponent is negative.

    Example:
        ```python
        from concrete_fhe_toolkit.ml.matrix import matrix_exp

        # Inside an FHE circuit
        # M_cubed = matrix_exp(enc_matrix, 3)
        ```
    """
    size, columns = _matrix_shape(matrix)
    if size == 0 or columns != size:
        raise ValueError("Matrix should be a nonempty square matrix for exponentiation")
    exponent = validate_integer("exponent", exponent, minimum=0)
    result: Any = np.identity(size, dtype=np.int64)
    base = _ensure_tensor(matrix)
    while exponent:
        if exponent % 2:
            result = matrix_multiply(result, base)
        exponent //= 2
        if exponent:
            base = matrix_multiply(base, base)
    return result

covariance_matrix

covariance_matrix(matrix: Union[ndarray, List[List[Any]]]) -> Union[np.ndarray, List[List[Any]]]

Calculate the covariance matrix of an encrypted 2D dataset.

The dataset should have observations as rows and features as columns. Returns the sample covariance (denominator N - 1), floored to integers. Means are not rounded: all arithmetic remains integer until the final division.

Parameters:

Name Type Description Default
matrix Union[ndarray, List[List[Any]]]

The encrypted 2D dataset (N observations x M features).

required

Returns:

Type Description
Union[ndarray, List[List[Any]]]

The M x M encrypted covariance matrix.

Example
from concrete_fhe_toolkit.ml.matrix import covariance_matrix

# Inside an FHE circuit
# cov = covariance_matrix(enc_dataset)
Source code in src/concrete_fhe_toolkit/ml/matrix.py
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
def covariance_matrix(matrix: Union[np.ndarray, List[List[Any]]]) -> Union[np.ndarray, List[List[Any]]]:
    """Calculate the covariance matrix of an encrypted 2D dataset.

    The dataset should have observations as rows and features as columns.
    Returns the sample covariance (denominator N - 1), floored to integers.
    Means are not rounded: all arithmetic remains integer until the final division.

    Args:
        matrix: The encrypted 2D dataset (N observations x M features).

    Returns:
        The M x M encrypted covariance matrix.

    Example:
        ```python
        from concrete_fhe_toolkit.ml.matrix import covariance_matrix

        # Inside an FHE circuit
        # cov = covariance_matrix(enc_dataset)
        ```
    """
    n_samples, n_features = _matrix_shape(matrix)
    if n_samples < 2 or n_features == 0:
        raise ValueError("covariance requires at least two samples and one feature")
    data = fhe.array(matrix)
    totals = np.sum(data, axis=0)
    denominator = n_samples * (n_samples - 1)
    # Compute exact sample covariance before the single final floor division.
    # n * sum(x*y) - sum(x)*sum(y) avoids rounding the means prematurely.
    products = np.reshape(data, (n_samples, n_features, 1)) * np.reshape(
        data, (n_samples, 1, n_features)
    )
    numerators = n_samples * np.sum(products, axis=0) - np.reshape(
        totals, (n_features, 1)
    ) * np.reshape(totals, (1, n_features))
    # Tensor arithmetic keeps diagonal and off-diagonal entries at a common
    # signed integer width in Concrete, including tiny covariances.
    covariance = numerators // denominator
    return covariance

matrix_flatten

matrix_flatten(matrix: Union[ndarray, List[List[Any]]]) -> Union[np.ndarray, List[Any]]

Flatten a 2D encrypted matrix into a 1D encrypted array.

Parameters:

Name Type Description Default
matrix Union[ndarray, List[List[Any]]]

The 2D encrypted matrix.

required

Returns:

Type Description
Union[ndarray, List[Any]]

Union[np.ndarray, List[Any]]: The 1D flattened array.

Example
from concrete_fhe_toolkit.ml.matrix import matrix_flatten

# Inside an FHE circuit
# vec = matrix_flatten(enc_matrix)
Source code in src/concrete_fhe_toolkit/ml/matrix.py
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
def matrix_flatten(matrix: Union[np.ndarray, List[List[Any]]]) -> Union[np.ndarray, List[Any]]: 
    """Flatten a 2D encrypted matrix into a 1D encrypted array.

    Args:
        matrix (Union[np.ndarray, List[List[Any]]]): The 2D encrypted matrix.

    Returns:
        Union[np.ndarray, List[Any]]: The 1D flattened array.

    Example:
        ```python
        from concrete_fhe_toolkit.ml.matrix import matrix_flatten

        # Inside an FHE circuit
        # vec = matrix_flatten(enc_matrix)
        ```
    """
    return _ensure_tensor(matrix).flatten()       

tensor_flatten

tensor_flatten(tensor: Union[ndarray, List[List[List[Any]]]]) -> Union[np.ndarray, List[Any]]

Flatten a 3D encrypted tensor into a 1D encrypted array.

Parameters:

Name Type Description Default
tensor Union[ndarray, List[List[List[Any]]]]

The 3D encrypted tensor.

required

Returns:

Type Description
Union[ndarray, List[Any]]

Union[np.ndarray, List[Any]]: The 1D flattened array.

Example
from concrete_fhe_toolkit.ml.matrix import tensor_flatten

# Inside an FHE circuit
# vec = tensor_flatten(enc_3d_tensor)
Source code in src/concrete_fhe_toolkit/ml/matrix.py
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
def tensor_flatten(tensor: Union[np.ndarray, List[List[List[Any]]]]) -> Union[np.ndarray, List[Any]]:
    """Flatten a 3D encrypted tensor into a 1D encrypted array.

    Args:
        tensor (Union[np.ndarray, List[List[List[Any]]]]): The 3D encrypted tensor.

    Returns:
        Union[np.ndarray, List[Any]]: The 1D flattened array.

    Example:
        ```python
        from concrete_fhe_toolkit.ml.matrix import tensor_flatten

        # Inside an FHE circuit
        # vec = tensor_flatten(enc_3d_tensor)
        ```
    """
    return _ensure_tensor(tensor).flatten()