> For the complete documentation index, see [llms.txt](https://docs.zama.org/concrete-ml/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.zama.org/concrete-ml/0.2/developper-explanations/skorch_usage.md).

# Skorch Usage

We use [skorch](https://skorch.readthedocs.io/en/stable/) to implement multi-layer, fully-connected torch neural networks in **Concrete-ML** in a way that is compatible with the scikit-learn API.

This wrapper implements torch training boilerplate code, alleviating the work that needs to be done by the user. It is possible to add hooks during the training phase, for example once an epoch is finished.

Skorch allows the user to easily create a classifier or regressor around a neural network (NN), implemented in Torch as a `nn.Module`. We provide a simple, fully-connected, multi-layer NN with a configurable number of layers and optional pruning (see [pruning](/concrete-ml/0.2/explanations/pruning.md)).

The `SparseQuantNeuralNetImpl` class implements this neural network. Please see the documentation on this class [in the API guide](https://github.com/zama-ai/concrete-ml/blob/release/0.2.x/docs/_apidoc/concrete.ml.sklearn.html#concrete.ml.sklearn.qnn.SparseQuantNeuralNetImpl).

```
class SparseQuantNeuralNetImpl(nn.Module):
    """Sparse Quantized Neural Network classifier.
```

The constructor of this class takes some parameters that influence FHE compatibility:

* `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` (default 7): maximum accumulator bit width to impose through pruning
* `n_hidden_neurons_multiplier` (default 4): explained below

A linear or convolutional layer of an NN will compute a linear combination of weights and inputs (we also call this a *'multi-sum'*). For example, a linear layer will compute:

$$output^k = \sum\_i^Nw\_{i}^kx\_i$$

where $$k$$ is the k-th neuron in the layer. In this case, the sum is taken on a single dimension. A convolutional layer will compute:

$$output\_{xy}^{k} = \sum\_c^{N}\sum\_j^{K\_h}\sum\_i^{K\_w}w\_{cji}^kx\_{c,y+j,x+i}^k$$

where $$k$$ is the k-th filter of the convolutional layer and $$N$$, $$K\_h$$, $$K\_w$$ are the number of input channels, the kernel height and the kernel width, respectively.

Following the formulas for the resulting bit width of quantized linear combinations described [here](/concrete-ml/0.2/how-to/reduce_needed_precision.md), notably the maximum dimensionality of the input and weights that can make the result exceed 7 bits:

$$\Omega = \mathsf{floor} \left( \frac{2^{n\_{\mathsf{max}}} - 1}{(2^{n\_{\mathsf{weights}}} - 1)(2^{n\_{\mathsf{inputs}}} - 1)} \right)$$

where $$n\_{\mathsf{max}} = 7$$ is the maximum precision allowed.

For example, we set $$n\_{\mathsf{weights}} = 2$$ and $$n\_{\mathsf{inputs}} = 2$$ with $$n\_{\mathsf{max}} = 7$$. The worst case is a scenario where all inputs and weights are equal to their maximal value $$2^2-1=3$$. The formula above tells us that, in this case, we can afford at most $$\Omega = 14$$ elements in the multi-sums detailed above.

In a practical setting, the distribution of the weights of a neural network is Gaussian. Thus, there will be weights that are equal to 0 and many weights will have small values. In a typical scenario, we can exceed the worst-case number of active neurons. The parameter `n_hidden_neurons_multiplier` is a factor that is multiplied with $$\Omega$$ to determine the total number of non-zero weights that should be kept in a neuron.

The pruning mechanism is already implemented in `SparseQuantNeuralNetImpl`, and the user only needs to determine the parameters listed above. They can choose them in a way that is convenient, e.g. maximizing accuracy.

The skorch wrapper requires that all the parameters that will be passed to the wrapped `nn.Module` be prefixed with `module__`. For example, the code to create an FHE-compatible **Concrete-ML** fully-connected NN classifier for a dataset with 10 input dimensions and two classes, will thus be:

```python
n_inputs = 10
n_outputs = 2
params = {
    "module__n_layers": 2,
    "module__n_w_bits": 2,
    "module__n_a_bits": 2,
    "module__n_accum_bits": 7,
    "module__n_hidden_neurons_multiplier": 1,
    "module__n_outputs": n_outputs,
    "module__input_dim": n_inputs,
    "module__activation_function": nn.ReLU,
    "max_epochs": 10,
}

concrete_classifier = NeuralNetClassifier(**params)
```

We could then increase `n_hidden_neurons_multiplier` to improve performance, taking care to verify that the compiled NN does not exceed 7 bits of accumulator bit width.

A similar example is given in the [classifier comparison notebook](https://github.com/zama-ai/concrete-ml/blob/release/0.2.x/docs/user/advanced_examples/ClassifierComparison.ipynb).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.zama.org/concrete-ml/0.2/developper-explanations/skorch_usage.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
