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...
Concrete ML models and data-frames can be easily deployed in a client/server setting, enabling the creation of privacy-preserving services in the cloud.
As seen in the concepts section, once compiled to FHE, a Concrete ML model or data-frame generates machine code that execute prediction, training or pre-processing on encrypted data. Secret encryption keys are needed so that the user can securely encrypt their data and decrypt the execution result. An evaluation key is also needed for the server to securely process the user's encrypted data.
Keys are generated by the user once for each service they use, based on the model the service provides and its cryptographic parameters.
The overall communications protocol to enable cloud deployment of machine learning services can be summarized in the following diagram:
The steps detailed above are:
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. Crypto-graphic parameters and compiled programs for data-frames are included directly in Concrete ML.
The client requests the cryptographic parameters (also called "client specs"). Once it receives them from the server, the secret and evaluation keys are generated.
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 data-frames include client evaluation keys.
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.
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.
Not all hardware/OS combinations are supported. Determine your platform, OS version, and Python version before referencing the table below.
Depending on your OS, Concrete ML may be installed with Docker or with pip:
OS / HW | Available on Docker | Available on pip |
---|---|---|
Only some versions of python
are supported: In the current release, these are 3.8
, 3.9
and 3.10
. The Concrete ML Python package requires glibc >= 2.28
. On Linux, you can check your glibc
version by running ldd --version
.
Concrete ML can be installed on Kaggle (see question on community for more details) 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).
Installing on Windows can be done using 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.
If you encounter any issue during installation on Apple Silicon mac, please visit this troubleshooting guide on community.
Concrete ML can be installed using Docker by either pulling the latest image or a specific version:
The image can be used with Docker volumes, see the Docker documentation here.
The image can then be used via the following command:
This will launch a Concrete ML enabled Jupyter server in Docker that can be accessed directly from a browser.
Alternatively, a shell can be lauched in Docker, with or without volumes:
Linux
Yes
Yes
Windows
Yes
Not currently
Windows Subsystem for Linux
Yes
Yes
macOS 11+ (Intel)
Yes
Yes
macOS 11+ (Apple Silicon: M1, M2, etc.)
Yes
Yes
Concrete ML is built on top of Concrete, which enables NumPy programs to be converted into FHE circuits.
Concrete ML models can be trained on clear or encrypted data, then deployed to predict on encrypted inputs. During deployment data pre-processing can be done on encrypted data. Therefore, data can be 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: The model is converted into an integer equivalent using quantization. Concrete ML performs this step either during training (Quantization Aware Training) or after training (Post-training Quantization), depending on model type. Quantization converts inputs, model weights, and all intermediate values of the inference computation to integers. More information is available here.
simulation: Testing FHE models on very large data-sets can take a long time. Furthermore, not all models are compatible with FHE constraints out of the box. Simulation allows you to execute a model that was quantized, to measure the accuracy it would have in FHE, but also to determine the modifications required to make it FHE compatible. Simulation is described in more detail here.
compilation: Once the model is quantized, simulation can confirm it has good accuracy in FHE. 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 can encrypt data and store it in a data-frame for further processing on a server. The server can pre-process such data, to prepare it for encrypted training or inference. Clients generate keys, encrypt and decrypt data-frames, while the Concrete ML-enabled server has pre-compiled circuits that perform pre-processing.
client/server model deployment: In a client/server setting, Concrete ML models can be exported in a way that:
allows the client to generate keys, encrypt, and decrypt.
provides 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 key (to encrypt/decrypt their data and results) and 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 are tools that hide away the details of the underlying cryptography scheme, called TFHE. However, some cryptography concepts are still useful when using these two toolkits:
encryption/decryption: These operations transform plaintext (i.e., human-readable information) into ciphertext (i.e., data that contains a form of the original plaintext that is unreadable by a human or computer without the proper key to decrypt it). Encryption takes plaintext and an encryption key and produces ciphertext, while decryption is the inverse operation.
encrypted inference: FHE allows a third party to execute (i.e., run inference or predict) a machine learning model on encrypted data (a ciphertext). The result of the inference is also encrypted and can only be read by the person who receives the decryption key.
key generation: Cryptographic keys need to be generated using random number generators. Their size may be large and key generation may take a long time. However, keys only need to be generated once for each model used by a client.
private key: A private 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 achieve security, TFHE, the underlying encryption scheme, adds random noise to ciphertexts. This can induce errors during processing of encrypted data, depending on noise parameters. By default, Concrete ML uses parameters that ensure the correctness of the encrypted computation, so there is no need to account for noise parametrization. Therefore, the results on encrypted data will be the same as the results of simulation on clear data.
While Concrete ML users only need to understand the cryptography concepts above, for a deeper understanding of the cryptography behind the Concrete stack, please see the whitepaper on TFHE and Programmable Boostrapping or this series of blogs.
To respect FHE constraints, all numerical programs that include non-linear operations over encrypted data must have all inputs, constants, and intermediate values represented with integers of a maximum of 16 bits.
Concrete ML quantizes the input data and model outputs in the same way as weights and activations. The main levers to control accumulator bit-width are the number of bits used for the inputs, weights, and activations of the model. These parameters are crucial to comply with the constraint on accumulator bit-widths. Please refer to the quantization documentation for more details about how to develop models with quantization in Concrete ML.
These methods may cause a reduction in the accuracy of the model since its representative power is diminished. Carefully choosing a quantization approach can alleviate accuracy loss, all the while allowing compilation to FHE. Concrete ML offers built-in models that include quantization algorithms, and users only need to configure some of their parameters, such as the number of bits, discussed above. See the advanced quantization guide for information about configuring these parameters for various models.
Additional specific methods can help to make models compatible with FHE constraints. For instance, dimensionality reduction can reduce the number of input features and, thus, the maximum accumulator bit-width reached within a circuit. Similarly, sparsity-inducing training methods, such as pruning, deactivate some features during inference. For now, dimensionality reduction is considered as a pre-processing step, while pruning is used in the built-in neural networks.
The configuration of model quantization parameters is illustrated in the advanced examples for Linear and Logistic Regressions and dimensionality reduction is shown in the Poisson regression example.
Concrete ML provides several of the most popular linear models for regression
and classification
that can be found in scikit-learn:
Concrete ML | scikit-learn |
---|---|
Using these models in FHE is extremely similar to what can be done with scikit-learn's API, making it easy for data scientists who have used this framework to get started with Concrete ML.
Models are also compatible with some of scikit-learn's main workflows, such as Pipeline()
and GridSearch()
.
It is possible to convert an already trained scikit-learn linear model to a Concrete ML one by using the from_sklearn_model
method. See below for an example. This functionality is only available for linear models.
The n_bits
parameter controls the bit-width of the inputs and weights of the linear models. When non-linear mapping is applied by the model, such as exp or sigmoid, Concrete ML applies it on the client-side, on clear-text values that are the decrypted output of the linear part of the model. Thus, Linear Models do not use table lookups, and can, therefore, use high precision integers for weight and inputs.
The n_bits
parameter can be set to 8
or more bits for models with up to 300
input dimensions. When the input has more dimensions, n_bits
must be reduced to 6-7
. All performance metrics are preserved down to n_bits=6
, compared to the non-quantized float models from scikit-learn.
The same quantization parameters (i.e., scale and zero-point) are applied on all features, so it can be beneficial to make all feature distribution similar by using standard or min-max normalization. For a more detailed comparison of the impact of such pre-processing please refer to the logistic regression notebook.
The following snippet gives an example about training a LogisticRegression model on a simple data-set followed by inference on encrypted data with FHE. A more complete example can be found in the LogisticRegression notebook.
We can then plot the decision boundary of the classifier and compare those results with a scikit-learn model executed in clear. The complete code can be found 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 are able to consider large precision numbers when quantizing inputs and weights in Concrete ML. Additionally, as the linear models do not use PBS, the FHE computations are always exact. This means 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.
Concrete ML provides simple built-in neural networks models 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 (i.e., the underlying nn.Module
), must have the prefix. 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 figure above right shows the Concrete ML neural network, trained with Quantization Aware Training in an FHE-compatible configuration. The figure compares this network to the floating-point equivalent, trained with scikit-learn.
module__n_layers
: number of layers in the FCNN, 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 (e.g., nn.ReLU, see the full list 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 (i.e., setting some weights to zero)
power_of_two_scaling
(default True): forces quantization scales to be powers-of-two, which, when coupled with the ReLU activation, benefits from strong FHE inference time optimization. See this section in the quantization documentation for more details.
max_epochs
: The number of epochs to train the network (default 10)
verbose
: Whether to log loss/metrics during training (default: False)
lr
: Learning rate (default 0.001)
Other parameters from skorch can be found in the skorch documentation.
module__n_hidden_neurons_multiplier
: The number of hidden neurons will be automatically set proportional to the dimensionality of the input. This parameter controls the proportionality factor and is set to 4 by default. 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 as it controls the number of non-zero neurons that are allowed in each layer. Increasing n_accum_bits
improves accuracy, but should take into account precision limitations to avoid an overflow in the accumulator. The default value is a good compromise that avoids an overflow in most cases, but you may want to change the value of this parameter to reduce the breadth of the network if you have overflow errors.
Furthermore, the number of neurons on intermediate layers is controlled through the n_hidden_neurons_multiplier
parameter - a value of 1 will make intermediate layers have the same number of neurons as the number of dimensions of the input data.
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.
We value your feedback! Take a 5-question developer survey to improve the Concrete ML library and the documentation and help other developers use FHE.
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:
automatically turn machine learning models into their FHE equivalent, using familiar APIs from scikit-learn and PyTorch (see how this works for linear models, tree-based models, and neural networks).
train models on encrypted data.
pre-process encrypted data through a data-frame paradigm
Fully Homomorphic Encryption 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. You can learn more about FHE in this introduction or by joining the FHE.org community.
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 linear models, including logistic regression, that are trained using federated learning using the from_sklearn
function.
Here is a simple example of classification on encrypted data using logistic regression. More examples can be found here.
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.
This example shows the typical flow of a Concrete ML model:
The model is trained on unencrypted (plaintext) data using scikit-learn. As FHE operates over integers, Concrete ML quantizes the model to use only integers during inference.
The quantized model is compiled to an FHE equivalent. Under the hood, the model is first converted to a Concrete Python program, then compiled.
Inference can then be done on encrypted data. The above example shows encrypted inference in the model-development phase. Alternatively, during deployment in a client/server setting, the data is encrypted by the client, processed securely by the server, and then decrypted by the client.
To make a model work with FHE, the only constraint is to make it run within the supported precision limitations of Concrete ML (currently 16-bit integers). Thus, machine learning models must be quantized, which sometimes leads to a loss of accuracy versus the original model, which operates on plaintext.
Additionally, Concrete ML currently only supports training on encrypted data for some models, while it supports inference for a large variety of models.
Finally, there is currently no support for 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, and the mixing of results of ensemble models.
These issues are currently being addressed, and significant improvements are expected to be released in the near future.
Concrete ML is built on top of Zama's Concrete.
Various tutorials are available for built-in models and deep learning. Several stand-alone demos for use cases can be found in the Demos and Tutorials section.
If you have built awesome projects using Concrete ML, feel free to let us know and we'll link to your work!
Support forum: https://community.zama.ai (we answer in less than 24 hours).
Live discussion on the FHE.org Discord server: https://discord.fhe.org (inside the #concrete channel).
Do you have a question about Zama? Write us on Twitter or send us an email at: hello@zama.ai
Concrete ML provides several of the most popular classification
and regression
tree models that can be found in scikit-learn:
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
As the maximum depth parameter of decision trees and tree-ensemble models strongly increases the number of nodes in the trees, we recommend using the XGBoost models which achieve better performance with lower depth.
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. A more complete example can be found in the XGBClassifier notebook.
Similarly, the decision boundaries of the Concrete ML model can be plotted and compared to the results of the classical XGBoost model executed in the clear. A 6-bit model is shown in order to illustrate the impact of quantization on classification. Similar plots can be found in the Classifier Comparison notebook.
This graph above shows that, when using a sufficiently high bit-width, quantization has little impact on the decision boundaries of the Concrete ML FHE decision tree models. As quantization is done individually on each input feature, the impact of quantization is strongly reduced. This means that FHE tree-based models reach a similar level of accuracy as their floating point equivalents. Using 6 bits for quantization means that the Concrete ML model reaches, or exceeds, the floating point accuracy. The number of bits for quantization can be adjusted through the n_bits
parameter.
When n_bits
is set to a low value, the quantization process may sometimes create some artifacts that could lead to a decrease in accuracy. At the same time, the execution speed in FHE could improve. In this way, it is possible to adjust the accuracy/speed trade-off, and some accuracy can be recovered 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.
Concrete ML offers nearest neighbors non-parametric classification models with a scikit-learn interface through the KNeighborsClassifier
class.
Concrete ML | scikit-learn |
---|---|
The KNeighborsClassifier
class quantizes the training data-set that is given to .fit
with the specified number of bits, n_bits
. As this value must be kept low to comply with accumulator size constraints the accuracy of the model will depend heavily a well-chosen value n_bits
and the dimensionality of the data.
The predict
method of the KNeighborsClassifier
performs the following steps:
quantization of the test vectors, performed in the clear
computation of the top-k class indices of the closest training set vector, on encrypted data
majority vote of the top-k class labels to find the class for each test vector, performed in the clear
The FHE inference latency of this model is heavily influenced by the n_bits
, the dimensionality of the data. Furthermore, the size of the data-set has a linear impact on the complexity of the data and the number of nearest neighbors, n_neighbors
, also plays a role.
The KNN computation executes in FHE in steps, where is the training data-set size and is n_neighbors
. Each step requires several PBS, but the run-time of each of these PBS is influenced by the factors listed above. These factors combine to give the precision required to represent the distances between test vectors and the training data-set vectors. The PBS input precision required by the circuit is related to the one of the distance values.
Concrete ML offers the possibility to train on encrypted data. The example shows this feature in action.
This example 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. 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:
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 linear models, including logistic regression, that are trained using federated learning using the .
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 logistic model that can be trained uses Stochastic Gradient Descent (SGD) and quantizes for data, weights, gradients and the error measure. It currently supports training 6-bit models, training both the coefficients and the bias.
The SGDClassifier
does not currently support training models with other values for the bit-widths. 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.
This section provides a set of tools and guidelines to help users build optimized FHE-compatible models. It discusses FHE simulation, the key-cache functionality that helps speed-up FHE result debugging, and gives a guide to evaluate circuit complexity.
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:
Compilation errors that signal that the ML model is not FHE compatible are usually of two types:
TLU input maximum bit-width is exceeded
No crypto-parameters can be found for the ML model: RuntimeError: NoParametersFound
is raised by the compiler
The following produces a neural network that is not FHE-compatible:
Upon execution, the Compiler will raise the following error within the graph representation:
To make this network FHE-compatible one can apply several techniques:
reduce the accumulator bit-width of the second layer named fc2
. To do this, a simple solution is to reduce the number of neurons, as it is proportional to the bit-width.
In FHE, univariate functions are encoded as table lookups, which are then implemented using Programmable Bootstrapping (PBS). PBS is a powerful technique but will require significantly more computing resources, and thus time, compared to simpler encrypted operations such as matrix multiplications, convolution, or additions.
Furthermore, the cost of PBS will depend on the bit-width of the compiled circuit. Every additional bit in the maximum bit-width raises the complexity of the PBS by a significant factor. It may be of interest to the model developer, then, to determine the bit-width of the circuit and the amount of PBS it performs.
This can be done by inspecting the MLIR code produced by the Compiler:
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. Their inputs in the listing above are: tensor<1x2x!FHE.eint<8>>
for the first and last call and tensor<1x50x!FHE.eint<8>>
for the two calls in the middle. Thus, PBS is applied 104 times.
Retrieving the bit-width of the circuit is then simply:
Decreasing the number of bits and the number of PBS applications induces large reductions in the computation time of the compiled circuit.
In addition to the built-in models, Concrete ML supports generic machine learning models implemented with Torch, or .
As is the most appropriate method of training neural networks that are compatible with , Concrete ML works with , a library providing QAT support for PyTorch.
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.
Converting neural networks to use FHE can be done with compile_brevitas_qat_model
or with compile_torch_model
for post-training quantization. If the model can not be converted to FHE two types of errors can be raised: (1) crypto-parameters can not be found and, (2) table look-up bit-width limit is exceeded. See the if you encounter these errors.
The PyTorch/Brevitas models, created following the example above, require the user to configure quantization parameters such as bit_width
(activation bit-width) and weight_bit_width
. The quantization parameters, along with the number of neurons on each layer, will determine the accumulator bit-width of the network. Larger accumulator bit-widths result in higher accuracy but slower FHE inference time.
The following configurations were determined through experimentation for convolutional and dense layers.
Using the templates above, the probability of obtaining the target accumulator bit-width, for a single layer, was determined experimentally by training 10 models for each of the following data-sets.
Note that the accuracy on larger data-sets, when the accumulator size is low, is also reduced strongly.
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 (resp. de-quantization) step is done in the clear within the forward
method, before (resp. after) any FHE computations.
The user can also perform the inference on clear data. Two approaches exist:
quantized_module.forward(quantized_x, fhe="simulate")
: 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")
: 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.
While the example above shows how to import a Brevitas/PyTorch model, Concrete ML also provides an option to import generic QAT models implemented in PyTorch or through ONNX. Deep learning models made with TensorFlow or Keras should be usable by preliminary converting them to ONNX.
QAT models contain quantizers in the PyTorch graph. These quantizers ensure that the inputs to the Linear/Dense and Conv layers are quantized.
When importing QAT models using this generic pipeline, a representative calibration set should be given as quantization parameters in the model need to be inferred from the statistics of the values encountered during inference.
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.
This guide provides a complete example of converting a PyTorch neural network into its FHE-friendly, quantized counterpart. It focuses on Quantization Aware Training a simple network on a synthetic data-set.
In general, quantization can be carried out in two different ways: either during Quantization Aware Training (QAT) or after the training phase with Post-Training Quantization (PTQ).
Regarding FHE-friendly neural networks, QAT is the best way to reach optimal accuracy under . This technique allows weights and activations to be reduced to very low bit-widths (e.g., 2-3 bits), which, combined with pruning, can keep accumulator bit-widths low.
Concrete ML uses the third-party library to perform QAT for PyTorch NNs, but options exist for other frameworks such as Keras/Tensorflow.
Several that use Brevitas are available in the Concrete ML library, such as the .
This guide is based on a , from which some code blocks are documented.
For a more formal description of the usage of Brevitas to build FHE-compatible neural networks, please see the .
For a formal explanation of the mechanisms that enable FHE-compatible neural networks, please see the the following paper.
In PyTorch, using standard layers, a fully connected neural network (FCNN) would look like this:
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 of 6.6 means that 4 times out of 10 the accumulator measured 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 irrespective of the number of neurons. While all the configurations tried here were FHE-compatible (accumulator < 16 bits), it is often preferable to have a lower accumulator size in order to speed up inference time.
Accumulator size is determined by Concrete as being the maximum bit-width encountered anywhere in the encrypted circuit.
Brevitas provides a quantized version of almost all PyTorch layers (Linear
layer becomes QuantLinear
, ReLU
layer becomes QuantReLU
and so on), plus some extra 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
In order to use FHE, the network must be quantized from end to end, and thanks to the Brevitas's QuantIdentity
layer, it is possible to quantize the input by placing it at the entry point of the network. Moreover, it is also possible to combine PyTorch and Brevitas layers, provided that a QuantIdentity
is placed after this PyTorch layer. The following table gives the replacements to be made to convert a PyTorch NN 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) with 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.
Quantization Aware Training is somewhat slower than normal training. QAT introduces quantization during both the forward and backward passes. The quantization process is inefficient on GPUs as its computational intensity is low with respect 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.
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.
Concrete ML builds upon the pandas data-frame functionality by introducing the capability to construct and perform operations on encrypted data-frames using FHE. This API ensures data scientists can leverage well-known pandas-like operations while maintaining privacy throughout the whole process.
Encrypted data-frames are a storage format for encrypted tabular data and they can be exchanged with third-parties without security risks.
Potential applications include:
Encrypted storage of tabular datasets
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
, you must construct a ClientEngine
which manages keys. Then call the encrypt_from_pandas
function:
Concrete ML's encrypted DataFrame
operations support a specific set of data types:
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.
Outsourced execution: The merge operation on Encrypted DataFrames can be securely performed on a third-party server. This means that the server can execute the merge without ever having access to the unencrypted data. The server only requires the encrypted DataFrames.
Encrypted DataFrames support a subset of operations that are available for pandas DataFrames. The following operations are currently supported:
merge
: left or right join two data-frames
Security: Serialized data-frames do not contain any secret keys. The data-frames can be exchanged with any third-party without any risk.
To save or load an encrypted DataFrame
from a file, use the following commands:
The library is designed to raise specific errors when encountering issues during the pre-processing and post-processing stages:
ValueError
: Raised when a column contains values outside the allowed range for integers, when there are too many unique strings, or when encountering an unsupported data type. Raised also when an operation is attempted on a data type that is not supported by the operation.
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.
In addition to Concrete ML models and , it is also possible to directly compile models. This can be particularly appealing, notably to import models trained with Keras.
ONNX models can be compiled by directly importing models that are already quantized with Quantization Aware Training (QAT) or by performing Post-Training Quantization (PTQ) 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 Post-Training Quantization, i.e., the quantization is not performed during training. This model would not have good performance in FHE. Quantization Aware Training should be added by the model developer. Additionally, importing QAT ONNX models can be done .
While Keras was used in this example, it is not officially supported. Additional work is needed to test all of Keras's types of layers and models.
The following operators are supported 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
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
The error this 17-bit value is used as an input to a table lookup
indicates that the 16-bit limit on the input of the Table Lookup (TLU) operation has been exceeded. To pinpoint the model layer that causes the error, Concrete ML provides the helper function. First, the model must be compiled so that it can be .
use by specifying the rounding_threshold_bits
parameter. Please evaluate the accuracy of the model using simulation if you use this feature, as it may impact accuracy. Setting a value 2-bit higher than the quantization n_bits
should be a good start.
adjust the tolerance for one-off errors using the p_error
parameter. See on this tolerance.
Once the model is trained, calling the from Concrete ML will automatically perform conversion and compilation of a QAT network. Here, 3-bit quantization is used for both the weights and activations. The compile_brevitas_qat_model
function automatically identifies the number of quantization bits used in the Brevitas model.
target accumulator bit-width | activation bit-width | weight bit-width | number of active neurons |
---|
FHE simulation allows to measure the impact of the Table Lookup error on the model accuracy. The Table Lookup error can be adjusted using p_error
/global_p_error
, as described in the section.
Suppose that n_bits_qat
is the bit-width of activations and weights during the QAT process. To import a PyTorch QAT network, you can use the library function, passing import_qat=True
:
Alternatively, if you want to import an ONNX model directly, please see . The also supports the import_qat
parameter.
-- for casting to dtype
-- partial support
The , example shows how to train a FCNN, similarly to the one above, 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, this PyTorch network can be imported using the function. This function uses simple PTQ.
neurons | 10 | 30 | 100 |
---|
using is the best way to guarantee a good accuracy for Concrete ML compatible neural networks.
PyTorch fp32 layer | Concrete ML model with PyTorch/Brevitas |
---|
PyTorch ops that require QuantIdentity |
---|
Non-zero neurons | 30 |
---|
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 (e.g., ). 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 where the developer can impose a number of zero-valued weights. Torch out of the box.
Non-zero neurons | 10 | 30 |
---|
Encrypted DataFrame
objects can be serialized to a file format for storage or transfer. When serialized, they contain the encrypted data and necessary to perform computations.
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 .
Models trained using 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 that are configured during training to a specific number of bits, the ONNX graph will need to be imported using the same settings:
8 | 3 | 3 | 80 |
10 | 4 | 3 | 90 |
12 | 5 | 5 | 110 |
14 | 6 | 6 | 110 |
16 | 7 | 6 | 120 |
probability of obtaining the accumulator bit-width | 8 | 10 | 12 | 14 | 16 |
mnist,fashion | 72% | 100% | 72% | 85% | 100% |
cifar10 | 88% | 88% | 75% | 75% | 88% |
cifar100 | 73% | 88% | 61% | 66% | 100% |
accuracy for target accumulator bit-width | 8 | 10 | 12 | 14 | 16 |
cifar10 | 20% | 37% | 89% | 90% | 90% |
cifar100 | 6% | 30% | 67% | 69% | 69% |
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 |
|
|
|
|
|
|
|
|
|
|
|
|
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 |
Credit card approval: 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 code here
Sentiment analysis with transformers: predicting if an encrypted tweet / short message is positive, negative or neutral, using FHE.
Health diagnosis: 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 code here
Encrypted image filtering: filtering encrypted images by applying filters such as black-and-white, ridge detection, or your own filter.
Check the code here
GPT-2 in FHE: Privacy-preserving text generation based on a user's prompt
Titanic: Train an XGB classifier that can perform encrypted prediction for the Kaggle Titanic competition
Federated learning and private inference: Use federated learning to train a Logistic Regression while preserving training data confidentiality. Import the model into Concrete ML and perform encrypted prediction
Neutral network fine-tuning: Fine-tune a VGG network to classify the CIFAR image data-sets and predict on encrypted data
Encrypted sentiment analysis:A Hugging Face space that securely analyzes the sentiment expressed in a short text
Credit scoring: Predict the chance of a given loan applicant defaulting on loan repayment
Comparison of Concrete ML regressors - June 2023
Encrypted image filtering using homomorphic encryption - February 2023
Sentiment analysis over encrypted data - November 2022
Concrete ML has support for serializing all available built-in models. Using this feature, one can dump a fitted and compiled model into a JSON string or file. The estimator can then be loaded 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 below.
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, one cannot serialize a model that was instantiated using callable objects for the train_split
and predict_nonlinearity
parameters or with callbacks
being enabled.
Loading a built-in model is possible through the following functions:
loads
: loads the model from a string.
load
: loads the model from a file.
A loaded model is required to be compiled once again in order for a user to be able to execute the inference in FHE or with simulation. This is because the underlying FHE circuit is currently not serialized. There is not required when FHE mode is disabled.
The above logistic regression model can therefore be loaded as below.
Neural networks pose unique challenges with regards to encrypted inference. Each neuron in a network applies an activation function that requires a PBS operation. The latency of a single PBS depends on the bit-width of the input of the PBS.
Several approaches can be used to reduce the overall latency of a neural network.
Quantization Aware Training and pruning introduce specific hyper-parameters that influence the accumulator sizes. It is possible to chose quantization and pruning configurations that reduce the accumulator size. A trade-off between latency and accuracy can be obtained by varying these hyper-parameters as described in the deep learning design guide.
While un-structured pruning is used to ensure the accumulator bit-width stays low, structured pruning can eliminate entire neurons from the network. Many neural networks are over-parametrized (since this enables easier training) and some neurons can be removed. Structured pruning, applied to a trained network as a fine-tuning step, can be applied to built-in neural networks using the prune helper function as shown in this example. To apply structured pruning to custom models, it is recommended to use the torch-pruning package.
Reducing the bit-width of the inputs to the Table Lookup (TLU) operations is a major source of improvements in the latency. Post-training, it is possible to leverage some properties of the fused activation and quantization functions expressed in the TLUs to further reduce the accumulator. 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 bring large improvements in latency while maintaining accuracy.
Finally, the TFHE scheme exposes 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. One 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 usage example of the API for finding the best p_error
.
FHE enables cloud applications to process private user data without running the risk of data leaks. Furthermore, deploying ML models in the cloud is advantageous as it eases model updates, allows to scale to large numbers of users by using large amounts of compute power, and protects model IP by keeping the model on a trusted server instead of the client device.
However, not all applications can be easily converted to FHE computation and the computation cost of FHE may make a full conversion exceed latency requirements.
Hybrid models provide a balance between on-device deployment and cloud-based deployment. This approach entails executing parts of the model directly on the client side, while other parts are securely processed with FHE on the server side. Concrete ML facilitates the hybrid deployment of various neural network models, including MLP (multilayer perceptron), CNN (convolutional neural network), and Large Language Models.
If model IP protection is important, care must be taken in choosing the parts of a model to be executed on the cloud. Some black-box model stealing attacks rely on knowledge distillation or on differential methods. As a general rule, the difficulty to steal a machine learning model is proportional to the size of the model, in terms of numbers of parameters and model depth.
The hybrid model deployment API provides an easy way to integrate 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 what part of the PyTorch neural network model must be executed in FHE. The model part must be a nn.Module
and is identified by its key in the original model's .named_modules()
.
The save_and_clear_private_info
function serializes the FHE circuits corresponding to the various parts of the model that were chosen to be moved server-side. It also saves the client-side model, removing the weights of the layers that are transferred server-side. Furthermore it saves all necessary information required to serve these sub-models with FHE, using the FHEModelDev
class.
The FHEModelServer
class should be used to create a server application that creates end-points to serve these sub-models:
For more information about serving FHE models, see the client/server section.
A client application that deploys a model with hybrid deployment can be developed in a very similar manner to on-premise deployment: the model is loaded normally with PyTorch, but an extra step is required to specify the remote endpoint and the model parts that are to be executed remotely.
Next, the client application must 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, it must set the operation mode of the HybridFHEModel
instance to HybridFHEMode.REMOTE
:
When performing inference with the HybridFHEModel
instance, hybrid_model
, only the regular forward
method is called, as if the model was fully deployed locally:
When calling forward
, the HybridFHEModel
handles, for each model part that is deployed remotely, all the necessary intermediate steps: quantizing the data, encrypting it, makes the request to the server using requests
Python module, decrypting and de-quantizing the result.
Concrete ML has APIs that make it easy, during model development and testing, to perform encryption, execution in FHE, and decryption in a single step. For more control, these individual steps can be executed separately. The APIs used to accomplish this are different for:
The following example shows how to create a synthetic data-set and how to use it to train a LogisticRegression model from Concrete ML. Next, we will discuss the dedicated functions for encryption, inference, and decryption.
All Concrete ML built-in models have a monolithic predict
method that performs the encryption, FHE execution, and decryption with a single function call. 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, it is possible to execute all main steps (key generation, quantization, encryption, FHE execution, decryption) separately.
For custom models, the API to execute inference in FHE or simulation is illustrated as:
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.
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
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 Demos and Tutorials 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 simulation to configure the speed/accuracy trade-off for tree-based models and neural networks, using grid-search or your own heuristics.
Linear Regression example Logistic Regression example Linear Support Vector Regression example Linear SVM classification
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.
Poisson Regression example Generalized Linear Models comparison
These two examples show generalized linear models (GLM) on the real-world OpenML insurance data-set. As the non-linear, inverse-link functions are computed, these models do not use PBS, and are, thus, very fast (~1ms execution time).
Using the OpenML spams 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 House Price prediction 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 Diabetes 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 House Prices 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 Iris and compared to a PyTorch floating point network. Second, a larger accumulator (>8 bits) is demonstrated on MNIST.
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.
Concrete ML provides functionality to deploy FHE machine learning models in a client/server setting. The deployment workflow and model serving pattern is as follows:
The diagram above shows the steps that a developer goes through to prepare a model for encrypted inference in a client/server setting. 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 client.specs.json
which lists the secure cryptographic parameters needed for the client to generate private and evaluation keys. It also contains serialized_processing.json
which 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 (i.e., a model compiled on x86 cannot run on ARM).
The compiled model (server.zip
) is deployed to a server and 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.
Note that for built-in models, the server output + post-processing adheres to the following guidelines: if the model is a regressor, the output follows the format of the scikit-learn .predict()
method; if the model is a classifier, the output follows the format of the scikit-learn .predict_proba()
method.
The client-side deployment of a secured inference machine learning model follows the schema above. First, 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. The public evaluation keys are then sent to the server, while the secret key remains on the client.
The private data is then encrypted by the client as described in the serialized_processing.json
file in client.zip
, and it is then sent to the server. Server-side, the FHE model inference is run on encrypted inputs using the public evaluation keys.
The encrypted result is then returned by the server to the client, which decrypts it using its private key. Finally, 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 follows the diagram above. The public evaluation keys sent by clients are stored. They are then retrieved for the client that is querying the service and used to evaluate the machine learning model stored in server.zip
. Finally, 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.
We provide scripts that leverage boto3
to deploy any Concrete ML model to AWS. The first required step is to properly set up AWS CLI on your system, which can be done by following the instructions in AWS Documentation. To create Access keys to configure AWS CLI, go to the appropriate panel on AWS website.
Once this first setup is done you can launch python src/concrete/ml/deployment/deploy_to_aws.py --path-to-model <path_to_your_serialized_model>
from the root of the repository to create an instance that runs a FastAPI server serving the model.
Running Docker with the latest version of Concrete ML will require you to build a Docker image. To do this, run the following command: poetry build && mkdir pkg && cp dist/* pkg/ && make release_docker
. You will need to have make
, poetry
and docker
installed on your system. To test locally there is a dedicated script: python src/concrete/ml/deployment/deploy_to_docker.py --path-to-model <path_to_your_serialized_model>
whoch should be run from the root of the repository in order to create a Docker that runs a FastAPI server serving the model.
No code is required to run the server but each client is specific to the use-case, even if the workflow stays the same. To see how to create your client refer to our examples or this notebook.
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 Demos and Tutorials section.
The examples listed here make use of simulation to perform evaluation over large test sets. Since FHE execution can be slow, only a few FHE executions can be performed. The correctness guarantees 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.
Quantization aware training example
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 Step-by-step guide, 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.
Concrete ML fully supports Pandas, allowing built-in models such as linear and tree-based models to use Pandas dataframes and series just as they would be used with NumPy arrays.
The table below summarizes current compatibility:
Methods | Support Pandas dataframe |
---|---|
The following example considers a LogisticRegression
model on a simple classification problem. A more advanced example can be found in the Titanic use case notebook, which considers a XGBClassifier
.
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.
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:
Several files are tracked by . While a few are required for running some tests, most of them are used for benchmarking and use case examples. By default, git clone
downloads all LFS files, which can add up to several hundreds of MB to the directory. Is it however possible to disable such behavior by running the running the following command instead :
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!
Internally, Concrete ML uses operators as intermediate representation (or IR) for manipulating machine learning models produced through export for , , and .
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 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 .
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 , producing a . Two steps are performed: calibration and assignment of equivalent 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 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.
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.
Documentation can alternatively be built using Sphinx:
The documentation contains both files written by hand by developers (the .md files) and files automatically created by parsing the source files.
Then to open it, go to docs/_build/html/index.html
or use the follwing command:
To build and open the docs at the same time, use:
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.
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 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 )
setting global_p_error
, the error probability of the full circuit (see )
not setting p_error
nor global_p_error
, and using default parameters (see )
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 , 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 ).
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
.
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:
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
.
The rounding operation is defined as follows:
Then, the rounding operation can be computed as:
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.
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.
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.
: 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.
: Methods to deploy a client/server to AWS.
: Methods to deploy a server using Docker.
: APIs for FHE deployment.
: Deployment server.
: Utils.
: 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.
: A torch to numpy module.
: File to manage the version of the package.
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()
:
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 .
Note that the NumpyModule
interpreter currently .
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 . For example, with LogisticRegression
:
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:
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
.
p_error | Inference Time (ms) |
---|
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 .
If the p_error
value is specified and 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.
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.
First, compute as the difference between , the actual bit-width of the accumulator, and :
where is the input number, and denotes the operation that rounds to the nearest integer.
The rounding_threshold_bits
parameter only works in FHE for TLU input bit-width () less or equal to 8 bits.
An example of such implementation is available in and
: 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.
: AWSInstance.
: 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.
: 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.
: 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 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.
: Div 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.
: 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.
: 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.
: Convert any allowed type into an array and cast it if required.
: 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.
: Create a EC2 instance.
: Terminate a AWS EC2 instance.
: Deploy a model to a EC2 AWS instance.
: Deploy a model.
: Terminate a AWS EC2 instance.
: Wait for AWS EC2 instance termination.
: Build server Docker image.
: Delete a Docker image.
: Deploy function.
: Kill all containers that use a given image.
: Check that current versions match the ones used in development.
: Filter logs based on previous logs.
: Check if ssh connection is available.
: Wait for connection to be available.
: 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.
: Get the numpy equivalent forward of the provided ONNX model.
: 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.
: 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.
: 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.
: 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.
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.
fit
✓
compile
✓
predict (fhe="simulate")
✓
predict (fhe="execute")
✓
0.001 | 0.80 |
0.01 | 0.41 |
0.1 | 0.37 |
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.
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 on the Zama forum or in the FHE.org Discord.
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.
Fundamentals
Explore core features.
Guides
Deploy your projects.
Tutorials
Learn more with tutorials.