Skip to content

openfheorg/openfhe-numpy

Repository files navigation

OpenFHE-NumPy

License Python Versions OpenFHE Version

OpenFHE-NumPy is a NumPy-like API for homomorphic encryption operations, built on top of OpenFHE. This library enables data scientists and machine learning practitioners to perform computations on encrypted data using familiar NumPy syntax.

Table of Contents

Project Structure

OpenFHE-NumPy is organized as a hybrid C++/Python project with the following structure:

openfhe-numpy/
├── config/              # Configuration files
├── docs/                # Documentation
├── examples/            # Python examples
├── openfhe_numpy/       # Main Python package
│   ├── cpp/             # C++ implementation
│   ├── operations/      # Matrix operations
│   ├── tensor/          # Tensor implementations
│   └── utils/           # Utility functions
├── tests/               # Test suite
└── CMakeLists.txt       # Build configuration

Installation

Prerequisites

  • C++ compiler: Supporting C++17 standard
  • CMake: Version 3.16 or newer
  • Python: Version 3.8 or newer
  • NumPy: Any version
  • OpenFHE: Any version
  • OpenFHE Python: Any version

Installing from Source

Before building, make sure you have the following dependencies installed:

We recommend following OpenFHE C++ and OpenFHE Python installation instructions first (which covers Linux, Windows and MacOS) and then getting back to this repo. If the some package cannot be found when running a Python example (occurs only for some environments), check the PYTHONPATH (OpenFHE Python) environment variable and the LD_LIBRARY_PATH (OpenFHE libraries). This ensures that the packages can be correctly located and imported.

# Clone the repository
git clone https://github.com/openfheorg/openfhe-numpy.git
cd openfhe-numpy

# Create build directory
mkdir build && cd build

# Configure with CMake
cmake ..

# Build the package
make

# Install
sudo make install

Installing using pip (for Ubuntu)

On Ubuntu, openfhe_numpy can be installed using pip. All available releases are listed at Python Package Index OpenFHE-Numpy Release History. Find the release for your version of Ubuntu and run

pip install openfhe_numpy==<openfhe_package_version>

Once installed, any python example at https://github.com/openfheorg/openfhe-numpy/tree/main/examples/python can be executed.

Note that Ubuntu LTS 20.04, 22.04, and 24.04 are currently supported. pip uninstall can be used to uninstall the openfhe package.

Running Tests

Run tests with unittest. See the testing readme for detailed instuctions.

Code Examples

import numpy as np
import openfhe_numpy as onp
from openfhe import *

# Initialize CKKS context
params = CCParamsCKKSRNS()
params.SetMultiplicativeDepth(7)
params.SetScalingModSize(59)
params.SetFirstModSize(60)
params.SetScalingTechnique(FIXEDAUTO)
params.SetSecretKeyDist(UNIFORM_TERNARY)

cc = GenCryptoContext(params)
cc.Enable(PKESchemeFeature.PKE)
cc.Enable(PKESchemeFeature.LEVELEDSHE)
cc.Enable(PKESchemeFeature.ADVANCEDSHE)

# Generate keys
keys = cc.KeyGen()
cc.EvalMultKeyGen(keys.secretKey)
cc.EvalSumKeyGen(keys.secretKey)

# Create matrix and encrypt it
A = np.array([[1, 2], [3, 4]])

ring_dim = cc.GetRingDimension()
total_slots = ring_dim // 2

# Encrypt with OpenFHE-NumPy
tensor_A = onp.array(
        cc=cc,
        data=A,
        batch_size=batch_size,
        order=onp.ROW_MAJOR,
        fhe_type="C",
        mode="zero",
        public_key=keys.publicKey,
    )


# Generate keys
onp.EvalSquareMatMultRotateKeyGen(keys.secretKey, tensor_A.ncols)

# Perform encrypted operations
tensor_product = tensor_A @ tensor_A  # Matrix multiplication
tensor_sum = onp.add(tensor_A, tensor_A)  # Element-wise addition

# Decrypt results
decrypted_product = tensor_product.decrypt(keys.secretKey, unpack_type="original")
decrypted_sum = tensor_sum.decrypt(keys.secretKey, unpack_type="original")

print("Result of A @ A:")
print(decrypted_product)

print("Result of A + A:")
print(decrypted_sum)

Available Operations

OpenFHE-NumPy currently supports the following operations:

Operation Description Example
add Element-wise addition onp.add(a, b) or a + b
subtract Element-wise subtraction onp.subtract(a, b) or a - b
multiply Element-wise multiplication onp.multiply(a, b) or a * b
matmul Matrix multiplication onp.matmul(a, b) or a @ b
transpose Matrix transposition onp.transpose(a)
cumulative_sum Cumulative sum along axis onp.cumulative_sum(a, axis)
power Element-wise power onp.power(a, exp)
dot Dot product onp.dot(a, b)
sum Sum along axis onp.sum(a, axis)

Current Limitations

In the current version, the OpenFHE-NumPy package supports operations on single-ciphertext vectors/matrices, where each encrypted array variable (which has type CTArray or PTArray) contains only a single encoding vector.

For example, we can consider a matrix:

1 2 3
4 5 6
7 8 9

As an encoding vector of the form: 1 2 3 0 4 5 6 0 7 8 9 0

The size of the encoded vector must be smaller than the number of available plaintext slots. Certain operations, such as matrix–vector multiplication, may require the ciphertext vector to be duplicated. In such cases, users should ensure that a sufficient number of slots are available for the function to execute correctly. We plan to release a future version with support for block ciphertexts, which will remove this limitation in the future.

Documentation

For detailed documentation on the API, please visit our documentation site.

Examples

We provide several examples showcasing the library's functionality:

Contributing

OpenFHE Development - Contributing Guide

License

OpenFHE-NumPy is licensed under the BSD 2-Clause License. See the LICENSE file for details.


OpenFHE-NumPy is an independent project and is not officially affiliated with NumPy.

About

Numpy-like matrix arithmetic library based on OpenFHE

Resources

License

Stars

Watchers

Forks

Packages

No packages published