Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
This document explains the essential cryptographic terms and the important concepts of Concrete ML model lifecycle with Fully Homomorphic Encryption (FHE).
Concrete ML is built on top of Concrete, which enables the conversion from NumPy programs into FHE circuits.
With Concrete ML, you can train a model on clear or encrypted data, then deploy it to predict on encrypted inputs. During deployment, data can be pre-processed while being encrypted. Therefore, data stay encrypted during the entire lifecycle of the machine learning model, with some limitations.
Training: A model is trained either using plaintext (non-encrypted) training data, or encrypted training data.
Quantization: Quantization converts inputs, model weights, and all intermediate values of the inference computation to integer equivalents. More information is available here. Concrete ML performs this step in two ways depending on model type:
During training (Quantization Aware Training): by adding quantization layers in the neural network model, weights can be forced to have discrete values and activation quantization parameters are optimized through gradient descent. QAT requires re-training a neural network with these quantization layers.
After training (Post Training Quantization): the floating point neural network is kept as-is and a calibration step determines quantization parameters for each layer. No re-training is necessary and thus, no training data or labels are needed to convert a neural network to FHE using PTQ.
Simulation: Simulation allows you to execute a model that was quantized, to measure its accuracy in FHE, and to determine the modifications required to make it FHE compatible. Simulation is described in more detail here.
Compilation: After quantizing the model and confirming that it has good FHE accuracy through simulation, the model then needs to be compiled using Concrete's FHE Compiler to produce an equivalent FHE circuit. This circuit is represented as an MLIR program consisting of low level cryptographic operations. You can read more about FHE compilation here, MLIR here, and about the low-level Concrete library here.
Inference: The compiled model can then be executed on encrypted data, once the proper keys have been generated. The model can also be deployed to a server and used to run private inference on encrypted inputs.
You can find examples of the model development workflow here.
Pre-processing: Data owners(client) can generate keys to encrypt/decrypt data and store it in a DataFrame for further processing on a server. The server can pre-process such data with pre-compiled circuits, to prepare it for encrypted training or inference.
Client/server model deployment: In a client/server setting, Concrete ML models can be exported to:
Allow the client to generate keys, encrypt, and decrypt.
Provide a compiled model that can run on the server to perform inference on encrypted data.
Key generation: The data owner (client) needs to generate a set of keys:
A private encryption key to encrypt/decrypt their data and results
A public evaluation key for the model's FHE evaluation on the server.
You can find an example of the model deployment workflow here.
Concrete ML and Concrete abstract the details of the underlying cryptography scheme, TFHE. However, understanding some cryptography concepts is still useful:
Encryption and decryption: Encryption converts human-readable information (plaintext) into data (ciphertext) that is unreadable by a human or computer unless with the proper key. Encryption takes plaintext and an encryption key and produces ciphertext, while decryption is the reverse operation.
Encrypted inference: FHE allows third parties to execute a machine learning model on encrypted data. The inference result is also encrypted and can only be decrypted by the key holder.
Key generation: Cryptographic keys are generated using random number generators. Key generation can be time-consuming and produce large keys, but each model used by a client only requires key generation once.
Private encryption key: A private encryption key is a series of bits used within an encryption algorithm for encrypting data so that the corresponding ciphertext appears random.
Public evaluation key: A public evaluation key is used to perform homomorphic operations on encrypted data, typically by a server.
Guaranteed correctness of encrypted computations: To ensure security, TFHE adds random noise to ciphertexts. Depending on the noise parameters, it can cause errors during encrypted data processing. By default, Concrete ML uses parameters that guarantee the correctness of encrypted computations, so the results on encrypted data equals to those of simulations on clear data.
Programmable Boostrapping (PBS) : Programmable Bootstrapping enables the homomorphic evaluation of any function of a ciphertext, with a controlled level of noise. Learn more about PBS in this paper.
For a deeper understanding of the cryptography behind the Concrete stack, refer to the whitepaper on TFHE and Programmable Boostrapping or this series of blogs.
FHE requires all inputs, constants, and intermediate values to be integers of maximum 16 bits. To make machine learning models compatible with FHE, Concrete ML implements some techniques with accuracy considerations:
Quantization: Concrete ML quantizes inputs, outputs, weights, and activations to meet FHE limitations. See the quantization documentation for details.
Accuracy trade-off: Quantization may reduce accuracy, but careful selection of quantization parameters or of the training approach can mitigate this. Concrete ML offers built-in quantized models; users only configure parameters like bit-width. For more details of quantization configurations, see the advanced quantization guide.
Additional methods: Dimensionality reduction and pruning are additional ways to make programs compatible for FHE. See Poisson regression example for dimensionality reduction and built-in neural networks for pruning.
This page explains Concrete ML linear models for both classification and regression. These models are based on scikit-learn linear models.
The following models are supported for training on clear data and predicting on encrypted data. Their API is similar the one of scikit-learn. These models are also compatible with some of scikit-learn's main workflows, such as Pipeline()
and GridSearch()
.
Concrete ML | scikit-learn |
---|---|
In addition to predicting on encrypted data, the following models support training on encrypted data.
| SGDClassifier | SGDClassifier |
The n_bits
parameter controls the bit-width of the inputs and weights of the linear models. Linear models do not use table lookups and thus alllows weight and inputs to be high precision integers.
For models with input dimensions up to 300
, the parameter n_bits
can be set to 8
or more. When the input dimensions are larger, n_bits
must be reduced to 6-7
. In many cases, quantized models can preserve all performance metrics compared to the non-quantized float models from scikit-learn when n_bits
is down to 6
. You should validate accuracy on held-out test sets and adjust n_bits
accordingly.
For optimal results, you can use standard or min-max normalization to achieve a similar distribution of individual features. When there are many one-hot features, consider Principal Component Analysis as a pre-processing stage.
For a more detailed comparison of the impact of such pre-processing, please refer to the logistic regression notebook.
You can convert an already trained scikit-learn linear model to a Concrete ML one by using the from_sklearn_model
method. See the following example.
The following example shows how to train a LogisticRegression model on a simple data-set and then use FHE to perform inference on encrypted data. You can find a more complete example in the LogisticRegression notebook.
The figure below compares the decision boundary of the FHE classifier and a scikit-learn model executed in clear. You can find the complete code in the LogisticRegression notebook.
The overall accuracy scores are identical (93%) between the scikit-learn model (executed in the clear) and the Concrete ML one (executed in FHE). In fact, quantization has little impact on the decision boundaries, as linear models can use large precision numbers when quantizing inputs and weights in Concrete ML. Additionally, as the linear models do not use Programmable Boostrapping, the FHE computations are always exact, irrespective of the PBS error tolerance setting. This ensures that the FHE predictions are always identical to the quantized clear ones.
An alternative to the example above is to train a scikit-learn model in a separate step and then to convert it to Concrete ML.
Zama 5-Question Developer Survey
We want to hear from you! Take 1 minute to share your thoughts and helping us enhance our documentation and libraries. 👉 Click here to participate.
This document illustrate how Concrete ML model and DataFrames are deployed in client/server setting when creating privacy-preserving services in the cloud.
Once compiled to FHE, a Concrete ML model or DataFrame generates machine code that execute prediction, training or pre-processing on encrypted data. During this process, Concrete ML generates the private encryption keys and the pubic evaluation keys.
The overall communications protocol to enable cloud deployment of machine learning services can be summarized in the following diagram:
The steps detailed above are:
Model Deployment: The model developer deploys the compiled machine learning model to the server. This model includes the cryptographic parameters. The server is now ready to provide private inference. Cryptographic parameters and compiled programs for DataFrames are included directly in Concrete ML.
Client request: The client requests the cryptographic parameters (client specs). Once the client receives them from the server, the secret and evaluation keys are generated.
Key exchanges: The client sends the evaluation key to the server. The server is now ready to accept requests from this client. The client sends their encrypted data. Serialized DataFrames include client evaluation keys.
Private inference: The server uses the evaluation key to securely run prediction, training and pre-processing on the user's data and sends back the encrypted result.
Decryption: The client now decrypts the result and can send back new requests.
For more information on how to implement this basic secure inference protocol, refer to the Production Deployment section and to the client/server example. For information on training on encrypted data, see the corresponding section.
Concrete ML is an open-source, privacy-preserving, machine learning framework based on Fully Homomorphic Encryption (FHE).
Learn the basics of Concrete ML, set it up, and make it run with ease.
Start building with Concrete ML by exploring its core features, discovering essential guides, and learning more with user-friendly tutorials.
Access to additional resources and join the Zama community.
Refer to the API, review product architecture, and access additional resources for in-depth explanations while working with Concrete ML.
Ask technical questions and discuss with the community. Our team of experts usually answers within 24 hours in working days.
Collaborate with us to advance the FHE spaces and drive innovation together.
Zama 5-Question Developer Survey
We want to hear from you! Take 1 minute to share your thoughts and helping us enhance our documentation and libraries. 👉 Click here to participate.
Concrete ML is an open source, privacy-preserving, machine learning framework based on Fully Homomorphic Encryption (FHE). It enables data scientists without any prior knowledge of cryptography to perform:
Automatic model conversion: Use familiar APIs from scikit-learn and PyTorch to convert machine learning models to their FHE equivalent. This is applicable for , , and ).
Encrypted data training: directly on encrypted data to maintain privacy.
Encrypted data pre-processing: using a DataFrame paradigm.
This example shows the typical flow of a Concrete ML model:
Training the model: Train the model on unencrypted (plaintext) data using scikit-learn. Since Fully Homomorphic Encryption (FHE) operates over integers, Concrete ML quantizes the model to use only integers during inference.
Compiling the model: Compile the quantized model to an FHE equivalent. Under the hood, the model is first converted to a Concrete Python program and then compiled.
It is also possible to call encryption, model prediction, and decryption functions separately as follows. Executing these steps separately is equivalent to calling predict_proba
on the model instance.
Precision and accuracy: In order to run models in FHE, Concrete ML requires models to be within the precision limit, currently 16-bit integers. Thus, machine learning models must be quantized and it sometimes leads to a loss of accuracy versus the original model that operates on plaintext.
Models availability: Concrete ML currently only supports training on encrypted data for some models, while it supports inference for a large variety of models.
Processing: Concrete currently doesn't support pre-processing model inputs and post-processing model outputs. These processing stages may involve:
Text-to-numerical feature transformation
Dimensionality reduction
KNN or clustering
Featurization
Normalization
The mixing of ensemble models' results.
These issues are currently being addressed, and significant improvements are expected to be released in the near future.
If you have built awesome projects using Concrete ML, feel free to let us know and we'll link to your work!
This document provides guides on how to install Concrete ML using PyPi or Docker.
Before you start, determine your environment:
Hardware platform
Operating System (OS) version
Python version
Depending on your OS/HW, Concrete ML may be installed with Docker or with pip:
OS / HW | Available on Docker | Available on pip |
---|
Version: In the current release, Concrete ML supports only 3.8
, 3.9
, 3.10
and 3.11
versions of python
.
Linux requirement: The Concrete ML Python package requires glibc >= 2.28
. On Linux, you can check your glibc
version by running ldd --version
.
Kaggle installation: Concrete ML can be installed on Kaggle () and on Google Colab.
Most of these limits are shared with the rest of the Concrete stack (namely Concrete Python). Support for more platforms will be added in the future.
Installing Concrete ML using PyPi requires a Linux-based OS or macOS (both x86 and Apple Silicon CPUs are supported).
If you need to install on Windows, use Docker or WSL. On WSL, Concrete ML will work as long as the package is not installed in the `/mnt/c/` directory, which corresponds to the host OS filesystem.
To install Concrete ML from PyPi, run the following:
This will automatically install all dependencies, notably Concrete.
You can install Concrete ML using Docker by either pulling the latest image or a specific version:
This will launch a Concrete ML enabled Jupyter server in Docker that can be accessed directly from a browser.
Alternatively, you can launch a shell in Docker, with or without volumes:
Zama 5-Question Developer Survey
Training on encrypted data: FHE is an encryption technique that allows computing directly on encrypted data, without needing to decrypt it. With FHE, you can build private-by-design applications without compromising on features. Learn more about FHE in or join the community.
Federated learning: Training on encrypted data provides the highest level of privacy but is slower than training on clear data. Federated learning is an alternative approach, where data privacy can be ensured by using a trusted gradient aggregator, coupled with optional differential privacy instead of encryption. Concrete ML can import all types of models: linear, tree-based and neural networks, that are trained using federated learning using the and the function.
Here is a simple example of classification on encrypted data using logistic regression. You can find more examples .
Performing inference: Perform inference on encrypted data. The example above shows encrypted inference in the model-development phase. Alternatively, during in a client/server setting, the client encrypts the data, the server processes it securely, and then the client decrypts the results.
Concrete ML is built on top of Zama's .
Various tutorials are available for and . Several stand-alone demos for use cases can be found in the section.
(we answer in less than 24 hours).
If you encounter any issue during installation on Apple Silicon mac, please visit this .
You can use the image with Docker volumes, . Use the following command:
We want to hear from you! Take 1 minute to share your thoughts and helping us enhance our documentation and libraries. 👉 to participate.
Linux | Yes | Yes |
Windows | Yes | No |
Windows Subsystem for Linux | Yes | Yes |
macOS 11+ (Intel) | Yes | Yes |
macOS 11+ (Apple Silicon: M1, M2, etc.) | Coming soon | Yes |
This document introduces how to construct and perform operations on encrypted DataFrames using Fully Homomorphic Encryption (FHE).
Encrypted DataFrames are a storage format for encrypted tabular data. You can exchange encrypted DataFrames with third parties to collaborate without privacy risks. Potential applications include:
Encrypt storage of tabular data-sets
Joint data analysis efforts between multiple parties
Data preparation steps before machine learning tasks, such as inference or training
Secure outsourcing of data analysis to untrusted third parties
To encrypt a pandas DataFrame, construct a ClientEngine
that manages keys and then call the encrypt_from_pandas
function:
Integer: Integers are supported within a specific range determined by the encryption scheme's quantization parameters. Default range is 1 to 15. 0 being used for the NaN
. Values outside this range will cause a ValueError
to be raised during the pre-processing stage.
Quantized Float: Floating-point numbers are quantized to integers within the supported range. This is achieved by computing a scale and zero point for each column, which are used to map the floating-point numbers to the quantized integer space.
String Enum: String columns are mapped to integers starting from 1. This mapping is stored and later used for de-quantization. If the number of unique strings exceeds 15, a ValueError
is raised.
Before encryption, the data is preprocessed. For example string enums first need to be mapped to integers, and floating point values must be quantized. By default, this mapping is done automatically. However, when two different clients encrypt their data separately, the automatic mappings may differ, possibly due to some missing values in one of the client's DataFrame. Thus the column can not be selected when merging encrypted DataFrames.
The encrypted DataFrame supports user-defined mappings. These schemas are defined as a dictionary where keys represent column names and values contain meta-data about the column. Supported column meta-data are:
string columns: mapping between string values and integers.
float columns: the min/max range that the column values lie in.
Encrypted DataFrame is designed to support a subset of operations that are available for pandas DataFrames. For now, only the merge
operation is supported. More operations will be added in the future releases.
Merge operation allows you to left or right join two DataFrames.
[!NOTE] The merge operation on Encrypted DataFrames can be securely performed on a third-party server, meaning that the server can execute the merge without ever having access to the unencrypted data. The server only requires the encrypted DataFrames.
You can serialize encrypted DataFrame objects to a file format for storage or transfer. When serialized, they contain the encrypted data and public evaluation keys necessary to perform computations.
[!NOTE] Serialized DataFrames do not contain any private encryption keys . The DataFrames can be exchanged with any third-party without any risk.
To save or load an encrypted DataFrame from a file, use the following commands:
During the pre-processing and post-processing stages, the ValueError
can happen in the following situations:
A column contains values outside the allowed range for integers
Too many unique strings
Unsupported data type by Concrete ML
Unsupported data type by the operation attempted
An example workflow where two clients encrypt two DataFrame
objects, perform a merge operation on the server side, and then decrypt the results is available in the notebook encrypted_pandas.ipynb.
While this API offers a new secure way to work on remotely stored and encrypted data, it has some strong limitations at the moment:
Precision of Values: The precision for numerical values is limited to 4 bits.
Supported Operations: The merge
operation is the only one available.
Index Handling: Index values are not preserved; users should move any relevant data from the index to a dedicated new column before encrypting.
Integer Range: The range of integers that can be encrypted is between 1 and 15.
Uniqueness for merge
: The merge
operation requires that the columns to merge on contain unique values. Currently this means that data-frames are limited to 15 rows.
Metadata Security: Column names and the mapping of strings to integers are not encrypted and are sent to the server in clear text.
This document explains how to train SGD Logistic Regression on encrypted data.
Training on encrypted data is done through an FHE program that is generated by Concrete ML, based on the characteristics of the data that are given to the fit
function. Once the FHE program associated with the SGDClassifier
object has fit the encrypted data, it performs specifically to that data's distribution and dimensionality.
When deploying encrypted training services, you need to consider the type of data that future users of your services will train on:
The distribution of the data should match to achieve good accuracy
The dimensionality of the data needs to match since the deployed FHE programs are compiled for a fixed number of dimensions.
See the deployment section for more details.
Training on encrypted data provides the highest level of privacy but is slower than training on clear data. Federated learning is an alternative approach, where data privacy can be ensured by using a trusted gradient aggregator, coupled with optional differential privacy instead of encryption. Concrete ML can import models trained through federated learning using 3rd party tools. All model types are supported - linear, tree-based and neural networks - through the from_sklearn_model
function and the compile_torch_model
function.
The logistic regression training example shows logistic regression training on encrypted data in action.
The following snippet shows how to instantiate a logistic regression model that trains on encrypted data:
To activate encrypted training, simply set fit_encrypted=True
in the constructor. When the value is set, Concrete ML generates an FHE program which, when called through the fit
function, processes encrypted training data, labels and initial weights and outputs trained model weights. If this value is not set, training is performed on clear data using scikit-learn
gradient descent.
Next, to perform the training on encrypted data, call the fit
function with the fhe="execute"
argument:
The max_iter
parameter controls the number of batches that are processed by the training algorithm.
The parameters_range
parameter determines the initialization of the coefficients and the bias of the logistic regression. It is recommended to give values that are close to the min/max of the training data. It is also possible to normalize the training data so that it lies in the range .
The trainable logistic model uses Stochastic Gradient Descent (SGD) and quantizes the data, weights, gradients and the error measure. It currently supports training 6-bit models, including g both the coefficients and the bias.
The SGDClassifier
does not currently support training models with other bit-width values. The execution time to train a model is proportional to the number of features and the number of training examples in the batch. The SGDClassifier
training does not currently support client/server deployment for training.
Once you have tested an SGDClassifier
that trains on encrypted data, you can build an FHE training service by deploying the FHE training program of the SGDClassifier
. See the Production Deloyment page for more details on how to the Concrete ML deployment utility classes. To deploy an FHE training program, you must pass the mode='training'
parameter to the FHEModelDev
class.
This document introduces the nearest neighbors non-parametric classification models that Concrete ML provides with a scikit-learn interface through the KNeighborsClassifier
class.
Concrete ML | scikit-learn |
---|---|
The KNeighborsClassifier
class quantizes the training data-set provided to .fit
using the specified number of bits (n_bits
). To comply with accumulator size constraints, you must keep this value low. The model's accuracy will depend significantly on a well-chosen n_bits
value and the dimensionality of the data.
The predict
method of the KNeighborsClassifier
performs the following steps:
Quantize the test vectors on clear data
Compute the top-k class indices of the closest training set vector on encrypted data
Vote for the top-k class labels to find the class for each test vector, performed on clear data
The FHE inference latency of this model is heavily influenced by the n_bits
and the dimensionality of the data. Additionally, the data-set size has a linear impact on the data complexity. The number of nearest neighbors (n_neighbors
) also affects performance.
The KNN computation executes in FHE in steps, where is the training data-set size and is n_neighbors
. Each step requires several PBS operations, with their runtime affected by the factors listed above. These factors determine the precision needed to represent the distances between test vectors and training data-set vectors. The PBS input precision required by the circuit is related to the precision of the distance values.
This document introduces the simple built-in neural networks models that Concrete ML provides with a scikit-learn interface through the NeuralNetClassifier
and NeuralNetRegressor
classes.
Concrete ML | scikit-learn |
---|---|
The neural network models are implemented with skorch, which provides a scikit-learn-like interface to Torch models (more here).
Concrete ML models are multi-layer, fully-connected, networks with customizable activation functions and have a number of neurons in each layer. This approach is similar to what is available in scikit-learn when using the MLPClassifier
/MLPRegressor
classes. The built-in models train easily with a single call to .fit()
, which will automatically quantize weights and activations. These models use Quantization Aware Training, allowing good performance for low precision (down to 2-3 bits) weights and activations.
While NeuralNetClassifier
and NeuralNetClassifier
provide scikit-learn-like models, their architecture is somewhat restricted to make training easy and robust. If you need more advanced models, you can convert custom neural networks as described in the FHE-friendly models documentation.
Good quantization parameter values are critical to make models respect FHE constraints. Weights and activations should be quantized to low precision (e.g., 2-4 bits). The sparsity of the network can be tuned as described below to avoid accumulator overflow.
Using nn.ReLU
as the activation function benefits from an optimization where quantization uses powers-of-two scales. This results in much faster inference times in FHE, thanks to a TFHE primitive that performs fast division by powers of two.
To create an instance of a Fully Connected Neural Network (FCNN), you need to instantiate one of the NeuralNetClassifier
and NeuralNetRegressor
classes and configure a number of parameters that are passed to their constructor.
Note that some parameters need to be prefixed by module__
, while others don't. The parameters related to the model must have the prefix, such as the underlying nn.Module
. The parameters related to training options do not require the prefix.
The Classifier Comparison notebook shows the behavior of built-in neural networks on several synthetic data-sets.
The folowing figure shows the Concrete ML neural network trained with Quantization Aware Training in an FHE-compatible configuration and compares it to the floating-point equivalent trained with scikit-learn.
module__n_layers
: number of layers in the FCNN.
This parameter must be at least 1. Note that this is the total number of layers. For a single, hidden layer NN model, set module__n_layers=2
module__activation_function
: can be one of the Torch activations (such as nn.ReLU)
See the full list of Torch activations here.
Neural networks with nn.ReLU
activation benefit from specific optimizations that make them around 10x faster than networks with other activation functions.
n_w_bits
(default 3): number of bits for weights
n_a_bits
(default 3): number of bits for activations and inputs
n_accum_bits
: maximum accumulator bit-width that is desired
By default, this is unbounded, which, for weight and activation bit-width settings, may make the trained networks fail in compilation. When used, the implementation will attempt to keep accumulators under this bit-width through pruning (for example, setting some weights to zero).
power_of_two_scaling
(default True): forces quantization scales to be powers-of-two
When coupled with the ReLU activation, this optimize strongly the FHE inference time.
See this section in the quantization documentation for more details.
max_epochs
(default 10): The number of epochs to train the network
verbose
(default: False): Whether to log loss/metrics during training
lr
(default 0.001): Learning rate
You can find other parameters from skorch in the skorch documentation.
module__n_hidden_neurons_multiplier
(default 4): The number of hidden neurons.
This parameter will be automatically set proportional to the dimensionality of the input. It controls the proportionality factor. This value gives good accuracy while avoiding accumulator overflow.
See the pruning and quantization sections for more info.
You can give weights to each class to use in training. Note that this must be supported by the underlying PyTorch loss function.
The n_accum_bits
parameter influences training accuracy by controlling the number of non-zero neurons allowed in each layer. You can increase n_accum_bits
to improve accuracy, but must consider the precision limitations to avoid an overflow in the accumulator. The default value is a balanced choice that generally avoids overflow, but you may need to adjust it to reduce the network breadth if you encounter overflow errors.
The number of neurons in intermediate layers is controlled by the n_hidden_neurons_multiplier
parameter. A value of 1 makes intermediate layers have the same number of neurons as the number as the input data dimensions.
This document introduces several scikit-learn's linear models for classification
and regression
tree models that Concrete ML provides.
Concrete ML | scikit-learn |
---|---|
Concrete ML also supports XGBoost's XGBClassifier
and XGBRegressor
:
Concrete ML | XGboost |
---|---|
For a formal explanation of the mechanisms that enable FHE-compatible decision trees, please see the following paper: Privacy-Preserving Tree-Based Inference with Fully Homomorphic Encryption, arXiv:2303.01254
Using the maximum depth parameter of decision trees and tree-ensemble models strongly increases the number of nodes in the trees. Therefore, we recommend using the XGBoost models which achieve better performance with lower depth.
You can convert an already trained scikit-learn tree-based model to a Concrete ML one by using the from_sklearn_model
method.
Here's an example of how to use this model in FHE on a popular data-set using some of scikit-learn's pre-processing tools. You can find a more complete example in the XGBClassifier notebook.
We can plot and compare the decision boundaries of the Concrete ML model and the classical XGBoost model executed in the clear. Here we show a 6-bit model to illustrate the impact of quantization on classification. You will find similar plots in the Classifier Comparison notebook.
When using a sufficiently high bit-width, quantization has little impact on the decision boundaries of the Concrete ML FHE decision tree model, as quantization is done individually on each input feature. It means FHE models can achieve similar accuracy levels as floating point models. Using 6 bits for quantization is effective in reaching or even exceeding floating point accuracy.
To adjust the number of bits for quantization, use the n_bits
parameter. Setting n_bits
to a low value may introduce artifacts, potentially reducing accuracy. However, the execution speed in FHE could improve. This adjustment allows you to manage the accuracy/speed trade-off. Additionally, you can recover some accuracy by increasing the n_estimators
parameter.
The following graph shows that using 5-6 bits of quantization is usually sufficient to reach the performance of a non-quantized XGBoost model on floating point data. The metrics plotted are accuracy and F1-score on the spambase
data-set.
The inference time in FHE is strongly dependant on the maximum circuit bit-width. For trees, in most cases, the quantization bit-width will be the same as the circuit bit-width. Therefore, reducing the quantization bit-width to 4 or less will result in fast inference times. Adding more bits will increase FHE inference time exponentially.
In some rare cases, the bit-width of the circuit can be higher than the quantization bit-width. This could happen when the quantization bit-width is low but the tree-depth is high. In such cases, the circuit bit-width is upper bounded by ceil(log2(max_depth + 1) + 1)
.
For more information on the inference time of FHE decision trees and tree-ensemble models please see Privacy-Preserving Tree-Based Inference with Fully Homomorphic Encryption, arXiv:2303.01254.
This section explains how to fine-tune neural-network models and large language-models on private data. Small models can be be fine-tuned using a single-client/single-server setup. For optimal latency when fine-tuning larger models (e.g., GPT2 and bigger) you should consider distributed computation, with multiple worker nodes performing the training on encrypted data.
For a tutorial about applying FHE LORA fine-tuning to a small neural network, see .
Concrete ML supports LORA, a parameter efficient fine-tuning (PEFT) approach, in the paradigm. LORA adds adapters, which contain a low number of fine-tunable weights, to the linear layers in an original model.
Concrete ML will outsource the logic of a model's original forward and backward passes to one or more remote servers. On the other hand, the forward and backward passes over the LORA weights, the loss computation and the weight updates are performed by the client side. As the number of LORA weights is low, this does not incur significant added computation time for the model training client machine. More than 99% of a model's weights can be outsourced for large LLMs.
The main benefit of hybrid-model LORA training is outsourcing the computation of the linear layers. In LLMs these layers have considerable size and performing inference and gradient computations for them requires significant hardware. Using Concrete ML, these computations can be securely outsourced, eliminating the memory bottleneck that previously constrained such operations.
Concrete ML integrates with the which adds LORA layer adapters to a model's linear layers. Here are the steps to convert a model to hybrid FHE LORA training.
peft
LORA layersThe LoraConfig
class from the peft
package contains the various LORA parameters. It is possible to specify which layers have LORA adapters through the target_modules
argument. Please refer to the documentation for a reference on the various config options.
Concrete ML requires a conversion step for the peft
model, adding FHE compatible layers. In this step the several fine-tuning parameters can be configured:
the number of gradient accumulation steps: for LORA it is common to accumulate gradients over several gradient descent steps before updating weights.
the optimizer parameters
the loss function
Next, a hybrid FHE model must be compiled in order to convert the selected outsourced layers to use FHE. Other layers will be executed on the client side. The back-and-forth communication of encrypted activations and gradients may require significant bandwidth.
Finally, the hybrid model can be trained, much in the same way a PyTorch model is trained. The client is responsible for generating and iterating on training data batches.
One fine-tuned, the LORA hybrid FHE model can perform inference only, through the model.inference_model
attribute of the hybrid FHE model.
To compare to the original model, it is possible to disable the LORA weights in order to use the original model for inference.
This document explains how to compile models in Concrete ML. This is particularly useful for importing models trained with Keras.
You can compile ONNX models by directly importing models that are already quantized with or by performing with Concrete ML.
The following example shows how to compile an ONNX model using PTQ. The model was initially trained using Keras before being exported to ONNX. The training code is not shown here.
This example uses PTQ, meaning that the quantization is not performed during training. This model does not have the optimal performance in FHE.
To improve performance in FHE, you should add QAT. Additionally, you can also import QAT ONNX models .
While a Keras ONNX model was used in this example, Keras/Tensorflow support in Concrete ML is only partial and experimental.
Models trained using QAT contain quantizers in the ONNX graph. These quantizers ensure that the inputs to the Linear/Dense and Conv layers are quantized. Since these QAT models have quantizers configured to a specific number of bits during training, you must import the ONNX graph using the same settings:
Concrete ML supports the following operators for evaluation and conversion to an equivalent FHE circuit. Other operators were not implemented either due to FHE constraints or because they are rarely used in PyTorch activations or scikit-learn models.
Abs
Acos
Acosh
Add
Asin
Asinh
Atan
Atanh
AveragePool
BatchNormalization
Cast
Celu
Clip
Concat
Constant
ConstantOfShape
Conv
Cos
Cosh
Div
Elu
Equal
Erf
Exp
Expand
Flatten
Floor
Gather
Gemm
Greater
GreaterOrEqual
HardSigmoid
HardSwish
Identity
LeakyRelu
Less
LessOrEqual
Log
MatMul
Max
MaxPool
Min
Mul
Neg
Not
OneHot
Or
PRelu
Pad
Pow
ReduceSum
Relu
Reshape
Round
Selu
Shape
Sigmoid
Sign
Sin
Sinh
Slice
Softplus
Squeeze
Sub
Tan
Tanh
ThresholdedRelu
Transpose
Unfold
Unsqueeze
Where
onnx.brevitas.Quant
This section provides a set of tools and guidelines to help users debug errors and build optimized models that are compatible with Fully Homomorphic Encryption (FHE).
The of Concrete ML provides a way to evaluate, using clear data, the results that ML models produce on encrypted data. The simulation includes any probabilistic behavior FHE may induce. The simulation is implemented with .
The simulation mode can be useful when developing and iterating on an ML model implementation. As FHE non-linear models work with integers up to 16 bits, with a trade-off between the number of bits and the FHE execution speed, the simulation can help to find the optimal model design.
Simulation is much faster than FHE execution. This allows for faster debugging and model optimization. For example, this was used for the red/blue contours in the , as computing in FHE for the whole grid and all the classifiers would take significant time.
The following example shows how to use the simulation mode in Concrete ML.
It is possible to avoid re-generating the keys of the models you are debugging. This feature is unsafe and should not be used in production. Here is an example that shows how to enable key-caching:
Error message: this [N]-bit value is used as an input to a table lookup
Possible solutions:
Error message: RuntimeError: NoParametersFound
Cause: This error occurs when cryptosystem parameters can not be found for the model bit-width, rounding mode and requested p_error
, when using rounding_threshold_bits
in the compile_torch_model
function. With rounding_threshold_bits
set, the 16-bit accumulator limit is relaxed, so the this [N]-bit value is used as an input to a table lookup
does not occur. However, cryptosystem-parameters may still not exist for the model to be compiled.
Error message: Error occurred during quantization aware training (QAT) import [...] Could not determine a unique scale for the quantization!
.
A common example is related to the concatenation operator. Suppose two tensors x
and y
are produced by two layers and need to be concatenated:
In the example above, the x
and y
layers need quantization before being concatenated.
Possible solutions:
If the error occurs for the first layer of the model: Add a QuantIdentity
layer in your model and apply it on the input of the forward
function, before the first layer is computed.
If the error occurs for a concatenation or addition layer: Add a new QuantIdentity
layer in your model. Suppose it is called quant_concat
. In the forward
function, before concatenation of x
and y
, apply it to both tensors that are concatenated. The usage of a common Quantidentity
layer to quantize both tensors that are concatenated ensures that they have the same scale:
Furthermore, the cost of PBS depends on the bit-width of the compiled circuit. Every additional bit in the maximum bit-width significantly increase the complexity of the PBS. Therefore, it is important to determine the bit-width of the circuit and the amount of PBS it performs in order to optimize the performance.
To inspect the MLIR code produced by the compiler, use the following command:
Example output:
In the MLIR code, there are several calls to FHELinalg.apply_mapped_lookup_table
and FHELinalg.apply_lookup_table
. These calls apply PBS to the cells of their input tensors. For example, in the code above, the inputs are: tensor<1x5x!FHE.eint<15>>
for both the first and last apply_mapped_lookup_table
call. Thus, the PBS is applied 10 times, corresponding to the size of every encrypted tensor, which is 1x5 multiplied by 2.
To retrieve the bit-width of the circuit, use this command:
Reducing the number of bits and the number of PBS applications can significantly decrease the computation time of the compiled circuit.
This document explains how to implement machine learning models with Torch in Concrete ML, leveraging Fully Homomorphic Encryption (FHE).
There are two approaches to build :
: This method requires using custom layers to quantize weights and activations to low bit-widths. Concrete ML works with , a library that provides QAT support for PyTorch.
Use compile_brevitas_qat_model
to compile models in this mode.
: This method allows to compile a vanilla PyTorch model. However, accuracy may decrease significantly when quantizing weights and activations to fewer than 7 bits. On the other hand, depending on the model size, quantizing with 6-8 bits can be incompatible with FHE constraints. Thus you need to determine the trade-off between model accuracy and FHE compatibility.
Use compile_torch_model
to compile models in this mode.
Both approaches require setting rounding_threshold_bits
parameter accordingly. You should experiment to find the best values, starting with an initial value of 6
. See for more details.
See the for explanations and solutions to some common errors raised by the compilation function.
The following example uses a simple QAT PyTorch model that implements a fully connected neural network with two hidden layers. Due to its small size, making this model respect FHE constraints is relatively easy. To use QAT, Brevitas QuantIdentity
nodes must be inserted in the PyTorch model, including one that quantizes the input of the forward
function.
The following example demonstrates a simple PyTorch model that implements a fully connected neural network with two hidden layers. The model is compiled with compile_torch_model
to use FHE.
The quantization parameters, along with the number of neurons in each layer, determine the accumulator bit-width of the network. Larger accumulator bit-widths result in higher accuracy but slower FHE inference time.
QAT: Configure parameters such as bit_width
and weight_bit_width
. Set n_bits=None
in the compile_brevitas_qat_model
.
PTQ: Set the n_bits
value in the compile_torch_model
function. Manually determine the trade-off between accuracy, FHE compatibility, and latency.
The model can now perform encrypted inference.
In this example, the input values x_test
and the predicted values y_pred
are floating points. The quantization (respectively de-quantization) step is done in the clear within the forward
method, before (respectively after) any FHE computations.
There are two approaches:
quantized_module.forward(quantized_x, fhe="simulate")
: This method simulates FHE execution taking into account Table Lookup errors. De-quantization must be done in a second step as for actual FHE execution. Simulation takes into account the p_error
/global_p_error
parameters
quantized_module.forward(quantized_x, fhe="disable")
: This method computes predictions in the clear on quantized data, and then de-quantize the result. The return value of this function contains the de-quantized (float) output of running the model in the clear. Calling this function on clear data is useful when debugging, but this does not perform actual FHE simulation.
Concrete ML supports a variety of PyTorch operators that can be used to build fully connected or convolutional neural networks, with normalization and activation layers. Moreover, many element-wise operators are supported.
Concrete ML also supports some of their QAT equivalents from Brevitas.
brevitas.nn.QuantLinear
brevitas.nn.QuantConv1d
brevitas.nn.QuantConv2d
brevitas.nn.QuantIdentity
The equivalent versions from torch.functional
are also supported.
Zama 5-Question Developer Survey
Cause: This error can occur when rounding_threshold_bits
is not used and accumulated intermediate values in the computation exceed 16 bits. To pinpoint the model layer that causes the error, Concrete ML provides the helper function. To use this function, the model must be compiled first so that it can be .
Reduce quantization n_bits
. However, this may reduce accuracy. When quantization n_bits
must be below 6, it is best to use .
Use rounding_threshold_bits
. This feature is described . It is recommended to use the setting, and set the rounding bits to 1 or 2 bits higher than the quantization n_bits
Use
Possible solutions: The solutions in this case are similar to the ones for the previous error: reducing bit-width, or reducing the rounding_threshold_bits
, or using the rounding method can help. Additionally adjusting the tolerance for one-off errors using the p_error
parameter can help, as explained in .
Cause: This error occurs when the model imported as a quantized-aware training model lacks quantization operators. See on how to use Brevitas layers. This error message indicates that some layers do not take inputs quantized through QuantIdentity
layers.
In FHE, univariate functions are encoded as Table Lookups, which are then implemented using . PBS is a powerful technique but requires significantly more computing resources compared to simpler encrypted operations such as matrix multiplications, convolution, or additions.
Once the model is trained, use from Concrete ML to perform conversion and compilation of the QAT network. Here, 3-bit quantization is used for both the weights and activations. This function automatically identifies the number of quantization bits used in the Brevitas model.
If QuantIdentity
layers are missing for any input or intermediate value, the compile function will raise an error. See the for an explanation.
You can perform the inference on clear data in order to evaluate the impact of quantization and of FHE computation on the accuracy of their model. See for more details.
FHE simulation allows to measure the impact of the Table Lookup error on the model accuracy. You can adjust the Table Lookup error using p_error
/global_p_error
, as described in the section.
-- for casting to dtype
-- partial support
We want to hear from you! Take 1 minute to share your thoughts and helping us enhance our documentation and libraries. 👉 to participate.
This document introduces several approaches to reduce the overall latency of a neural network.
Neural networks are challenging for encrypted inference. Each neuron in a network has to apply an activation function that requires a Programmable Bootstrapping(PBS) operation. The latency of a single PBS depends on the bit-width of its input.
Quantization Aware Training and pruning introduce specific hyper-parameters that influence the accumulator sizes. You can chose quantization and pruning configurations to reduce the accumulator size. To obtain a trade-off between latency and accuracy, you can manually set these hyper-parameters as described in the deep learning design guide.
While using unstructured pruning ensures the accumulator bit-width stays low, structured pruning can eliminate entire neurons from the network as many neural networks are over-parametrized for easier training. You can apply structured pruning to a trained network as a fine-tuning step. This example demonstrates how to apply structured pruning to built-in neural networks using the prune helper function. To apply structured pruning to custom models, it is recommended to use the torch-pruning package.
Reducing the bit-width of inputs to the Table Lookup (TLU) operations significantly improves latency. Post-training, you can leverage properties of the fused activation and quantization functions in the TLUs to further reduce the accumulator size. This is achieved through the rounded PBS feature as described in the rounded activations and quantizers reference. Adjusting the rounding amount relative to the initial accumulator size can improve latency while maintaining accuracy.
Finally, the TFHE scheme introduces a TLU error tolerance parameter that has an impact on crypto-system parameters that influence latency. A higher tolerance of TLU off-by-one errors results in faster computations but may reduce accuracy. You can think of the error of obtaining as a Gaussian distribution centered on : is obtained with probability of 1 - p_error
, while , are obtained with much lower probability, etc. In Deep NNs, these type of errors can be tolerated up to some point. See the p_error
documentation for details and more specifically the API for finding the best p_error
.
This document explains how to perform encryption, execution, and decryption of Fully Homomorphic Encryption (FHE) using one function call of the Concrete ML API, or multiple function calls separately.
The APIs are different for the following:
All Concrete ML built-in models have a single predict
method that performs the encryption, FHE execution, and decryption with only one function call.
The following example shows how to create a synthetic data-set and how to use it to train a LogisticRegression model from Concrete ML.
Concrete ML models follow the same API as scikit-learn models, transparently performing the steps related to encryption for convenience.
Regarding this LogisticRegression model, as with scikit-learn, it is possible to predict the logits as well as the class probabilities by respectively using the decision_function
or predict_proba
methods instead.
Alternatively, you can execute key generation, quantization, encryption, FHE execution and decryption separately.
For custom models, the API to execute inference in FHE or simulation is as follows:
This document explains how to serialize build-in models in Concrete ML.
Serialization allows you to dump a fitted and compiled model into a JSON string or file. You can then load the estimator back using the JSON object.
All built-in models provide the following methods:
dumps
: Dumps the model as a string.
dump
: Dumps the model into a file.
For example, a logistic regression model can be dumped in a string as follows:
Similarly, it can be dumped into a file:
Alternatively, Concrete ML provides two equivalent global functions:
Some parameters used for instantiating Quantized Neural Network models are not supported for serialization. In particular, you cannot serialize a model that was instantiated using callable objects for the train_split
and predict_nonlinearity
parameters or with callbacks
being enabled.
You can load a built-in model using the following functions:
loads
: Loads the model from a string.
load
: Loads the model from a file.
A loaded model must be compiled once again to execute the inference in FHE or with simulation because the underlying FHE circuit is currently not serialized. This recompilation is not required when FHE mode is disabled.
The same logistic regression model can be loaded as follows:
This document explains how to use Concrete ML API to deploy hybrid models in Fully Homomorphic Encryption (FHE).
FHE allows cloud applications to process private user data securely, minimizing the risk of data leaks. Deploying machine learning (ML) models in the cloud offers several advantages:
Simplifies model updates.
Scales to large user bases by leveraging substantial compute power.
Protects model's Intellectual Property (IP) by keeping the model on a trusted server rather than on client devices.
However, not all applications can be easily converted to FHE computation. The high computation cost of FHE might exceed latency requirements for full conversion.
Hybrid models provide a balance between on-device deployment and cloud-based deployment. This approach involves:
Executing parts of the model on the client side.
Securely processing other parts with FHE on the server side.
Concrete ML supports hybrid deployment for various neural network models, including Multilayer Perceptron (MLP), Convolutional Neural Network (CNN), and Large Language Models(LLM).
To protect model IP, carefully choose the model parts to execute in the cloud. Some black-box model stealing attacks use knowledge distillation or differential methods. Generally, the difficulty of stealing a machine learning model increases with the model's size, number of parameters, and depth.
The hybrid model deployment API simplifies integrating the standard deployment procedure into neural network style models that are compiled with compile_brevitas_qat_model
or compile_torch_model
.
To use hybrid model deployment, the first step is to define which part of the PyTorch neural network model must be executed in FHE. Ensure the model part is a nn.Module
and is identified by its key in the original model's .named_modules()
.
Here is an example:
The save_and_clear_private_info
functions as follows:
Serializes the FHE circuits for the model parts chosen to be server-side.
Saves the client-side model, removing the weights of the layers transferred to the server.
Saves all necessary information required to serve these sub-models with FHE using the FHEModelDev
class.
To create a server application that serves these sub-models, use the FHEModelServer
class:
For more information about serving FHE models, see the client/server section.
You can develop a client application that deploys a model with hybrid deployment in a very similar manner to on-premise deployment: Use PyTorch to load the model normally, but specify the remote endpoint and the part of the model to be executed remotely.
Next, obtain the parameters necessary to encrypt and quantize data, as detailed in the client/server documentation.
When the client application is ready to make inference requests to the server, set the operation mode of the HybridFHEModel
instance to HybridFHEMode.REMOTE
:
For inference with the HybridFHEModel
instance, hybrid_model
, call the regular forward
method as if the model was fully deployed locally::
When calling HybridFHEModel
, it handles all the necessary intermediate steps for each model part deployed remotely, including:
Quantizing the data.
Encrypting the data.
Making the request to the server using requests
Python module.
Decrypting and de-quantizing the result.
This guide demonstrates how to convert a PyTorch neural network into a Fully Homomorphic Encryption (FHE)-friendly, quantized version. It focuses on Quantization Aware Training (QAT) using a simple network on a synthetic data-set. This guide is based on a notebook tutorial, from which some code blocks are documented.
In general, quantization can be carried out in two different ways:
During the training phase with Quantization Aware Training (QAT)
After the training phase with Post Training Quantization (PTQ).
For FHE-friendly neural networks, QAT is the best method to achieve optimal accuracy under FHE constraints. This technique reduces weights and activations to very low bit-widths (for example, 2-3 bits). When combined with pruning, QAT helps keep low accumulator bit-widths.
Concrete ML uses the third-party library Brevitas to perform QAT for PyTorch neural networks, but options exist for other frameworks such as Keras/Tensorflow. Concrete ML provides several demos and tutorials that use Brevitas , including the CIFAR classification tutorial. For a more formal description of the usage of Brevitas to build FHE-compatible neural networks, please see the Brevitas usage reference.
For a formal explanation of the mechanisms that enable FHE-compatible neural networks, please see the the following paper.
Deep Neural Networks for Encrypted Inference with TFHE, 7th International Symposium, CSCML 2023
In PyTorch, using standard layers, a Fully Connected Neural Network (FCNN) would look like this:
Similarly to the one above, the notebook tutorial shows how to train a FCNN on a synthetic 2D data-set with a checkerboard grid pattern of 100 x 100 points. The data is split into 9500 training and 500 test samples.
Once trained, you can import this PyTorch network using the compile_torch_model
function, which uses simple PTQ.
The network was trained using different numbers of neurons in the hidden layers, and quantized using 3-bits weights and activations. The mean accumulator size, shown below, is measured as the mean over 10 runs of the experiment. An accumulator size of 6.6 means that 4 times out of 10, the accumulator was 6 bits, while 6 times it was 7 bits.
This shows that the fp32 accuracy and accumulator size increases with the number of hidden neurons, while the 3-bits accuracy remains low regardless of the number of neurons. Although all configurations tested were FHE-compatible (accumulator < 16 bits), it is often preferable to have a lower accumulator size to speed up inference time.
Accumulator size is determined by Concrete as the maximum bit-width encountered anywhere in the encrypted circuit.
Using QAT with Brevitas is the best way to guarantee a good accuracy for Concrete ML compatible neural networks.
Brevitas provides quantized versions of almost all PyTorch layers. For example, Linear
layer becomes QuantLinear
, and ReLU
layer becomes QuantReLU
. Brevitas also offers additional quantization parameters, such as:
bit_width
: precision quantization bits for activations
act_quant
: quantization protocol for the activations
weight_bit_width
: precision quantization bits for weights
weight_quant
: quantization protocol for the weights
To use FHE, the network must be quantized from end to end. With the Brevitas QuantIdentity
layer, you can quantize the input by placing it at the network's entry point. Moreover, you can combine PyTorch and Brevitas layers, as long as a QuantIdentity
layer follows the PyTorch layer. The following table lists the replacements needed to convert a PyTorch neural network for Concrete ML compatibility.
Some PyTorch operators (from the PyTorch functional API), require a brevitas.quant.QuantIdentity
to be applied on their inputs.
The QAT import tool in Concrete ML is a work in progress. While it has been tested with some networks built with Brevitas, it is possible to use other tools to obtain QAT networks.
With Brevitas, the network above becomes:
In the network above, biases are used for linear layers but are not quantized ("bias": True, "bias_quant": None
). The addition of the bias is a univariate operation and is fused into the activation function.
Training this network with pruning (see below) using 30 out of 100 total non-zero neurons gives good accuracy while keeping the accumulator size low.
The PyTorch QAT training loop is the same as the standard floating point training loop, but hyper-parameters such as learning rate might need to be adjusted.
QAT is somewhat slower than normal training. QAT introduces quantization during both the forward and backward passes. The quantization process is inefficient on GPUs due to its low computational intensity is low relative to data transfer time.
Considering that FHE only works with limited integer precision, there is a risk of overflowing in the accumulator, which will make Concrete ML raise an error.
To understand how to overcome this limitation, consider a scenario where 2 bits are used for weights and layer inputs/outputs. The Linear
layer computes a dot product between weights and inputs . With 2 bits, no overflow can occur during the computation of the Linear
layer as long the number of neurons does not exceed 14, as in the sum of 14 products of 2-bits numbers does not exceed 7 bits.
By default, Concrete ML uses symmetric quantization for model weights, with values in the interval . For example, for the possible values are ; for , the values can be .
In a typical setting, the weights will not all have the maximum or minimum values (such as ). Weights typically have a normal distribution around 0, which is one of the motivating factors for their symmetric quantization. A symmetric distribution and many zero-valued weights are desirable because opposite sign weights can cancel each other out and zero weights do not increase the accumulator size.
This fact can be leveraged to train a network with more neurons, while not overflowing the accumulator, using a technique called pruning where the developer can impose a number of zero-valued weights. Torch provides support for pruning out of the box.
The following code shows how to use pruning in the previous example:
Results with PrunedQuantNet
, a pruned version of the QuantSimpleNet
with 100 neurons on the hidden layers, are given below, showing a mean accumulator size measured over 10 runs of the experiment:
This shows that the fp32 accuracy has been improved while maintaining constant mean accumulator size.
When pruning a larger neural network during training, it is easier to obtain a low bit-width accumulator while maintaining better final accuracy. Thus, pruning is more robust than training a similar, smaller network.
This document explains the deployment workflow and the model serving pattern for deploying Fully Homomorphic Encryption machine learning models in a client/server setting using Concrete ML.
The steps to prepare a model for encrypted inference in a client/server setting is illustrated as follows:
The training of the model and its compilation to FHE are performed on a development machine.
Three different files are created when saving the model:
client.zip
contains the following files:
client.specs.json
lists the secure cryptographic parameters needed for the client to generate private and evaluation keys.
serialized_processing.json
describes the pre-processing and post-processing required by the machine learning model, such as quantization parameters to quantize the input and de-quantize the output.
server.zip
contains the compiled model. This file is sufficient to run the model on a server. The compiled model is machine-architecture specific, for example, a model compiled on x86 cannot run on ARM.
The compiled model (server.zip
) is deployed to a server. The cryptographic parameters (client.zip
) are shared with the clients. In some settings, such as a phone application, the client.zip
can be directly deployed on the client device and the server does not need to host it.
Important: In a client-server production using FHE, the server's output format depends on the model type:
For regressors, the output matches the predict()
method from scikit-learn, providing direct predictions.
For classifiers, the output uses the predict_proba()
method format, offering probability scores for each class, which allows clients to determine class membership by applying a threshold (commonly 0.5).
The FHEModelDev
, FHEModelClient
, and FHEModelServer
classes in the concrete.ml.deployment
module simplifies the deployment and interaction between the client and server:
FHEModelDev
:
This class handles the serialization of the underlying FHE circuit as well as the crypto-parameters used for generating the keys.
Use the save
method of this class during the development phase to prepare and save the model artifacts (client.zip
and server.zip
). With save
method, you can deploy a trained model or a training FHE program.
FHEModelClient
is used on the client side for the following actions:
Generate and serialize the cryptographic keys.
Encrypt the data before sending it to the server.
Decrypt the results received from the server.
Load quantization parameters and pre/post-processing from serialized_processing.json
.
FHEModelServer
is used on the server side for the following actions:
Load the FHE circuit from server.zip
.
Execute the model on encrypted data received from the client.
From Client to Server: serialized_evaluation_keys
(once), encrypted_data
.
From Server to Client: encrypted_result
.
These objects are serialized into bytes to streamline the data transfer between the client and server.
The client-side deployment of a secured inference machine learning model is illustrated as follows:
The workflow contains the following steps:
Key generation: The client obtains the cryptographic parameters stored in client.zip
and generates a private encryption/decryption key as well as a set of public evaluation keys.
Sending public keys: The public evaluation keys are sent to the server, while the secret key remains on the client.
Data encryption: The private data is encrypted by the client as described in the serialized_processing.json
file in client.zip
.
Data transmission: The encrypted data is sent to the server.
Encrypted inference: Server-side, the FHE model inference is run on encrypted inputs using the public evaluation keys.
Data transmission: The encrypted result is returned by the server to the client.
Data decryption: The client decrypts it using its private key.
Post-processing: The client performs any necessary post-processing of the decrypted result as specified in serialized_processing.json
(part of client.zip
).
The server-side implementation of a Concrete ML model is illustrated as follows:
The workflow contains the following steps:
Storing the public key: The public evaluation keys sent by clients are stored.
Model evaluation: The public evaluation keys are retrieved for the client that is querying the service and used to evaluate the machine learning model stored in server.zip
.
Sending back the result: The server sends the encrypted result of the computation back to the client.
For a complete example, see the client-server notebook or the use-case examples.
This document provides a complete instruction on using GPU acceleration with Concrete ML.
Concrete ML can compile both built-in and custom models using a CUDA-accelerated backend. However, once a model is compiled for CUDA, executing it on a non-CUDA-enabled machine will raise an error.
Feature | Built-in models | Custom Models | Deployment | DataFrame |
---|
When compiling a model for GPU, it will be assigned GPU-specific crypto-system parameters. These parameters are more constrained compared to CPU-specific ones. As a result, the Concrete compiler may have difficulty finding suitable GPU-compatible crypto-parmaters for some models, leading to a NoParametersFound
error.
On high-end GPUs like V100, A100, or H100, the performance gains range from 1x to 10x compared to a desktop CPU. When compared to a high-end 64 or 96-core server CPU, the speed-up is typically around 1x to 3x.
On consumer grade GPUs such as GTX40xx or GTX30xx, there may be little speedup or even a slowdown compared to execution on a desktop CPU.
To use the CUDA enabled backend you need to install the GPU-enabled Concrete compiler:
If you already have the same version of concrete-python
installed, it will not be re-installed automatically. In that case you may need to remove it manually before installing the GPU version.
To switch back to the CPU-only version of the compiler, change the index-url to the CPU-only repository or remove the index-url parameter alltogether:
To check if the CUDA acceleration is available you can use helper functions of concrete-python
:
To compile a model for cuda, simply supply the device='cuda'
argument to its compilation function. For built-in models, this function is .compile
, while for custom models it can be compile_torch_model
or compile_brevitas_qat_model
.
These examples illustrate the basic usage of Concrete ML to build various types of neural networks. They use simple data-sets, focusing on the syntax and usage of Concrete ML. For examples showing how to train high-accuracy models on more complex data-sets, see the section.
The examples listed here make use of to perform evaluation over large test sets. Since FHE execution can be slow, only a few FHE executions can be performed. The of Concrete ML ensure that accuracy measured with simulation is the same as that which will be obtained during FHE execution.
Some examples constrain accumulators to 7-8 bits, which can be sufficient for simple data-sets. Up to 16-bit accumulators can be used, but this introduces a slowdown of 4-5x compared to 8-bit accumulators.
This shows how to use Quantization Aware Training and pruning when starting out from a classical PyTorch network. This example uses a simple data-set and a small NN, which achieves good accuracy with low accumulator size.
Following the , this notebook implements a Quantization Aware Training convolutional neural network on the MNIST data-set. It uses 3-bit weights and activations, giving a 7-bit accumulator.
The default parameters for Concrete ML are chosen considering the security model, and are selected with a of . In particular, it is assumed that the results of decrypted computations are not shared by the secret key owner with any third parties, as such an action can lead to leakage of the secret encryption key. If you are designing an application where decryptions must be shared, you will need to craft custom encryption parameters which are chosen in consideration of the IND-CPA^D security model [1].
The section explains how Concrete ML can ensure guaranteed correctness of encrypted computations. In this approach, a quantized machine learning model will be converted to an FHE circuit that produces the same result on encrypted data as the original model on clear data.
However, the can be configured by the user. Raising this probability results in lower latency when executing on encrypted data, but higher values cancel the correctness guarantee of the default setting. In practice this may not be an issue, as the accuracy of the model may be maintained, even though slight differences are observed in the model outputs. Moreover, as noted in the , raising the off-by-one error probability may negatively impact the security model.
Furthermore, a second approach to reduce latency at the expense of correctness is approximate computation of univariate functions. This mode is enabled by using the . When using the rounding method, off-by-one errors are always induced in the computation of activation functions, irrespective of the bootstrapping off-by-one error probability.
When trading-off better latency for correctness, it is highly recommended to use the to measure accuracy on a drawn-out test-set. In many cases the accuracy of the model is only slightly impacted by approximate computations.
[1] Li, Baiyu, et al. “Securing approximate homomorphic encryption using differential privacy.” Annual International Cryptology Conference. Cham: Springer Nature Switzerland, 2022. https://eprint.iacr.org/2022/816.pdf
: Encrypted anonymization uses Fully Homomorphic Encryption (FHE) to anonymize personally identifiable information (PII) within encrypted documents, enabling computations to be performed on the encrypted data.
Check the
: Predicting credit scoring card approval application in which sensitive data can be shared and analyzed without exposing the actual information to neither the three parties involved, nor the server processing it.
Check the
: predicting if an encrypted tweet / short message is positive, negative or neutral, using FHE.
Check the and the
: giving a diagnosis using FHE to preserve the privacy of the patient based on a patient's symptoms, history and other health factors.
Check the
: filtering encrypted images by applying filters such as black-and-white, ridge detection, or your own filter.
Check the
Zama 5-Question Developer Survey
These examples illustrate the basic usage of built-in Concrete ML models. For more examples showing how to train high-accuracy models on more complex data-sets, see the section.
In Concrete ML, built-in linear models are exact equivalents to their scikit-learn counterparts. As they do not apply any non-linearity during inference, these models are very fast (~1ms FHE inference time) and can use high-precision integers (between 20-25 bits).
Tree-based models apply non-linear functions that enable comparisons of inputs and trained thresholds. Thus, they are limited with respect to the number of bits used to represent the inputs. But as these examples show, in practice 5-6 bits are sufficient to exactly reproduce the behavior of their scikit-learn counterpart models.
In the examples below, built-in neural networks can be configured to work with user-specified accumulator sizes, which allow the user to adjust the speed/accuracy trade-off.
It is recommended to use to configure the speed/accuracy trade-off for tree-based models and neural networks, using grid-search or your own heuristics.
These examples show how to use the built-in linear models on synthetic data, which allows for easy visualization of the decision boundaries or trend lines. Executing these 1D and 2D models in FHE takes around 1 millisecond.
Based on three different synthetic data-sets, all the built-in classifiers are demonstrated in this notebook, showing accuracies, inference times, accumulator bit-widths, and decision boundaries.
This example shows how to configure a training algorithm that works on encrypted data and how to deploy it in a client/server application.
: Module for shared data structures and code.
: Check and conversion tools.
: Module for debugging.
: Provide some variants of assert.
: Serialization module.
: Custom decoder for serialization.
: Dump functions for serialization.
: Custom encoder for serialization.
: Load functions for serialization.
: Utils that can be re-used by other pieces of code in the module.
: Module for deployment of the FHE model.
: APIs for FHE deployment.
: ONNX module.
: ONNX conversion related code.
: Utility functions for onnx operator implementations.
: Some code to manipulate models.
: Utils to interpret an ONNX model with numpy.
: ONNX ops implementation in Python + NumPy.
: Public API for encrypted data-frames.
: Define the framework used for managing keys (encrypt, decrypt) for encrypted data-frames.
: Define the encrypted data-frame framework.
: Module which is used to contain common functions for pytest.
: Torch modules for our pytests.
: Common functions or lists for test files, which can't be put in fixtures.
: Modules for quantization.
: Base Quantized Op class that implements quantization for a float numpy op.
: Post Training Quantization methods.
: QuantizedModule API.
: Optimization passes for QuantizedModules.
: Quantized versions of the ONNX operators for post training quantization.
: Quantization utilities for a numpy array/tensor.
: Modules for p_error
search.
: p_error binary search for classification and regression tasks.
: Import sklearn models.
: Base classes for all estimators.
: Implement sklearn's Generalized Linear Models (GLM).
: Implement sklearn linear model.
: Implement sklearn neighbors model.
: Scikit-learn interface for fully-connected quantized neural networks.
: Sparse Quantized Neural Network torch module.
: Implement RandomForest models.
: Implement Support Vector Machine.
: Implement DecisionTree models.
: Implements the conversion of a tree model to a numpy function.
: Implements XGBoost models.
: Modules for torch to numpy conversion.
: torch compilation function.
: Implement the conversion of a torch model to a hybrid fhe/torch inference.
: This module contains classes for LoRA (Low-Rank Adaptation) training and custom layers.
: A torch to numpy module.
: File to manage the version of the package.
neurons | 10 | 30 | 100 |
---|---|---|---|
PyTorch fp32 layer | Concrete ML model with PyTorch/Brevitas |
---|---|
PyTorch ops that require QuantIdentity |
---|
Non-zero neurons | 30 |
---|---|
Non-zero neurons | 10 | 30 |
---|---|---|
: Privacy-preserving text generation based on a user's prompt
: Train an XGB classifier that can perform encrypted prediction for the
: Use federated learning to train a Logistic Regression while preserving training data confidentiality. Import the model into Concrete ML and perform encrypted prediction
: Fine-tune a VGG network to classify the CIFAR image data-sets and predict on encrypted data
:A Hugging Face space that securely analyzes the sentiment expressed in a short text
: Predict the chance of a given loan applicant defaulting on loan repayment
- April 2024
- February 2024
- June 2023
- June 2023
- May 2023
- February 2023
- November 2022
- August 2022
- May 2024
- February 2024
- June 2023
We want to hear from you! Take 1 minute to share your thoughts and helping us enhance our documentation and libraries. 👉 to participate.
These two examples show generalized linear models (GLM) on the real-world data-set. As the non-linear, inverse-link functions are computed, these models do not use , and are, thus, very fast (~1ms execution time).
Using the data-set, this example shows how to train a classifier that detects spam, based on features extracted from email messages. A grid-search is performed over decision-tree hyper-parameters to find the best ones.
Using the data-set, this example shows how to train regressor that predicts house prices.
This example shows how to train tree-ensemble models (either XGBoost or Random Forest), first on a synthetic data-set, and then on the data-set. Grid-search is used to find the best number of trees in the ensemble.
Privacy-preserving prediction of house prices is shown in this example, using the data-set. Using 50 trees in the ensemble, with 5 bits of precision for the input features, the FHE regressor obtains an score of 0.90 and an execution time of 7-8 seconds.
Two different configurations of the built-in, fully-connected neural networks are shown. First, a small bit-width accumulator network is trained on and compared to a PyTorch floating point network. Second, a larger accumulator (>8 bits) is demonstrated on .
: Custom json decoder to handle non-native types found in serialized Concrete ML objects.
: Custom json encoder to handle non-native types found in serialized Concrete ML objects.
: Enum representing the execution mode.
: Mode for the FHE API.
: Client API to encrypt and decrypt FHE data.
: Dev API to save the model and then load and run the FHE circuit.
: Server API to load and run the FHE circuit.
: A mixed quantized-raw valued onnx function.
: Type construct that marks an ndarray as a raw output of a quantized op.
: Define a framework that manages keys.
: Define an encrypted data-frame framework that supports Pandas operators and parameters.
: Torch model that performs a simple addition between two inputs.
: Torch model with some branching and skip connections.
: Torch model with some branching and skip connections.
: Torch CNN model for the tests.
: Torch CNN model with grouped convolution for compile torch tests.
: Torch CNN model for the tests.
: Torch CNN model for the tests with a max pool.
: Torch CNN model for the tests.
: Concat with fancy indexing.
: Small model that uses a 1D convolution operator.
: Torch model that with two different quantizers on the input.
: A torch model with an embedding layer.
: PyTorch module for performing matrix multiplication between two encrypted values.
: Minimalist network that expands the input tensor to a larger size.
: Torch model for the tests.
: Torch model that should generate MatMul->Add ONNX patterns.
: Torch model that should generate MatMul->Add ONNX patterns.
: Torch model for the tests.
: Model that only adds an empty dimension at axis 0.
: Model that only adds an empty dimension at axis 0, and returns the initial input as well.
: PyTorch module for performing SGD training.
: Torch model to test multiple inputs forward.
: Torch model to test multiple inputs forward.
: Torch model to test multiple inputs with different shape in the forward pass.
: Network that applies two quantized operations on a single input.
: Multi-output model.
: Torch model to test the concat and unsqueeze operators.
: Torch QAT model that does not quantize the inputs.
: Torch model, where we reuse some elements in a loop.
: Torch QAT model that applies various padding patterns.
: A model with a QAT Module.
: Torch model that implements a simple non-uniform quantizer.
: A small quantized network with Brevitas, trained on make_classification.
: Torch QAT model that reshapes the input.
: Fake torch model used to generate some onnx.
: Torch model implements a step function that needs Greater, Cast and Where.
: Torch model that with a single conv layer that produces the output, e.g., a blur filter.
: Torch model implements a step function that needs Greater, Cast and Where.
: A very small CNN.
: A very small QAT CNN to classify the sklearn digits data-set.
: A small network with Brevitas, trained on make_classification.
: Torch model that performs a encrypted division between two inputs.
: Torch model that performs a encrypted multiplication between two inputs.
: Torch model to test the ReduceSum ONNX operator in a leveled circuit.
: Torch model that calls univariate and shape functions of torch.
: An operator that mixes (adds or multiplies) together encrypted inputs.
: Base class for quantized ONNX ops implemented in numpy.
: An univariate operator of an encrypted value.
: Base ONNX to Concrete ML computation graph conversion class.
: Post-training Affine Quantization.
: Converter of Quantization Aware Training networks.
: Inference for a quantized model.
: Detect neural network patterns that can be optimized with round PBS.
: ConstantOfShape operator.
: Gather operator.
: Shape operator.
: Slice operator.
: Quantized Abs op.
: Quantized Addition operator.
: Quantized Average Pooling op.
: Quantized Batch normalization with encrypted input and in-the-clear normalization params.
: Brevitas uniform quantization with encrypted input.
: Cast the input to the required data type.
: Quantized Celu op.
: Quantized clip op.
: Concatenate operator.
: Quantized Conv op.
: Quantized Division operator.
: Quantized Elu op.
: Comparison operator ==.
: Quantized erf op.
: Quantized Exp op.
: Expand operator for quantized tensors.
: Quantized flatten for encrypted inputs.
: Quantized Floor op.
: Quantized Gemm op.
: Comparison operator >.
: Comparison operator >=.
: Quantized HardSigmoid op.
: Quantized Hardswish op.
: Quantized Identity op.
: Quantized LeakyRelu op.
: Comparison operator <.
: Comparison operator <=.
: Quantized Log op.
: Quantized MatMul op.
: Quantized Max op.
: Quantized Max Pooling op.
: Quantized Min op.
: Quantized Multiplication operator.
: Quantized Neg op.
: Quantized Not op.
: Or operator ||.
: Quantized PRelu op.
: Quantized Padding op.
: Quantized pow op.
: ReduceSum with encrypted input.
: Quantized Relu op.
: Quantized Reshape op.
: Quantized round op.
: Quantized Selu op.
: Quantized sigmoid op.
: Quantized Neg op.
: Quantized Softplus op.
: Squeeze operator.
: Subtraction operator.
: Quantized Tanh op.
: Transpose operator for quantized inputs.
: Quantized Unfold op.
: Unsqueeze operator.
: Where operator on quantized arrays.
: Calibration set statistics.
: Options for quantization.
: Abstraction of quantized array.
: Quantization parameters for uniform quantization.
: Uniform quantizer.
: Class for p_error
hyper-parameter search for classification and regression tasks.
: Base class for linear and tree-based classifiers in Concrete ML.
: Base class for all estimators in Concrete ML.
: Mixin class for tree-based classifiers.
: Mixin class for tree-based estimators.
: Mixin class for tree-based regressors.
: Mixin that provides quantization for a torch module and follows the Estimator API.
: A Mixin class for sklearn KNeighbors classifiers with FHE.
: A Mixin class for sklearn KNeighbors models with FHE.
: A Mixin class for sklearn linear classifiers with FHE.
: A Mixin class for sklearn linear models with FHE.
: A Mixin class for sklearn linear regressors with FHE.
: A Mixin class for sklearn SGD classifiers with FHE.
: A Mixin class for sklearn SGD regressors with FHE.
: A Gamma regression model with FHE.
: A Poisson regression model with FHE.
: A Tweedie regression model with FHE.
: An ElasticNet regression model with FHE.
: A Lasso regression model with FHE.
: A linear regression model with FHE.
: A logistic regression model with FHE.
: A Ridge regression model with FHE.
: An FHE linear classifier model fitted with stochastic gradient descent.
: An FHE linear regression model fitted with stochastic gradient descent.
: A k-nearest neighbors classifier model with FHE.
: A Fully-Connected Neural Network classifier with FHE.
: A Fully-Connected Neural Network regressor with FHE.
: Sparse Quantized Neural Network.
: Implements the RandomForest classifier.
: Implements the RandomForest regressor.
: A Classification Support Vector Machine (SVM).
: A Regression Support Vector Machine (SVM).
: Implements the sklearn DecisionTreeClassifier.
: Implements the sklearn DecisionTreeClassifier.
: Implements the XGBoost classifier.
: Implements the XGBoost regressor.
: Simple enum for different modes of execution of HybridModel.
: Convert a model to a hybrid model.
: Hybrid FHE Model Server.
: Placeholder type for a typical logger like the one from loguru.
: A wrapper class for the modules to be evaluated remotely with FHE.
: Backward module for linear layers.
: Custom linear module.
: Custom autograd function for forward and backward passes.
: Forward module for linear layers.
: LoraTraining module for fine-tuning with LoRA in a hybrid model setting.
: General interface to transform a torch.nn.Module to numpy module.
: sklearn.utils.check_X_y with an assert.
: sklearn.utils.check_X_y with an assert and multi-output handling.
: sklearn.utils.check_array with an assert.
: Provide a custom assert to check that the condition is False.
: Provide a custom assert to check that a piece of code is never reached.
: Provide a custom assert to check that the condition is True.
: Define a custom object hook that enables loading any supported serialized values.
: Dump any Concrete ML object in a file.
: Dump any object as a string.
: Dump the value into a custom dict format.
: Load any Concrete ML object that provide a load_dict
method.
: Load any Concrete ML object that provide a dump_dict
method.
: Indicate if all unpacked values are of a supported float dtype.
: Indicate if all unpacked values are of a supported integer dtype.
: Indicate if all unpacked values are of the specified dtype(s).
: Check if two numpy arrays are equal within a tolerances and have the same shape.
: Check whether the device string for compilation or FHE execution is CUDA or CPU.
: Check whether the device string is valid or raise an exception.
: Convert any allowed type into an array and cast it if required.
: Check whether the circuit can be executed on the required device.
: Check the user did not set p_error or global_p_error in configuration.
: Compute the number of bits required to represent x.
: Generate a proxy function for a function accepting only *args type arguments.
: Return the class of the model (instantiated or not), which can be a partial() instance.
: Return the name of the model, which can be a partial() instance.
: Return the ONNX opset_version.
: Check if a model is a Brevitas type.
: Indicate if the model class represents a classifier.
: Indicate if a model class, which can be a partial() instance, is an element of a_list.
: Indicate if the input container is a Pandas DataFrame.
: Indicate if the input container is a Pandas Series.
: Indicate if the input container is a Pandas DataFrame or Series.
: Indicate if the model class represents a regressor.
: Return (p_error, global_p_error) that we want to give to Concrete.
: Check and process the rounding_threshold_bits parameter.
: Sanitize arg_name, replacing invalid chars by _.
: Make the input a tuple if it is not already the case.
: Check that current versions match the ones used in development.
: Fuse sequence of matmul -> add into a gemm node.
: Get the numpy equivalent forward of the provided ONNX model.
: Get the numpy equivalent forward of the provided ONNX model for tree-based models only.
: Get the numpy equivalent forward of the provided torch Module.
: Preprocess the ONNX model to be used for numpy execution.
: Compute the output shape of a pool or conv operation.
: Compute any additional padding needed to compute pooling layers.
: Pad a tensor according to ONNX spec, using an optional custom pad value.
: Compute the average pooling normalization constant.
: Comparison operation using round_bit_pattern
function.
: Remove the nodes following first node matching node_op_type from the ONNX graph.
: Remove the first node matching node_op_type and its following nodes from the ONNX graph.
: Convert the first Gather node to a matrix multiplication node.
: Keep the outputs given in outputs_to_keep and remove the others from the model.
: Remove identity nodes from a model.
: Remove unnecessary nodes from the ONNX graph.
: Remove unused Constant nodes in the provided onnx model.
: Simplify an ONNX model, removes unused Constant nodes and Identity nodes.
: Check an ONNX model, handling large models (>2GB) by using external data.
: Execute the provided ONNX graph on the given inputs.
: Execute the provided ONNX graph on the given inputs for tree-based models only.
: Get the attribute from an ONNX AttributeProto.
: Construct the qualified type name of the ONNX operator.
: Remove initializers from model inputs.
: Cast values to floating points.
: Compute abs in numpy according to ONNX spec.
: Compute acos in numpy according to ONNX spec.
: Compute acosh in numpy according to ONNX spec.
: Compute add in numpy according to ONNX spec.
: Compute asin in numpy according to ONNX spec.
: Compute sinh in numpy according to ONNX spec.
: Compute atan in numpy according to ONNX spec.
: Compute atanh in numpy according to ONNX spec.
: Compute Average Pooling using Torch.
: Compute the batch normalization of the input tensor.
: Execute ONNX cast in Numpy.
: Compute celu in numpy according to ONNX spec.
: Apply concatenate in numpy according to ONNX spec.
: Return the constant passed as a kwarg.
: Compute N-D convolution using Torch.
: Compute cos in numpy according to ONNX spec.
: Compute cosh in numpy according to ONNX spec.
: Compute div in numpy according to ONNX spec.
: Compute elu in numpy according to ONNX spec.
: Compute equal in numpy according to ONNX spec.
: Compute equal in numpy according to ONNX spec and cast outputs to floats.
: Compute erf in numpy according to ONNX spec.
: Compute exponential in numpy according to ONNX spec.
: Flatten a tensor into a 2d array.
: Compute Floor in numpy according to ONNX spec.
: Compute Gemm in numpy according to ONNX spec.
: Compute greater in numpy according to ONNX spec.
: Compute greater in numpy according to ONNX spec and cast outputs to floats.
: Compute greater or equal in numpy according to ONNX spec.
: Compute greater or equal in numpy according to ONNX specs and cast outputs to floats.
: Compute hardsigmoid in numpy according to ONNX spec.
: Compute hardswish in numpy according to ONNX spec.
: Compute identity in numpy according to ONNX spec.
: Compute leakyrelu in numpy according to ONNX spec.
: Compute less in numpy according to ONNX spec.
: Compute less in numpy according to ONNX spec and cast outputs to floats.
: Compute less or equal in numpy according to ONNX spec.
: Compute less or equal in numpy according to ONNX spec and cast outputs to floats.
: Compute log in numpy according to ONNX spec.
: Compute matmul in numpy according to ONNX spec.
: Compute Max in numpy according to ONNX spec.
: Compute Max Pooling using Torch.
: Compute Min in numpy according to ONNX spec.
: Compute mul in numpy according to ONNX spec.
: Compute Negative in numpy according to ONNX spec.
: Compute not in numpy according to ONNX spec.
: Compute not in numpy according to ONNX spec and cast outputs to floats.
: Compute or in numpy according to ONNX spec.
: Compute or in numpy according to ONNX spec and cast outputs to floats.
: Compute pow in numpy according to ONNX spec.
: Compute relu in numpy according to ONNX spec.
: Compute round in numpy according to ONNX spec.
: Compute selu in numpy according to ONNX spec.
: Compute sigmoid in numpy according to ONNX spec.
: Compute Sign in numpy according to ONNX spec.
: Compute sin in numpy according to ONNX spec.
: Compute sinh in numpy according to ONNX spec.
: Compute softmax in numpy according to ONNX spec.
: Compute softplus in numpy according to ONNX spec.
: Compute sub in numpy according to ONNX spec.
: Compute tan in numpy according to ONNX spec.
: Compute tanh in numpy according to ONNX spec.
: Compute thresholdedrelu in numpy according to ONNX spec.
: Transpose in numpy according to ONNX spec.
: Compute Unfold using Torch.
: Compute the equivalent of numpy.where.
: Compute the equivalent of numpy.where.
: Decorate a numpy onnx function to flag the raw/non quantized inputs.
: Compute rounded equal in numpy according to ONNX spec for tree-based models only.
: Compute rounded less in numpy according to ONNX spec for tree-based models only.
: Compute rounded less or equal in numpy according to ONNX spec for tree-based models only.
: Load a serialized encrypted data-frame.
: Merge two encrypted data-frames in FHE using Pandas parameters.
: Check that the given object can properly be serialized.
: Reduce size of the given data-set.
: Select n_sample
random elements from a 2D NumPy array.
: Get the pytest parameters to use for testing all models available in Concrete ML.
: Get the pytest parameters to use for testing linear models.
: Get the pytest parameters to use for testing neighbor models.
: Get the pytest parameters to use for testing neural network models.
: Get the pytest parameters to use for testing tree-based models.
: Instantiate any Concrete ML model type.
: Load an object saved with torch.save() from a file or dict.
: Determine if both data-frames are identical.
: Indicate if two values are equal.
: Convert the n_bits parameter into a proper dictionary.
: Fill a parameter set structure from kwargs parameters.
: Get the quantized module of a given model in FHE, simulated or not.
: Add transpose after last node.
: Assert if an Add node with a specific constant exists in the ONNX graph.
: Create ONNX model with Hummingbird convert method.
: Build a FHE-compliant onnx-model using a fitted scikit-learn model.
: Apply post-processing from the graph.
: Apply pre-processing onto the ONNX graph.
: Convert the tree inference to a numpy functions using Hummingbird.
: Pre-process tree values.
: Workaround to fix torch issue that does not export the proper axis in the ONNX squeeze node.
: Build a quantized module from a Torch or ONNX model.
: Compile a Brevitas Quantization Aware Training model.
: Compile a torch module into an FHE equivalent.
: Compile a torch module into an FHE equivalent.
: Convert a torch tensor or a numpy array to a numpy array.
: Check if a torch model has QNN layers.
: Convert all Conv1D layers in a module or a Conv1D layer itself to nn.Linear.
: Convert a tuple to a string representation.
: Convert a a string representation of a tuple to a tuple.
: Get names of modules to be executed remotely.
fp32 accuracy
68.70%
83.32%
88.06%
3-bit accuracy
56.44%
55.54%
56.50%
mean accumulator size
6.6
6.9
7.4
torch.nn.Linear
brevitas.quant.QuantLinear
torch.nn.Conv2d
brevitas.quant.Conv2d
torch.nn.AvgPool2d
torch.nn.AvgPool2d
+ brevitas.quant.QuantIdentity
torch.nn.ReLU
brevitas.quant.QuantReLU
torch.transpose
torch.add
(between two activation tensors)
torch.reshape
torch.flatten
3-bit accuracy brevitas
95.4%
3-bit accuracy in Concrete ML
95.4%
Accumulator size
7
3-bit accuracy
82.50%
88.06%
Mean accumulator size
6.6
6.8
GPU support | ✅ | ✅ | ✅ | ❌ |
Quantization is the process of constraining an input from a continuous or otherwise large set of values (such as real numbers) to a discrete set (such as integers).
This means that some accuracy in the representation is lost (e.g., a simple approach is to eliminate least-significant bits). In many cases in machine learning, it is possible to adapt the models to give meaningful results while using these smaller data types. This significantly reduces the number of bits necessary for intermediary results during the execution of these machine learning models.
Since FHE is currently limited to 16-bit integers, it is necessary to quantize models to make them compatible. As a general rule, the smaller the bit-width of integer values used in models, the better the FHE performance. This trade-off should be taken into account when designing models, especially neural networks.
Quantization implemented in Concrete ML is applied in two ways:
Built-in models apply quantization internally and the user only needs to configure some quantization parameters. This approach requires little work by the user but may not be a one-size-fits-all solution for all types of models. The final quantized model is FHE-friendly and ready to predict over encrypted data. In this setting, Post-Training Quantization (PTQ) is used for linear models, data quantization is used for tree-based models and, finally, Quantization Aware Training (QAT) is included in the built-in neural network models.
For custom neural networks with more complex topology, obtaining FHE-compatible models with good accuracy requires QAT. Concrete ML offers the possibility for the user to perform quantization before compiling to FHE. This can be achieved through a third-party library that offers QAT tools, such as Brevitas for PyTorch. In this approach, the user is responsible for implementing a full-integer model, respecting FHE constraints. Please refer to the advanced QAT tutorial for tips on designing FHE neural networks.
While Concrete ML quantizes machine learning models, the data that the client has is often in floating point. Concrete ML models provide APIs to quantize inputs and de-quantize outputs.
Note that the floating point input is quantized in the clear, meaning it is converted to integers before being encrypted. The model's outputs are also integers and decrypted before de-quantization.
Let be the range of a value to quantize where is the minimum and is the maximum. To quantize a range of floating point values (in ) to integer values (in ), the first step is to choose the data type that is going to be used. Many ML models work with weights and activations represented as 8-bit integers, so this will be the value used in this example. Knowing the number of bits that can be used for a value in the range , the scale
can be computed :
where is the number of bits (). In the following, is assumed.
In practice, the quantization scale is then . This means the gap between consecutive representable values cannot be smaller than , which, in turn, means there can be a substantial loss of precision. Every interval of length will be represented by a value within the range .
The other important parameter from this quantization schema is the zero point
value. This essentially brings the 0 floating point value to a specific integer. If the quantization scheme is asymmetric (quantized values are not centered in 0), the resulting will be in .
When using quantized values in a matrix multiplication or convolution, the equations for computing the result become more complex. The IntelLabs Distiller documentation provides a more detailed explanation of the maths used to quantize values and how to keep computations consistent.
Machine learning acceleration solutions are often based on integer computation of activations. To make quantization computations hardware-friendly, a popular approach is to ensure that scales are powers-of-two, which allows the replacement of the division in the equations above with a shift-right operation. TFHE also has a fast primitive for right bit-shift that enables acceleration in the special case of power-of-two scales.
Built-in models provide a simple interface for configuring quantization parameters, most notably the number of bits used for inputs, model weights, intermediary values, and output values.
For linear models, the quantization is done post-training. Thus, the model is trained in floating point, and then, the best integer weight representations are found, depending on the distribution of inputs and weights. For these models, the user selects the value of the n_bits
parameter.
For linear models, n_bits
is used to quantize both model inputs and weights. Depending on the number of features, you can use a single integer value for the n_bits
parameter (e.g., a value between 2 and 7). When the number of features is high, the n_bits
parameter should be decreased if you encounter compilation errors. It is also possible to quantize inputs and weights with different numbers of bits by passing a dictionary to n_bits
containing the op_inputs
and op_weights
keys.
For tree-based models, the training and test data is quantized. The maximum accumulator bit-width for a model trained with n_bits=n
for this type of model is known beforehand: It will need n+1
bits. Through experimentation, it was determined that, in many cases, a value of 5 or 6 bits gives the same accuracy as training in floating point and values above n=7
do not increase model performance (but rather induce a strong slowdown).
Tree-based models can directly control the accumulator bit-width used. If 6 or 7 bits are not sufficient to obtain good accuracy on your data-set, one option is to use an ensemble model (RandomForest or XGBoost) and increase the number of trees in the ensemble. This, however, will have a detrimental impact on FHE execution speed.
For built-in neural networks, several linear layers are used. Thus, the outputs of a layer are used as inputs to a new layer. Built-in neural networks use Quantization Aware Training. The parameters controlling the maximum accumulator bit-width are the number of weights and activation bits ( module__n_w_bits
, module__n_a_bits
), but also the pruning factor. This factor is determined automatically by specifying a desired accumulator bit-width module__n_accum_bits
and, optionally, a multiplier factor, module__n_hidden_neurons_multiplier
.
For built-in neural networks, the maximum accumulator bit-width cannot be precisely controlled. To use many input features and a high number of bits is beneficial for model accuracy, but it can conflict with the 16-bit accumulator constraint. Finding the best quantization parameters to maximize accuracy, while keeping the accumulator size down, can only be accomplished through experimentation.
The models implemented in Concrete ML provide features to let the user quantize the input data and de-quantize the output data.
In a client/server setting, the client is responsible for quantizing inputs before sending them, encrypted, to the server. The client must then de-quantize the encrypted integer results received from the server. See the Production Deployment section for more details.
Here is a simple example showing how to perform inference, starting from float values and ending up with float values. The FHE engine that is compiled for ML models does not support data batching.
Alternatively, the forward
method groups the quantization, FHE execution and de-quantization steps all together.
IntelLabs distiller explanation of quantization: Distiller documentation
Compilation of a model produces machine code that executes the model on encrypted data. In some cases, notably in the client/server setting, the compilation can be done by the server when loading the model for serving.
As FHE execution is much slower than execution on non-encrypted data, Concrete ML has a simulation mode which can help to quickly evaluate the impact of FHE execution on models.
Concrete ML implements model inference using Concrete as a backend. In order to execute in FHE, a numerical program written in Concrete needs to be compiled. This functionality is described here, and Concrete ML hides away most of the complexity of this step, completing the entire compilation process itself.
From the perspective of the Concrete ML user, the compilation process performed by Concrete can be broken up into 3 steps:
tracing the NumPy program and creating a Concrete op-graph
checking the op-graph for FHE compatibility
producing machine code for the op-graph (this step automatically determines cryptographic parameters)
Additionally, the client/server API packages the result of the last step in a way that allows the deployment of the encrypted circuit to a server, as well as key generation, encryption, and decryption on the client side.
Compilation is performed for built-in models with the compile
method :
When using a pipeline, the Concrete ML model can predict with FHE during the pipeline execution, but it needs to be compiled beforehand. The compile function must be called on the Concrete ML model:
For custom models, with one of the compile_brevitas_qat_model
(for Brevitas models with Quantization Aware Training) or compile_torch_model
(PyTorch models using Post-Training Quantization) functions:
The first step in the list above takes a Python function implemented using the Concrete supported operation set and transforms it into an executable operation graph.
The result of this single step of the compilation pipeline allows the:
execution of the op-graph, which includes TLUs, on clear non-encrypted data. This is not secure, but it is much faster than executing in FHE. This mode is useful for debugging, especially when looking for appropriate model hyper-parameters
verification of the maximum bit-width of the op-graph and the intermediary bit-widths of model layers, to evaluate their impact on FHE execution latency
Simulation is enabled for all Concrete ML models once they are compiled as shown above. Obtaining the simulated predictions of the models is done by setting the fhe="simulate"
argument to prediction methods:
Moreover, the maximum accumulator bit-width is determined as follows:
While Concrete ML hides away all the Concrete code that performs model inference, it can be useful to understand how Concrete code works. Here is a toy example for a simple linear regression model on integers to illustrate compilation concepts. Generally, it is recommended to use the built-in models, which provide linear regression out of the box.
Documentation with GitBook is done mainly by pushing content on GitHub. GitBook then pulls the docs from the repository and publishes. In most cases, GitBook is just a mirror of what is available in GitHub.
There are, however, some use-cases where documentation can be modified directly in GitBook (and, then, push the modifications to GitHub), for example when the documentation is modified by a person outside of Zama. In this case, a GitHub branch is created, and a GitHub space is associated to it: modifications are done in this space and automatically pushed to the branch. Once the modifications have been completed, one can simply create a pull-request, to finally merge modifications on the main branch.
Pruning is a method to reduce neural network complexity, usually applied in order to reduce the computation cost or memory size. Pruning is used in Concrete ML to control the size of accumulators in neural networks, thus making them FHE-compatible. See here for an explanation of accumulator bit-width constraints.
Pruning is used in Concrete ML for two types of neural networks:
Built-in neural networks include a pruning mechanism that can be parameterized by the user. The pruning type is based on L1-norm. To comply with FHE constraints, Concrete ML uses unstructured pruning, as the aim is not to eliminate neurons or convolutional filters completely, but to decrease their accumulator bit-width.
Custom neural networks, to work well under FHE constraints, should include pruning. When implemented with PyTorch, you can use the framework's pruning mechanism (e.g., L1-Unstructured) to good effect.
In neural networks, a neuron computes a linear combination of inputs and learned weights, then applies an activation function.
The neuron computes:
When building a full neural network, each layer will contain multiple neurons, which are connected to the inputs or to the neuron outputs of a previous layer.
For every neuron shown in each layer of the figure above, the linear combinations of inputs and learned weights are computed. Depending on the values of the inputs and weights, the sum - which for Concrete ML neural networks is computed with integers - can take a range of different values.
To respect the bit-width constraint of the FHE table lookup, the values of the accumulator must remain small to be representable using a maximum of 16 bits. In other words, the values must be between 0 and .
Pruning a neural network entails fixing some of the weights to be zero during training. This is advantageous to meet FHE constraints, as irrespective of the distribution of , multiplying these input values by 0 does not increase the accumulator value.
Fixing some of the weights to 0 makes the network graph look more similar to the following:
While pruning weights can reduce the prediction performance of the neural network, studies show that a high level of pruning (above 50%) can often be applied. See here how Concrete ML uses pruning in Fully Connected Neural Networks.
In the formula above, in the worst case, the maximum number of the input and weights that can make the result exceed bits is given by:
Here, is the maximum precision allowed.
For example, if and with , the worst case scenario occurs when all inputs and weights are equal to their maximal value . There can be at most elements in the multi-sums.
The distribution of the weights of a neural network is Gaussian, with many weights either 0 or having a small value. This enables exceeding the worst case number of active neurons without having to risk overflowing the bit-width. In built-in neural networks, the parameter n_hidden_neurons_multiplier
is multiplied with to determine the total number of non-zero weights that should be kept in a neuron.
Internally, Concrete ML uses ONNX operators as intermediate representation (or IR) for manipulating machine learning models produced through export for PyTorch, Hummingbird, and skorch.
As ONNX is becoming the standard exchange format for neural networks, this allows Concrete ML to be flexible while also making model representation manipulation easy. In addition, it allows for straight-forward mapping to NumPy operators, supported by Concrete to use Concrete stack's FHE-conversion capabilities.
The diagram below gives an overview of the steps involved in the conversion of an ONNX graph to an FHE-compatible format (i.e., a format that can be compiled to FHE through Concrete).
All Concrete ML built-in models follow the same pattern for FHE conversion:
The models are trained with sklearn or PyTorch.
All models have a PyTorch implementation for inference. This implementation is provided either by a third-party tool such as Hummingbird or implemented directly in Concrete ML.
The PyTorch model is exported to ONNX. For more information on the use of ONNX in Concrete ML, see here.
The Concrete ML ONNX parser checks that all the operations in the ONNX graph are supported and assigns reference NumPy operations to them. This step produces a NumpyModule
.
Quantization is performed on the NumpyModule
, producing a QuantizedModule
. Two steps are performed: calibration and assignment of equivalent QuantizedOp
objects to each ONNX operation. The QuantizedModule
class is the quantized counterpart of the NumpyModule
.
Once the QuantizedModule
is built, Concrete is used to trace the ._forward()
function of the QuantizedModule
.
Moreover, by passing a user provided nn.Module
to step 2 of the above process, Concrete ML supports custom user models. See the associated FHE-friendly model documentation for instructions about working with such models.
Once an ONNX model is imported, it is converted to a NumpyModule
, then to a QuantizedModule
and, finally, to an FHE circuit. However, as the diagram shows, it is perfectly possible to stop at the NumpyModule
level if you just want to run the PyTorch model as NumPy code without doing quantization.
Note that the NumpyModule
interpreter currently supports the following ONNX operators.
In order to better understand how Concrete ML works under the hood, it is possible to access each model in their ONNX format and then either print it or visualize it by importing the associated file in Netron. For example, with LogisticRegression
:
Concrete ML provides features for advanced users to adjust cryptographic parameters generated by the Concrete stack. This allows users to identify the best trade-off between latency and performance for their specific machine learning models.
Concrete ML makes use of table lookups (TLUs) to represent any non-linear operation (e.g., a sigmoid). TLUs are implemented through the Programmable Bootstrapping (PBS) operation, which applies a non-linear operation in the cryptographic realm.
The result of TLU operations is obtained with a specific tolerance to off-by-one errors. Concrete ML offers the possibility to set the probability of such errors occurring, which influences the cryptographic parameters. The lower the tolerance, the more restrictive the parameters become, making both key generation and, more significantly, FHE execution time slower.
Concrete ML has a simulation mode where the impact of approximate computation of TLUs on the model accuracy can be determined. The simulation is much faster, speeding up model development significantly. The behavior in simulation mode is representative of the behavior of the model on encrypted data.
In Concrete ML, there are three different ways to define the tolerance to off-by-one errors for each TLU operation:
setting p_error
, the error probability of an individual TLU (see here)
setting global_p_error
, the error probability of the full circuit (see here)
not setting p_error
nor global_p_error
, and using default parameters (see here)
p_error
and global_p_error
cannot be set at the same time, as they are incompatible with each other.
The first way to set error probabilities in Concrete ML is at the local level, by directly setting the tolerance to error of each individual TLU operation (such as activation functions for a neuron output). This tolerance is referred to as p_error
. A given PBS operation has a 1 - p_error
chance of being correct 100% of the time. The successful evaluation here means that the value decrypted after FHE evaluation is exactly the same as the one that would be computed in the clear. Otherwise, off-by-one errors might occur, but, in practice, these errors are not necessarily problematic if they are sufficiently rare.
For simplicity, it is best to use default options, irrespective of the type of model. Especially for deep neural networks, default values may be too pessimistic, reducing computation speed without any improvement in accuracy. For deep neural networks, some TLU errors might not affect the accuracy of the network, so p_error
can be safely increased (e.g., see CIFAR classifications in our showcase).
Here is a visualization of the effect of the p_error
on a neural network model with a p_error = 0.1
compared to execution in the clear (i.e., no error):
Varying p_error
in the one hidden-layer neural network above produces the following inference times. Increasing p_error
to 0.1 halves the inference time with respect to a p_error
of 0.001. In the graph above, the decision boundary becomes noisier with a higher p_error
.
The speedup depends on model complexity, but, in an iterative approach, it is possible to search for a good value of p_error
to obtain a speedup while maintaining good accuracy. Concrete ML provides a tool to find a good value for p_error
based on binary search.
Users have the possibility to change this p_error
by passing an argument to the compile
function of any of the models. Here is an example:
If the p_error
value is specified and simulation is enabled, the run will take into account the randomness induced by the choice of p_error
. This results in statistical similarity to the FHE evaluation.
A global_p_error
is also available and defines the probability of 100% correctness for the entire model, compared to execution in the clear. In this case, the p_error
for every TLU is determined internally in Concrete such that the global_p_error
is reached for the whole model.
There might be cases where the user encounters a No cryptography parameter found
error message. Increasing the p_error
or the global_p_error
in this case might help.
Usage is similar to the p_error
parameter:
In the above example, XGBoostClassifier in FHE has a 1/10 probability to have a one-off output value compared to the expected value. The shift is relative to the expected value, so even if the result is different, it should be close to the expected value.
If neither p_error
or global_p_error
are set, Concrete ML employs p_error = 2^-40
by default.
Currently finding a good p_error
value a-priori is not possible, as it is difficult to determine the impact of the TLU error on the output of a neural network. Concrete ML provides a tool to find a good p_error
value that improves inference speed while maintaining accuracy. The method is based on binary search and evaluates the latency/accuracy trade-off iteratively.
With this optimal p_error
, accuracy is maintained while execution time is improved by a factor of 1.51.
Please note that the default setting for the search interval is restricted to a range of 0.0 to 0.9. Increasing the upper bound beyond this range may result in longer execution times, especially when p_error≈1
.
To speed-up neural networks, a rounding operator can be applied on the accumulators of linear and convolution layers to retain the most significant bits on which the activation and quantization is applied. The accumulator is represented using bits, and is the desired input bit-width of the TLU operation that computes the activation and quantization.
The rounding operation is defined as follows:
First, compute as the difference between , the actual bit-width of the accumulator, and :
Then, the rounding operation can be computed as:
where is the input number, and denotes the operation that rounds to the nearest integer.
In Concrete ML, this feature is currently implemented for custom neural networks through the compile functions, including
concrete.ml.torch.compile_torch_model
,
concrete.ml.torch.compile_onnx_model
and
concrete.ml.torch.compile_brevitas_qat_model
.
The rounding_threshold_bits
argument can be set to a specific bit-width. It is important to choose an appropriate bit-width threshold to balance the trade-off between speed and accuracy. By reducing the bit-width of intermediate tensors, it is possible to speed-up computations while maintaining accuracy.
The rounding_threshold_bits
parameter only works in FHE for TLU input bit-width () less or equal to 8 bits.
To find the best trade-off between speed and accuracy, it is recommended to experiment with different thresholds and check the accuracy on an evaluation set after compiling the model.
In practice, the process looks like this:
Set a rounding_threshold_bits
to a relatively high P. Say, 8 bits.
Check the accuracy
Update P = P - 1
repeat steps 2 and 3 until the accuracy loss is above a certain, acceptable threshold.
An example of such implementation is available in evaluate_torch_cml.py and CifarInFheWithSmallerAccumulators.ipynb
By using verbose = True
and show_mlir = True
during compilation, the user receives a lot of information from Concrete. These options are, however, mainly meant for power-users, so they may be hard to understand.
Here, one will see:
the computation graph (typically):
the MLIR, produced by Concrete:
information from the optimizer (including cryptographic parameters):
In this latter optimization, the following information will be provided:
The bit-width ("6-bit integers") used in the program: for the moment, the compiler only supports a single precision (i.e., that all PBS are promoted to the same bit-width - the largest one). Therefore, this bit-width predominantly drives the speed of the program, and it is essential to reduce it as much as possible for faster execution.
The maximal norm2 ("7 manp"), which has an impact on the crypto parameters: The larger this norm2, the slower PBS will be. The norm2 is related to the norm of some constants appearing in your program, in a way which will be clarified in the Concrete documentation.
The probability of error of an individual PBS, which was requested by the user ("3.300000e-02 error per pbs call" in User Config).
The probability of error of the full circuit, which was requested by the user ("1.000000e+00 error per circuit call" in User Config). Here, the probability 1 stands for "not used", since we had set the individual probability via p_error
.
The probability of error of an individual PBS, which is found by the optimizer ("1/30 errors (3.234529e-02)").
The probability of error of the full circuit which is found by the optimizer ("1/10 errors (9.390887e-02)").
An estimation of the cost of the circuit ("4.214000e+02 Millions Operations"): Large values indicate a circuit that will execute more slowly.
Here is some further information about cryptographic parameters:
1x glwe_dimension
2**11 polynomial (2048)
762 lwe dimension
keyswitch l,b=5,3
blindrota l,b=2,15
wopPbs : false
This optimizer feedback is a work in progress and will be modified and improved in future releases.
Concrete ML has support for quantized ML models and also provides quantization tools for Quantization Aware Training and Post-Training Quantization. The core of this functionality is the conversion of floating point values to integers and back. This is done using QuantizedArray
in concrete.ml.quantization
.
The class takes several arguments that determine how float values are quantized:
n_bits
defines the precision used in quantization
values
are floating point values that will be converted to integers
is_signed
determines if the quantized integer values should allow negative values
is_symmetric
determines if the range of floating point values to be quantized should be taken as symmetric around zero
See also the reference for more information:
It is also possible to use symmetric quantization, where the integer values are centered around 0:
In the following example, showing the de-quantization of model outputs, the QuantizedArray
class is used in a different way. Here it uses pre-quantized integer values and has the scale
and zero-point
set explicitly. Once the QuantizedArray
is constructed, calling dequant()
will compute the floating point values corresponding to the integer values qvalues
, which are the output of the fhe_circuit.encrypt_run_decrypt(..)
call.
Machine learning models are implemented with a diverse set of operations, such as convolution, linear transformations, activation functions, and element-wise operations. When working with quantized values, these operations cannot be carried out in an equivalent way to floating point values. With quantization, it is necessary to re-scale the input and output values of each operation to fit in the quantization domain.
In Concrete ML, the quantized equivalent of a scikit-learn model or a PyTorch nn.Module
is the QuantizedModule
. Note that only inference is implemented in the QuantizedModule
, and it is built through a conversion of the inference function of the corresponding scikit-learn or PyTorch module.
Built-in neural networks expose the quantized_module
member, while a QuantizedModule
is also the result of the compilation of custom models through compile_torch_model
and compile_brevitas_qat_model
.
Calibration is the process of determining the typical distributions of values encountered for the intermediate values of a model during inference.
The section gave an overview of the conversion of a generic ONNX graph to an FHE-compatible Concrete ML op-graph. This section describes the implementation of operations in the Concrete ML op-graph and the way floating point can be used in some parts of the op-graphs through table lookup operations.
Concrete, the underlying implementation of TFHE that powers Concrete ML, enables two types of operations on integers:
arithmetic operations: the addition of two encrypted values and multiplication of encrypted values with clear scalars. These are used, for example, in dot-products, matrix multiplication (linear layers), and convolution.
table lookup operations (TLU): using an encrypted value as an index, return the value of a lookup table at that index. This is implemented using Programmable Bootstrapping. This operation is used to perform any non-linear computation such as activation functions, quantization, and normalization.
Since machine learning models use floating point inputs and weights, they first need to be converted to integers using .
Alternatively, it is possible to use a table lookup to avoid the quantization of the entire graph, by converting floating-point ONNX subgraphs into lambdas and computing their corresponding lookup tables to be evaluated directly in FHE. This operator-fusion technique only requires the input and output of the lambdas to be integers.
For example, in the following graph there is a single input, which must be an encrypted integer tensor. The following series of univariate functions is then fed into a matrix multiplication (MatMul) and fused into a single table lookup with integer inputs and outputs.
Concrete ML implements ONNX operations using Concrete, which can handle floating point operations, as long as they can be fused to an integer lookup table. The ONNX operations implementations are based on the QuantizedOp
class.
There are two modes of creation of a single table lookup for a chain of ONNX operations:
float mode: when the operation can be fused
mixed float/integer: when the ONNX operation needs to perform arithmetic operations
Thus, QuantizedOp
instances may need to quantize their inputs or the result of their computation, depending on their position in the graph.
The QuantizedOp
class provides a generic implementation of an ONNX operation, including the quantization of inputs and outputs, with the computation implemented in NumPy in ops_impl.py
. It is possible to picture the architecture of the QuantizedOp
as the following structure:
Depending on the position of the op in the graph and its inputs, the QuantizedOp
can be fully fused to a TLU.
Many ONNX ops are trivially univariate, as they multiply variable inputs with constants or apply univariate functions such as ReLU, Sigmoid, etc. This includes operations between the input and the MatMul in the graph above (subtraction, comparison, multiplication, etc. between inputs and constants).
Operations, such as matrix multiplication of encrypted inputs with a constant matrix or convolution with constant weights, require that the encrypted inputs be integers. In this case, the input quantizer of the QuantizedOp
is applied. These types of operations are implemented with a class that derives from QuantizedOp
and implements q_impl
, such as QuantizedGemm
and QuantizedConv
.
Finally, some operations produce graph outputs, which must be integers. These operations need to quantize their outputs as follows:
The diagram above shows that both float ops and integer ops need to quantize their outputs to integers when placed at the end of the graph.
To chain the operation types described above following the ONNX graph, Concrete ML constructs a function that calls the q_impl
of the QuantizedOp
instances in the graph in sequence, and uses Concrete to trace the execution and compile to FHE. Thus, in this chain of function calls, all groups of that instruction that operate in floating point will be fused to TLUs. In FHE, this lookup table is computed with a PBS.
The red contours show the groups of elementary Concrete instructions that will be converted to TLUs.
Note that the input is slightly different from the QuantizedOp
. Since the encrypted function takes integers as inputs, the input needs to be de-quantized first.
QuantizedOp
QuantizedOp
is the base class for all ONNX-quantized operators. It abstracts away many things to allow easy implementation of new quantized ops.
The QuantizedOp
class exposes a function can_fuse
that:
helps to determine the type of implementation that will be traced.
determines whether operations further in the graph, that depend on the results of this operation, can fuse.
In most cases, ONNX ops have a single variable input and one or more constant inputs.
When the op implements element-wise operations between the inputs and constants (addition, subtract, multiplication, etc), the operation can be fused to a TLU. Thus, by default in QuantizedOp
, the can_fuse
function returns True
.
When the op implements operations that mix the various scalars in the input encrypted tensor, the operation cannot fuse, as table lookups are univariate. Thus, operations such as QuantizedGemm
and QuantizedConv
return False
in can_fuse
.
Some operations may be found in both settings above. A mechanism is implemented in Concrete ML to determine if the inputs of a QuantizedOp
are produced by a unique integer tensor. Therefore, the can_fuse
function of some QuantizedOp
types (addition, subtraction) will allow fusion to take place if both operands are produced by a unique integer tensor:
You can check ops_impl.py
to see how some operations are implemented in NumPy. The declaration convention for these operations is as follows:
The required inputs should be positional arguments only before the /
, which marks the limit of the positional arguments.
The optional inputs should be positional or keyword arguments between the /
and *
, which marks the limits of positional or keyword arguments.
The operator attributes should be keyword arguments only after the *
.
The proper use of positional/keyword arguments is required to allow the QuantizedOp
class to properly populate metadata automatically. It uses Python inspect modules and stores relevant information for each argument related to its positional/keyword status. This allows using the Concrete implementation as specifications for QuantizedOp
, which removes some data duplication and generates a single source of truth for QuantizedOp
and ONNX-NumPy implementations.
In that case (unless the quantized implementation requires special handling like QuantizedGemm
), you can just set _impl_for_op_named
to the name of the ONNX op for which the quantized class is implemented (this uses the mapping ONNX_OPS_TO_NUMPY_IMPL
in onnx_utils.py
to get the correct implementation).
Providing an integer implementation requires sub-classing QuantizedOp
to create a new operation. This sub-class must override q_impl
in order to provide an integer implementation. QuantizedGemm
is an example of such a case where quantized matrix multiplication requires proper handling of scales and zero points. The q_impl
of that class reflects this.
In the body of q_impl
, you can use the _prepare_inputs_with_constants
function in order to obtain quantized integer values:
Here, prepared_inputs
will contain one or more QuantizedArray
, of which the qvalues
are the quantized integers.
Once the required integer processing code is implemented, the output of the q_impl
function must be implemented as a single QuantizedArray
. Most commonly, this is built using the de-quantized results of the processing done in q_impl
.
In this case, in q_impl
you can check whether the current operation can be fused by calling self.can_fuse()
. You can then have both a floating-point and an integer implementation. The traced execution path will depend on can_fuse()
:
Before you start this section, you must install Docker by following official guide.
Once you have access to this repository and the dev environment is installed on your host OS (via make setup_env
once ), you should be able to launch the commands to build the dev Docker image with make docker_build
.
Once you do that, you can get inside the Docker environment using the following command:
After you finish your work, you can leave Docker by using the exit
command or by pressing CTRL + D
.
is a third-party, open-source library that converts machine learning models into tensor computations, and it can export these models to ONNX. The list of supported models can be found in .
Concrete ML allows the conversion of an ONNX inference to NumPy inference (note that NumPy is always the entry point to run models in FHE with Concrete ML).
Hummingbird exposes a convert
function that can be imported as follows from the hummingbird.ml
package:
This function can be used to convert a machine learning model to an ONNX as follows:
In theory, the resulting onnx_model
could be used directly within Concrete ML's get_equivalent_numpy_forward
method (as long as all operators present in the ONNX model are implemented in NumPy) and get the NumPy inference.
In practice, there are some steps needed to clean the ONNX output and make the graph compatible with Concrete ML, such as applying quantization where needed or deleting/replacing non-FHE friendly ONNX operators (such as Softmax and ArgMax).
This wrapper implements Torch training boilerplate code, lessening the work required of the user. It is possible to add hooks during the training phase, for example once an epoch is finished.
While Brevitas provides many types of quantization, for Concrete ML, a custom "mixed integer" quantization applies. This "mixed integer" quantization is much simpler than the "integer only" mode of Brevitas. The "mixed integer" network design is defined as:
all weights and activations of convolutional, linear and pooling layers must be quantized (e.g., using Brevitas layers, QuantConv2D
, QuantAvgPool2D
, QuantLinear
)
For "mixed integer" quantization to work, the first layer of a Brevitas nn.Module
must be a QuantIdentity
layer. However, you can then use functions such as torch.sigmoid
on the result of such a quantizing operation.
For examples of such a "mixed integer" network design, please see the Quantization Aware Training examples:
Concrete ML is a Python
library, so Python
should be installed to develop Concrete ML. v3.8
and v3.9
are the only supported versions. Concrete ML also uses Poetry
and Make
.
First of all, you need to git clone
the project:
In order to be able to run all documentation examples, we recommend to also and then pull the necessary files :
On the contrary, to disable downloading all these files (which represents up to several hundreds of MB) when cloning the repository, simply run :
A simple way to have everything installed is to use the development Docker (see the guide). On Linux and macOS, you have to run the script in ./script/make_utils/setup_os_deps.sh
. Specify the --linux-install-python
flag if you want to install python3.8 as well on apt-enabled Linux distributions. The script should install everything you need for Docker and bare OS development (you can first review the content of the file to check what it will do).
For Windows users, the setup_os_deps.sh
script does not install dependencies because of how many different installation methods there are due to the lack of a single package manager.
The first step is to (as some of the dev tools depend on it), then . In addition to installing Python, you are still going to need the following software available on path on Windows, as some of the basic dev tools depend on them:
git
jq
make
Development on Windows only works with the Docker environment. Follow .
The dev tools use make
to launch various commands.
On Linux, you can install make
from your distribution's preferred package manager.
On macOS, you can install a more recent version of make
via brew:
In the following sections, be sure to use the proper make
tool for your system: make
, gmake
, or other.
To get the source code of Concrete ML, clone the code repository using the link for your favorite communication protocol (ssh or https).
We are going to make use of virtual environments. This helps to keep the project isolated from other Python
projects in the system. The following commands will create a new virtual environment under the project directory and install dependencies to it.
The following command will not work on Windows if you don't have Poetry >= 1.2.
Finally, activate the newly created environment using the following command:
Docker automatically creates and sources a venv in ~/dev_venv/
The venv persists thanks to volumes. It also creates a volume for ~/.cache to speedup later reinstallations. You can check which Docker volumes exist with:
You can still run all make
commands inside Docker (to update the venv, for example). Be mindful of the current venv being used (the name in parentheses at the beginning of your command prompt).
After your work is done, you can simply run the following command to leave the environment:
From time to time, new dependencies will be added to the project or the old ones will be removed. The command below will make sure the project has the proper environment, so run it regularly!
If you are having issues, consider using the dev Docker exclusively (unless you are working on OS-specific bug fixes or features).
Here are the steps you can take on your OS to try and fix issues:
Here are the steps you can take in your Docker to try and fix issues:
If the problem persists at this point, you should ask for help. We're here and ready to assist!
p_error | Inference Time (ms) |
---|---|
The quantized versions of floating point model operations are stored in the QuantizedModule
. The ONNX_OPS_TO_QUANTIZED_IMPL
dictionary maps ONNX floating point operators (e.g., Gemm) to their quantized equivalent (e.g., QuantizedGemm). For more information on implementing these operations, please see the .
The computation graph is taken from the corresponding floating point ONNX graph exported from scikit-learn , or from the ONNX graph exported by PyTorch. Calibration is used to obtain quantized parameters for the operations in the QuantizedModule
. Parameters are also determined for the quantization of inputs during model deployment.
To perform calibration, an interpreter goes through the ONNX graph in and stores the intermediate results as it goes. The statistics of these values determine quantization parameters.
That QuantizedModule
generates the Concrete function that is compiled to FHE. The compilation will succeed if the intermediate values conform to the 16-bits precision limit of the Concrete stack. See for details.
Lei Mao's blog on quantization:
Google paper on neural network quantization and integer-only inference:
This figure shows that the QuantizedOp
has a body that implements the computation of the operation, following the . The operation's body can take either integer or float inputs and can output float or integer values. Two quantizers are attached to the operation: one that takes float inputs and produces integer inputs and one that does the same for the output.
Concrete ML uses to implement multi-layer, fully-connected PyTorch neural networks in a way that is compatible with the scikit-learn API.
skorch allows the user to easily create a classifier or regressor around a neural network (NN), implemented in Torch as a nn.Module
, which is used by Concrete ML to provide a fully-connected, multi-layer NN with a configurable number of layers and optional pruning (see and the for more information).
Under the hood, Concrete ML uses a skorch wrapper around a single PyTorch module, SparseQuantNeuralNetwork
. More information can be found .
is a quantization aware learning toolkit built on top of PyTorch. It provides quantization layers that are one-to-one equivalents to PyTorch layers, but also contain operations that perform the quantization during training.
PyTorch floating-point versions of univariate functions can be used (e.g., torch.relu
, nn.BatchNormalization2D
, torch.max
(encrypted vs. constant), torch.add
, torch.exp
). See the for a full list.
The "mixed integer" mode used in Concrete ML neural networks is based on the that makes both weights and activations representable as integers during training. However, through the use of lookup tables in Concrete ML, floating point univariate PyTorch functions are supported.
You can also refer to the class, which is the basis of the built-in NeuralNetworkClassifier
.
To manually install Python, you can follow guide (alternatively, you can google how to install Python 3.8 (or 3.9)
).
Poetry
is used as the package manager. It drastically simplifies dependency and environment management. You can follow official guide to install it.
It is possible to install gmake
as make
. Check this for more info.
On Windows, check .
At this point, you should consider using Docker as nobody will have the exact same setup as you. If, however, you need to develop on your OS directly, you can .
0.001
0.80
0.01
0.41
0.1
0.37
Importing ONNX
Quantization tools
FHE op-graph design
External libraries
Concrete ML is a constant work-in-progress, and thus may contain bugs or suboptimal APIs.
Before opening an issue or asking for support, please read this documentation to understand common issues and limitations of Concrete ML. You can also check the outstanding issues on github.
Furthermore, undefined behavior may occur if the input-set, which is internally used by the compilation core to set bit-widths of some intermediate data, is not sufficiently representative of the future user inputs. With all the inputs in the input-set, it appears that intermediate data can be represented as an n-bit integer. But, for a particular computation, this same intermediate data needs additional bits to be represented. The FHE execution for this computation will result in an incorrect output, as typically occurs in integer overflows in classical programs.
If you didn't find an answer, you can ask a question through the community channels.
When submitting an issue (here), ideally include as much information as possible. In addition to the Python script, the following information is useful:
the reproducibility rate you see on your side
any insight you might have on the bug
any workaround you have been able to find
If you would like to contribute to a project and send pull requests, take a look at the contributor guide.
Concrete ML supports a wide range of models through the integration of ONNX nodes. In case a specific ONNX node is missing, developers need to add support for the new ONNX nodes.
The ops_impl.py
file is responsible for implementing the computation of ONNX operators using floating-point arithmetic. The implementation should mirror the behavior of the corresponding ONNX operator precisely. This includes adhering to the expected inputs, outputs, and operational semantics.
Refer to the ONNX documentation to grasp the expected behavior, inputs and outputs of the operator.
After implementing the operator in ops_impl.py
, you need to import it into onnx_utils.py
and map it within the ONNX_OPS_TO_NUMPY_IMPL
dictionary. This mapping is crucial for the framework to recognize and utilize the new operator.
Quantized operators are defined in quantized_ops.py
and are used to handle integer arithmetic. Their implementation is required for the new ONNX to be executed in FHE.
There exist two types of quantized operators:
Univariate Non-Linear Operators: Such operator applies transformation on every element of the input without changing its shape. Sigmoid, Tanh, ReLU are examples of such operation. The sigmoid in this file is simply supported as follows:
Linear Layers: Linear layers like Gemm
and Conv
require specific implementations for integer arithmetic. Please refer to the QuantizedGemm
and QuantizedConv
implementations for reference.
Proper testing is essential to ensure the correctness of the new ONNX node support.
There are many locations where tests can be added:
test_onnx_ops_impl.py
: Tests the implementation of the ONNX node in floating points.
test_quantized_ops.py
: Tests the implementation of the ONNX node in integer arithmetic.
Optional: test_compile_torch.py
: Tests the implementation of a specific torch model that contains the new ONNX operator. The model needs to be added in torch_models.py
.
Finally, update the documentation to reflect the newly supported ONNX node.
There are three ways to contribute to Concrete ML:
You can open issues to report bugs and typos and to suggest ideas.
You can become an official contributor but you need to sign our Contributor License Agreement (CLA) on your first contribution. Our CLA-bot will guide you through the process when you will open a Pull Request on Github.
You can also provide new tutorials or use-cases, showing what can be done with the library. The more examples we have, the better and clearer it is for the other users.
First, you need to fork the Concrete ML repository and properly set up the project by following the steps provided here.
When creating your branch, make sure the name follows the expected format :
For example:
Each commit to Concrete ML should conform to the standards of the project. You can let the development tools fix some issues automatically with the following command:
Additionally, you will need to make sure that the following command does not return any error (pcc
: pre-commit checks):
Your code must be well documented, provide extensive tests if any feature has been added and must not break other tests. To execute all tests, please run the following command. Be aware that running all tests can take up to an hour.
You need to make sure you get 100% code coverage. The make pytest
command checks that by default and will fail with a coverage report at the end should some lines of your code not be executed during testing.
If your coverage is below 100%, you should write more tests and then create the pull request. If you ignore this warning and create the PR, checks will fail and your PR will not be merged.
There may be cases where covering your code is not possible (an exception that cannot be triggered in normal execution circumstances). In those cases, you may be allowed to disable coverage for some specific lines. This should be the exception rather than the rule, and reviewers will ask why some lines are not covered. If it appears they can be covered, then the PR won't be accepted in that state.
Concrete ML uses a consistent commit naming scheme and you are expected to follow it as well. The accepted format can be printed to your terminal by running:
For example:
Just a reminder that commit messages are checked in the conformance step and are rejected if they don't follow the rules. To learn more about conventional commits, check this page.
You should rebase on top of the repository's main
branch before you create your pull request. Merge commits are not allowed, so rebasing on main
before pushing gives you the best chance of to avoid rewriting parts of your PR later if conflicts arise with other PRs being merged. After you commit changes to your forked repository, you can use the following commands to rebase your main branch with Concrete ML's one:
You can learn more about rebasing here.
You can now open a pull-request in the Concrete ML repository. For more details on how to do so from a forked repository, please read GitHub's official documentation on the subject.
Fundamentals
Explore core features.
Guides
Deploy your projects.
Tutorials
Learn more with tutorials.