Skip to content

Base Classes

compile(inputset) treats each item as one integer sample. Use simulate or predict for one sample and simulate_many or predict_many for a sequence.

from concrete_fhe_toolkit.ml import FHELinearRegression

model = FHELinearRegression(weights=[2, 1], bias=1)
model.compile([[0, 0], [5, 5]])
assert int(model.simulate([3, 2])) == 9

# Build a fixed-size batch circuit from individual calibration samples.
model.compile([[0, 0], [5, 5]], batch_size=4, inputset_is_batched=False)
predictions = model.simulate_many([[1, 2], [3, 4], [5, 5]])

For existing prebatched inputsets, compile(batches, batch_size=4) retains its meaning. Alternatively, compile(batches, inputset_is_batched=True) infers the batch size. Partial prediction batches repeat their final sample for padding and discard padded outputs. Calibration samples and runtime samples must have matching shapes and cover the values used during inference.

concrete_fhe_toolkit.ml.classes

Core data structures and definitions for encrypted ML.

FHEModel

Base class for models with single-sample or fixed-batch circuits.

Example
model = FHEModel()
Source code in src/concrete_fhe_toolkit/ml/classes.py
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
class FHEModel:
    """Base class for models with single-sample or fixed-batch circuits.

    Example:
        ```python
        model = FHEModel()
        ```
    """

    def __init__(self):
        """Initializes the FHEModel.

        Returns:
            None
        """
        self.circuit = None
        self.batch_size = 1
        self._batched = False
        self._sample_shape = None

    def _repr_html_(self):
        model_name = self.__class__.__name__

        # Status configurations
        c_color = "#10B981" if self.circuit is not None else "#EF4444"
        c_text = "Compiled" if self.circuit is not None else "Not Compiled"
        c_icon = "✓" if self.circuit is not None else "✕"

        b_color = "#3B82F6" if self._batched else "#6B7280"
        b_text = "Batched" if self._batched else "Not Batched"

        attribute_name = ""
        attribute_value = None
        if hasattr(self, "trees"):
            attribute_name = "Number of Trees"
            attribute_value =  len(self.trees)
        elif hasattr(self, "filters"):
            attribute_name = "Number of Filters"
            attribute_value = len(self.filters)
        elif hasattr(self, "weights"):
            attribute_name = "Number of Weights"
            attribute_value = len(self.weights)
        elif hasattr(self, "k"):
            attribute_name = "Number of Neighbors (k)"
            attribute_value = self.k
        elif hasattr(self, "mlp_layers"):
            attribute_name = "Number of Layers"
            attribute_value = len(self.mlp_layers)
        elif hasattr(self, "centroids"):
            attribute_name = "Number of Centroids"
            attribute_value = len(self.centroids)
        elif hasattr(self, "components"):
            attribute_name = "Number of Components"
            attribute_value = len(self.components) 
        elif hasattr(self, "priors"):
            attribute_name = "Number of Classes"
            attribute_value = len(self.priors)
        elif hasattr(self, "tree"):
            attribute_name = "Tree Depth"

            def tree_depth(node):
                if not isinstance(node, dict):
                    return 0

                depth = 1 + max(tree_depth(node.get("left")), tree_depth(node.get("right")))
                return depth

            attribute_value = tree_depth(self.tree)                          

        extra_html = ""
        if attribute_name != "":
            extra_html = f"""
                <div style="display: flex; justify-content: space-between; align-items: center; border-top: 1px dashed #E5E7EB; padding-top: 12px; margin-top: 4px;">
                    <span style="color: #4B5563; font-size: 14px; font-weight: 500;">{attribute_name}</span>
                    <span style="color: #111827; font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; font-size: 14px; font-weight: 600; background-color: #F3F4F6; padding: 2px 8px; border-radius: 6px;">
                        {attribute_value}
                    </span>
                </div>
            """

        html = f"""
        <div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; border: 1px solid #E5E7EB; border-radius: 12px; padding: 20px; background: linear-gradient(to bottom right, #ffffff, #f8fafc); width: 320px; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03);">
            <div style="display: flex; align-items: center; margin-bottom: 16px; border-bottom: 1px solid #E5E7EB; padding-bottom: 12px;">
                <div style="background-color: #1F2937; color: white; border-radius: 8px; padding: 6px 10px; font-size: 16px; margin-right: 12px;">🤖</div>
                <h3 style="color: #111827; margin: 0; font-size: 18px; font-weight: 600;">{model_name}</h3>
            </div>

            <div style="display: flex; flex-direction: column; gap: 12px;">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <span style="color: #4B5563; font-size: 14px; font-weight: 500;">Compilation</span>
                    <span style="background-color: {c_color}15; color: {c_color}; padding: 4px 10px; border-radius: 9999px; font-size: 12px; font-weight: 600; display: flex; align-items: center; gap: 4px;">
                        <span>{c_icon}</span> {c_text}
                    </span>
                </div>

                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <span style="color: #4B5563; font-size: 14px; font-weight: 500;">Batch State</span>
                    <span style="background-color: {b_color}15; color: {b_color}; padding: 4px 10px; border-radius: 9999px; font-size: 12px; font-weight: 600;">
                        {b_text}
                    </span>
                </div>

                <div style="display: flex; justify-content: space-between; align-items: center; border-top: 1px dashed #E5E7EB; padding-top: 12px; margin-top: 4px;">
                    <span style="color: #4B5563; font-size: 14px; font-weight: 500;">Batch Size</span>
                    <span style="color: #111827; font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; font-size: 14px; font-weight: 600; background-color: #F3F4F6; padding: 2px 8px; border-radius: 6px;">
                        {self.batch_size}
                    </span>
                </div>
                {extra_html}
            </div>
        </div>
        """
        return html

    def _circuit_logic(self, features: Any) -> Any:
        """Core circuit logic to be implemented by subclasses.

        Args:
            features (Any): The encrypted 2D feature matrix containing input samples.

        Returns:
            Any: The result of the circuit computation.
        """
        raise NotImplementedError("Subclasses must implement _circuit_logic")

    def _batch_circuit_logic(self, features_batch: Any) -> Any:
        """Executes the circuit logic on a batch of features.

        Args:
            features_batch (Any): A batch of input features.

        Returns:
            Any: An array of results from the circuit logic.
        """
        return fhe.array([self._circuit_logic(sample) for sample in features_batch])

    def _single_circuit_logic(self, features: Any) -> Any:
        """Executes the circuit logic on a single sample.

        Args:
            features (Any): The encrypted 2D feature matrix containing input samples.

        Returns:
            Any: The result of the circuit logic.
        """
        result = self._circuit_logic(features)
        return fhe.array(result) if isinstance(result, (list, tuple)) else result

    @staticmethod
    def _integer_array(value: Any) -> Any:
        """Converts a value to an integer numpy array safely.

        Args:
            value (Any): The encrypted value to process or validate.

        Returns:
            Any: The resulting integer numpy array.
        """
        array = np.asarray(value)
        if array.size == 0:
            raise ValueError("samples must not be empty")
        if array.dtype.kind not in "iu":
            raise TypeError("samples must contain integers")
        if array.dtype.kind == "u" and np.any(array > np.iinfo(np.int64).max):
            raise ValueError("samples must fit in signed 64-bit integers")
        return array.astype(np.int64)

    def compile(self, inputset: Any, batch_size: Any=None, *, inputset_is_batched: Any=None,
                configuration: Any=None) -> Any:
        """Compile representative integer samples.

        By default, each inputset item is one sample and the circuit accepts
        one sample, including image/tensor samples. ``predict_many`` reuses it.

        For compatibility, an explicit ``batch_size`` means each inputset
        item is an already assembled batch. Pass ``inputset_is_batched=False``
        with ``batch_size`` to build a batch circuit from individual samples.
        ``inputset_is_batched=True`` can infer batch size from the first item.
        All batches must have the same shape and size. Runtime samples must
        remain within the public bounds represented by the inputset.

        Args:
            inputset (Any): The calibration dataset.
            batch_size (Any, optional): The batch size. Defaults to None.
            inputset_is_batched (Any, optional): Whether the inputset is batched. Defaults to None.
            configuration (Any, optional): Optional FHE compiler configuration object.

        Returns:
            Any: The compiled circuit or None.

        Example:
            ```python
            model.compile([[0, 0], [5, 5]])
            model.compile([[0, 0], [5, 5]], batch_size=4,
                          inputset_is_batched=False)
            model.compile([[[0, 0]] * 4, [[5, 5]] * 4], batch_size=4)
            ```
        """
        if inputset_is_batched is not None and not isinstance(inputset_is_batched, bool):
            raise TypeError("inputset_is_batched must be a boolean or None")
        size = None if batch_size is None else validate_integer("batch_size", batch_size, 1)
        prebatched = size is not None if inputset_is_batched is None else inputset_is_batched
        items = [self._integer_array(item) for item in inputset]
        if not items:
            raise ValueError("inputset must contain at least one sample")
        shape = items[0].shape
        if any(item.shape != shape for item in items):
            raise ValueError("all inputset items must have the same shape")
        batched = prebatched or size is not None
        if prebatched:
            if not shape:
                raise ValueError("each inputset item must contain a batch")
            size = shape[0] if size is None else size
            if shape[0] != size:
                raise ValueError("inputset batch dimension must equal batch_size")
            sample_shape = shape[1:]
            calibration = items
        elif batched:
            sample_shape = shape
            # Every lane observes every calibration sample and its bounds.
            assert size is not None
            calibration = [np.stack([item] * size) for item in items]
        else:
            size = 1
            sample_shape = shape
            calibration = items
        function = self._batch_circuit_logic if batched else self._single_circuit_logic
        parameter = "features_batch" if batched else "features"
        compiler = fhe.Compiler(function, {parameter: "encrypted"})
        if configuration is None:
            # Force extremely tight error bounds to avoid FHE noise non-determinism
            circuit = compiler.compile(calibration, configuration=fhe.Configuration(global_p_error=0.01))
        else:
            circuit = compiler.compile(calibration, configuration=configuration)
        # Commit state only after successful compilation.
        self.compiler = compiler
        self.circuit = circuit
        self.batch_size = size
        self._batched = batched
        self._sample_shape = sample_shape
        return self

    def predict(self, features: Any) -> Any:
        """Encrypt one sample, evaluate it, and decrypt its prediction.

        Args:
            features (Any): The encrypted 2D feature matrix containing input samples.

        Returns:
            Any: The prediction result.
        """
        return self.predict_many([features])[0]

    def simulate(self, features: Any) -> Any:
        """Simulate one sample without encryption; compile the model first.

        Args:
            features (Any): The encrypted 2D feature matrix containing input samples.

        Returns:
            Any: The simulation result.
        """
        return self.simulate_many([features])[0]

    def _run_many(self, samples: Any, method: Any) -> Any:
        """Helper to run a method over multiple samples.

        Args:
            samples (Any): The list of samples.
            method (Any): The name of the method to call on the circuit.

        Returns:
            Any: A list of results.
        """
        if self.circuit is None:
            raise ValueError("The model should be compiled before prediction")
        items = [self._integer_array(sample) for sample in samples]
        if not items:
            return []
        expected_shape = self._sample_shape if self._sample_shape is not None else items[0].shape
        if any(item.shape != expected_shape for item in items):
            raise ValueError("sample shape does not match the compiled model")
        run = getattr(self.circuit, method)
        if not self._batched:
            return [run(item) for item in items]
        results = []
        for start in range(0, len(items), self.batch_size):
            batch = items[start:start + self.batch_size]
            count = len(batch)
            # Repeat an in-domain sample, preserving arbitrary tensor shape.
            batch = batch + [batch[-1]] * (self.batch_size - count)
            results.extend(run(np.stack(batch))[:count])
        return results

    def predict_many(self, samples: Any) -> Any:
        """Predict samples using the compiled circuit and its existing keys.

        Partial batches repeat the final sample for padding; padded predictions
        are discarded. Single-sample circuits execute once per input sample.

        Args:
            samples (Any): The list of samples to predict on.

        Returns:
            Any: The list of predictions.
        """
        return self._run_many(samples, "encrypt_run_decrypt")

    def simulate_many(self, samples: Any) -> Any:
        """Simulate samples with the same batching rules as ``predict_many``.

        Args:
            samples (Any): The list of samples to simulate on.

        Returns:
            Any: The list of simulation results.
        """
        return self._run_many(samples, "simulate")

compile

compile(inputset: Any, batch_size: Any = None, *, inputset_is_batched: Any = None, configuration: Any = None) -> Any

Compile representative integer samples.

By default, each inputset item is one sample and the circuit accepts one sample, including image/tensor samples. predict_many reuses it.

For compatibility, an explicit batch_size means each inputset item is an already assembled batch. Pass inputset_is_batched=False with batch_size to build a batch circuit from individual samples. inputset_is_batched=True can infer batch size from the first item. All batches must have the same shape and size. Runtime samples must remain within the public bounds represented by the inputset.

Parameters:

Name Type Description Default
inputset Any

The calibration dataset.

required
batch_size Any

The batch size. Defaults to None.

None
inputset_is_batched Any

Whether the inputset is batched. Defaults to None.

None
configuration Any

Optional FHE compiler configuration object.

None

Returns:

Name Type Description
Any Any

The compiled circuit or None.

Example
model.compile([[0, 0], [5, 5]])
model.compile([[0, 0], [5, 5]], batch_size=4,
              inputset_is_batched=False)
model.compile([[[0, 0]] * 4, [[5, 5]] * 4], batch_size=4)
Source code in src/concrete_fhe_toolkit/ml/classes.py
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def compile(self, inputset: Any, batch_size: Any=None, *, inputset_is_batched: Any=None,
            configuration: Any=None) -> Any:
    """Compile representative integer samples.

    By default, each inputset item is one sample and the circuit accepts
    one sample, including image/tensor samples. ``predict_many`` reuses it.

    For compatibility, an explicit ``batch_size`` means each inputset
    item is an already assembled batch. Pass ``inputset_is_batched=False``
    with ``batch_size`` to build a batch circuit from individual samples.
    ``inputset_is_batched=True`` can infer batch size from the first item.
    All batches must have the same shape and size. Runtime samples must
    remain within the public bounds represented by the inputset.

    Args:
        inputset (Any): The calibration dataset.
        batch_size (Any, optional): The batch size. Defaults to None.
        inputset_is_batched (Any, optional): Whether the inputset is batched. Defaults to None.
        configuration (Any, optional): Optional FHE compiler configuration object.

    Returns:
        Any: The compiled circuit or None.

    Example:
        ```python
        model.compile([[0, 0], [5, 5]])
        model.compile([[0, 0], [5, 5]], batch_size=4,
                      inputset_is_batched=False)
        model.compile([[[0, 0]] * 4, [[5, 5]] * 4], batch_size=4)
        ```
    """
    if inputset_is_batched is not None and not isinstance(inputset_is_batched, bool):
        raise TypeError("inputset_is_batched must be a boolean or None")
    size = None if batch_size is None else validate_integer("batch_size", batch_size, 1)
    prebatched = size is not None if inputset_is_batched is None else inputset_is_batched
    items = [self._integer_array(item) for item in inputset]
    if not items:
        raise ValueError("inputset must contain at least one sample")
    shape = items[0].shape
    if any(item.shape != shape for item in items):
        raise ValueError("all inputset items must have the same shape")
    batched = prebatched or size is not None
    if prebatched:
        if not shape:
            raise ValueError("each inputset item must contain a batch")
        size = shape[0] if size is None else size
        if shape[0] != size:
            raise ValueError("inputset batch dimension must equal batch_size")
        sample_shape = shape[1:]
        calibration = items
    elif batched:
        sample_shape = shape
        # Every lane observes every calibration sample and its bounds.
        assert size is not None
        calibration = [np.stack([item] * size) for item in items]
    else:
        size = 1
        sample_shape = shape
        calibration = items
    function = self._batch_circuit_logic if batched else self._single_circuit_logic
    parameter = "features_batch" if batched else "features"
    compiler = fhe.Compiler(function, {parameter: "encrypted"})
    if configuration is None:
        # Force extremely tight error bounds to avoid FHE noise non-determinism
        circuit = compiler.compile(calibration, configuration=fhe.Configuration(global_p_error=0.01))
    else:
        circuit = compiler.compile(calibration, configuration=configuration)
    # Commit state only after successful compilation.
    self.compiler = compiler
    self.circuit = circuit
    self.batch_size = size
    self._batched = batched
    self._sample_shape = sample_shape
    return self

predict

predict(features: Any) -> Any

Encrypt one sample, evaluate it, and decrypt its prediction.

Parameters:

Name Type Description Default
features Any

The encrypted 2D feature matrix containing input samples.

required

Returns:

Name Type Description
Any Any

The prediction result.

Source code in src/concrete_fhe_toolkit/ml/classes.py
259
260
261
262
263
264
265
266
267
268
def predict(self, features: Any) -> Any:
    """Encrypt one sample, evaluate it, and decrypt its prediction.

    Args:
        features (Any): The encrypted 2D feature matrix containing input samples.

    Returns:
        Any: The prediction result.
    """
    return self.predict_many([features])[0]

simulate

simulate(features: Any) -> Any

Simulate one sample without encryption; compile the model first.

Parameters:

Name Type Description Default
features Any

The encrypted 2D feature matrix containing input samples.

required

Returns:

Name Type Description
Any Any

The simulation result.

Source code in src/concrete_fhe_toolkit/ml/classes.py
270
271
272
273
274
275
276
277
278
279
def simulate(self, features: Any) -> Any:
    """Simulate one sample without encryption; compile the model first.

    Args:
        features (Any): The encrypted 2D feature matrix containing input samples.

    Returns:
        Any: The simulation result.
    """
    return self.simulate_many([features])[0]

predict_many

predict_many(samples: Any) -> Any

Predict samples using the compiled circuit and its existing keys.

Partial batches repeat the final sample for padding; padded predictions are discarded. Single-sample circuits execute once per input sample.

Parameters:

Name Type Description Default
samples Any

The list of samples to predict on.

required

Returns:

Name Type Description
Any Any

The list of predictions.

Source code in src/concrete_fhe_toolkit/ml/classes.py
311
312
313
314
315
316
317
318
319
320
321
322
323
def predict_many(self, samples: Any) -> Any:
    """Predict samples using the compiled circuit and its existing keys.

    Partial batches repeat the final sample for padding; padded predictions
    are discarded. Single-sample circuits execute once per input sample.

    Args:
        samples (Any): The list of samples to predict on.

    Returns:
        Any: The list of predictions.
    """
    return self._run_many(samples, "encrypt_run_decrypt")

simulate_many

simulate_many(samples: Any) -> Any

Simulate samples with the same batching rules as predict_many.

Parameters:

Name Type Description Default
samples Any

The list of samples to simulate on.

required

Returns:

Name Type Description
Any Any

The list of simulation results.

Source code in src/concrete_fhe_toolkit/ml/classes.py
325
326
327
328
329
330
331
332
333
334
def simulate_many(self, samples: Any) -> Any:
    """Simulate samples with the same batching rules as ``predict_many``.

    Args:
        samples (Any): The list of samples to simulate on.

    Returns:
        Any: The list of simulation results.
    """
    return self._run_many(samples, "simulate")

FHELogisticRegression

Bases: FHEModel

Encrypted Logistic Regression Inference Model.

Evaluates a logistic regression model over encrypted features.

Parameters:

Name Type Description Default
weights Any

The pre-trained cleartext model weights used for inference.

required
bias Any

The pre-trained cleartext model bias used for inference.

required
Example
model = FHELogisticRegression(weights=[3, 2], bias=-7)
model.compile(dummy_inputset, batch_size=1)
Source code in src/concrete_fhe_toolkit/ml/classes.py
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
class FHELogisticRegression(FHEModel):
    """Encrypted Logistic Regression Inference Model.

    Evaluates a logistic regression model over encrypted features.

    Args:
        weights: The pre-trained cleartext model weights used for inference.
        bias: The pre-trained cleartext model bias used for inference.

    Example:
        ```python
        model = FHELogisticRegression(weights=[3, 2], bias=-7)
        model.compile(dummy_inputset, batch_size=1)
        ```
    """
    def __init__(self, weights: Any, bias: Any, *, input_scale: Any = 1, output_scale: Any = 1):
        super().__init__()
        """Initialize the object."""
        self.weights = weights
        self.bias = bias
        self.input_scale = input_scale
        self.output_scale = output_scale

    def _circuit_logic(self, features: Any) -> Any:
        return logistic_regression_inference(self.weights, self.bias, features)

FHELinearRegression

Bases: FHEModel

Encrypted Linear Regression Inference Model.

Evaluates a linear regression model over encrypted features.

Parameters:

Name Type Description Default
weights Any

The pre-trained cleartext model weights used for inference.

required
bias Any

The pre-trained cleartext model bias used for inference.

required
Example
model = FHELinearRegression(weights=[10, -5], bias=2)
model.compile(dummy_inputset, batch_size=1)
Source code in src/concrete_fhe_toolkit/ml/classes.py
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
class FHELinearRegression(FHEModel):
    """Encrypted Linear Regression Inference Model.

    Evaluates a linear regression model over encrypted features.

    Args:
        weights: The pre-trained cleartext model weights used for inference.
        bias: The pre-trained cleartext model bias used for inference.

    Example:
        ```python
        model = FHELinearRegression(weights=[10, -5], bias=2)
        model.compile(dummy_inputset, batch_size=1)
        ```
    """
    def __init__(self, weights: Any, bias: Any, *, input_scale: Any = 1, output_scale: Any = 1):
        super().__init__()
        """Initialize the object."""
        self.weights = weights
        self.bias = bias
        self.input_scale = input_scale
        self.output_scale = output_scale

    def _circuit_logic(self, features: Any) -> Any:
        return linear_regression_inference(self.weights, self.bias, features)

FHEDecisionTree

Bases: FHEModel

Encrypted Decision Tree Inference Model.

Evaluates a decision tree over encrypted features.

Parameters:

Name Type Description Default
tree Any

The public tree representation (dict format).

required
Example
model = FHEDecisionTree(tree=my_parsed_tree)
model.compile(dummy_inputset, batch_size=1)
Source code in src/concrete_fhe_toolkit/ml/classes.py
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
class FHEDecisionTree(FHEModel):
    """Encrypted Decision Tree Inference Model.

    Evaluates a decision tree over encrypted features.

    Args:
        tree: The public tree representation (dict format).

    Example:
        ```python
        model = FHEDecisionTree(tree=my_parsed_tree)
        model.compile(dummy_inputset, batch_size=1)
        ```
    """
    def __init__(self,tree: Any):
        super().__init__()
        """Initialize the object."""
        self.tree = tree

    def _circuit_logic(self, features: Any) -> Any:
        return decision_tree_inference(features, self.tree)

FHEPCA

Bases: FHEModel

Encrypted Principal Component Analysis (PCA) Inference Model.

Applies PCA dimensionality reduction to encrypted features.

Parameters:

Name Type Description Default
means Any

The public list of feature means.

required
components Any

The public principal components matrix.

required
Example
model = FHEPCA(means=[0.5, 0.5], components=[[1, 0], [0, 1]])
model.compile(dummy_inputset, batch_size=1)
Source code in src/concrete_fhe_toolkit/ml/classes.py
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
class FHEPCA(FHEModel):
    """Encrypted Principal Component Analysis (PCA) Inference Model.

    Applies PCA dimensionality reduction to encrypted features.

    Args:
        means: The public list of feature means.
        components: The public principal components matrix.

    Example:
        ```python
        model = FHEPCA(means=[0.5, 0.5], components=[[1, 0], [0, 1]])
        model.compile(dummy_inputset, batch_size=1)
        ```
    """
    def __init__(self, means: Any, components: Any):
        super().__init__()
        """Initialize the object."""
        self.means = means
        self.components = components

    def _circuit_logic(self, features: Any) -> Any:
        return pca_inference(features, self.means, self.components)

FHECNN

Bases: FHEModel

Encrypted Convolutional Neural Network (CNN) Inference Model.

Applies a 2D convolutional layer to an encrypted image.

Parameters:

Name Type Description Default
filters Any

The public 2D or 3D list of convolutional filters.

required
bias Any

The pre-trained cleartext model bias used for inference.

required
Example
model = FHECNN(filters=my_conv_filters, bias=my_conv_bias)
model.compile(dummy_inputset, batch_size=1)
Source code in src/concrete_fhe_toolkit/ml/classes.py
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
class FHECNN(FHEModel):
    """Encrypted Convolutional Neural Network (CNN) Inference Model.

    Applies a 2D convolutional layer to an encrypted image.

    Args:
        filters: The public 2D or 3D list of convolutional filters.
        bias: The pre-trained cleartext model bias used for inference.

    Example:
        ```python
        model = FHECNN(filters=my_conv_filters, bias=my_conv_bias)
        model.compile(dummy_inputset, batch_size=1)
        ```
    """        
    def __init__(self, filters: Any, bias: Any):
        super().__init__()
        """Initialize the object."""
        self.filters = filters
        self.bias = bias

    def _circuit_logic(self, features: Any) -> Any:
        return cnn_inference(self.filters, self.bias, image = features)

FHERandomForest

Bases: FHEModel

Encrypted Random Forest Inference Model.

Evaluates an ensemble of decision trees over encrypted features.

Parameters:

Name Type Description Default
trees Any

The public list of tree representations (dict format).

required
Example
model = FHERandomForest(trees=[tree1, tree2, tree3])
model.compile(dummy_inputset, batch_size=1)
Source code in src/concrete_fhe_toolkit/ml/classes.py
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
class FHERandomForest(FHEModel):
    """Encrypted Random Forest Inference Model.

    Evaluates an ensemble of decision trees over encrypted features.

    Args:
        trees: The public list of tree representations (dict format).

    Example:
        ```python
        model = FHERandomForest(trees=[tree1, tree2, tree3])
        model.compile(dummy_inputset, batch_size=1)
        ```
    """
    def __init__(self, trees: Any):
        super().__init__()
        """Initialize the object."""
        self.trees = trees

    def _circuit_logic(self, features: Any) -> Any:
        return random_forest_inference(features,self.trees)    

FHEXGBoost

Bases: FHEModel

Encrypted XGBoost Inference Model.

Evaluates a gradient boosting tree ensemble over encrypted features.

Parameters:

Name Type Description Default
trees Any

The public list of tree representations (dict format).

required
Example
model = FHEXGBoost(trees=my_xgb_trees)
model.compile(dummy_inputset, batch_size=1)
Source code in src/concrete_fhe_toolkit/ml/classes.py
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
class FHEXGBoost(FHEModel):
    """Encrypted XGBoost Inference Model.

    Evaluates a gradient boosting tree ensemble over encrypted features.

    Args:
        trees: The public list of tree representations (dict format).

    Example:
        ```python
        model = FHEXGBoost(trees=my_xgb_trees)
        model.compile(dummy_inputset, batch_size=1)
        ```
    """
    def __init__(self, trees: Any):
        super().__init__() 
        """Initialize the object."""
        self.trees = trees   

    def _circuit_logic(self, features: Any) -> Any:
        return xgboost_inference(features, self.trees)    

FHESVM

Bases: FHEModel

Encrypted Support Vector Machine (SVM) Inference Model.

Evaluates a linear SVM over encrypted features.

Parameters:

Name Type Description Default
weights Any

The pre-trained cleartext model weights used for inference.

required
bias Any

The pre-trained cleartext model bias used for inference.

required
Example
model = FHESVM(weights=[0.5, -1.2], bias=0.1)
model.compile(dummy_inputset, batch_size=1)
Source code in src/concrete_fhe_toolkit/ml/classes.py
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
class FHESVM(FHEModel):
    """Encrypted Support Vector Machine (SVM) Inference Model.

    Evaluates a linear SVM over encrypted features.

    Args:
        weights: The pre-trained cleartext model weights used for inference.
        bias: The pre-trained cleartext model bias used for inference.

    Example:
        ```python
        model = FHESVM(weights=[0.5, -1.2], bias=0.1)
        model.compile(dummy_inputset, batch_size=1)
        ```
    """
    def __init__(self, weights: Any, bias: Any):
        super().__init__()
        """Initialize the object."""
        self.weights = weights
        self.bias = bias

    def _circuit_logic(self, features: Any) -> Any:
        return svm_inference(self.weights, self.bias, features)

FHEKNN

Bases: FHEModel

Encrypted K-Nearest Neighbors (KNN) Inference Model.

Evaluates KNN distances between encrypted features and plaintext training data.

Parameters:

Name Type Description Default
X_train Any

The public training dataset features.

required
y_train Any

The public training dataset labels.

required
k Any

The number of nearest neighbors to consider.

required
Example
model = FHEKNN(X_train=public_X, y_train=public_y, k=3)
model.compile(dummy_inputset, batch_size=1)
Source code in src/concrete_fhe_toolkit/ml/classes.py
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
class FHEKNN(FHEModel):
    """Encrypted K-Nearest Neighbors (KNN) Inference Model.

    Evaluates KNN distances between encrypted features and plaintext training data.

    Args:
        X_train: The public training dataset features.
        y_train: The public training dataset labels.
        k: The number of nearest neighbors to consider.

    Example:
        ```python
        model = FHEKNN(X_train=public_X, y_train=public_y, k=3)
        model.compile(dummy_inputset, batch_size=1)
        ```
    """
    def __init__(self, X_train: Any, y_train: Any, k: Any):
        super().__init__()
        """Initialize the object."""
        self.X_train = X_train
        self.y_train = y_train
        self.k = k

    def _circuit_logic(self, features: Any) -> Any:
        return knn_inference(features, self.X_train, self.y_train, k=self.k)

FHEMLP

Bases: FHEModel

Encrypted Multi-Layer Perceptron (Dense) Inference Model.

Evaluates a sequence of dense neural network layers over encrypted features.

Parameters:

Name Type Description Default
mlp_layers Any

The public list of layer tuples, where each tuple is (weights, bias).

required
Example
model = FHEMLP(mlp_layers=[(w1, b1), (w2, b2)])
model.compile(dummy_inputset, batch_size=1)
Source code in src/concrete_fhe_toolkit/ml/classes.py
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
class FHEMLP(FHEModel):    
    """Encrypted Multi-Layer Perceptron (Dense) Inference Model.

    Evaluates a sequence of dense neural network layers over encrypted features.

    Args:
        mlp_layers: The public list of layer tuples, where each tuple is `(weights, bias)`.

    Example:
        ```python
        model = FHEMLP(mlp_layers=[(w1, b1), (w2, b2)])
        model.compile(dummy_inputset, batch_size=1)
        ```
    """
    def __init__(self, mlp_layers: Any):
        super().__init__()
        """Initialize the object."""
        self.mlp_layers = mlp_layers

    def _circuit_logic(self, features: Any) -> Any:
        return mlp_inference(features,self.mlp_layers)    

FHENaiveBayes

Bases: FHEModel

Encrypted Naive Bayes Inference Model.

Evaluates a Bernoulli Naive Bayes classifier over encrypted binary features. The model aggregates log probabilities using FHE lookup tables and returns the class index with the highest score using an encrypted argmax reduction.

Parameters:

Name Type Description Default
log_prob_tables Any

The public quantized feature log probabilities.

required
priors Any

The public quantized class priors.

required
Example
# Assuming `model` was returned by FHENaiveBayesTrainer.fit_encrypted
model.compile(dummy_inputset, batch_size=1)
prediction = model.predict([1, 0, 1, 1])
Source code in src/concrete_fhe_toolkit/ml/classes.py
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
class FHENaiveBayes(FHEModel):
    """Encrypted Naive Bayes Inference Model.

    Evaluates a Bernoulli Naive Bayes classifier over encrypted binary features.
    The model aggregates log probabilities using FHE lookup tables and returns 
    the class index with the highest score using an encrypted argmax reduction.

    Args:
        log_prob_tables: The public quantized feature log probabilities.
        priors: The public quantized class priors.

    Example:
        ```python
        # Assuming `model` was returned by FHENaiveBayesTrainer.fit_encrypted
        model.compile(dummy_inputset, batch_size=1)
        prediction = model.predict([1, 0, 1, 1])
        ```
    """
    def __init__(self, log_prob_tables: Any, priors: Any):
        super().__init__()
        """Initialize the object."""
        self.log_prob_tables = log_prob_tables
        self.priors = priors
        self.scale: Optional[int] = None

    def _circuit_logic(self, features: Any) -> Any:
        return naive_bayes_inference(features,self.log_prob_tables,self.priors)

FHENaiveBayesTrainer

Trainer for Encrypted Bernoulli Naive Bayes.

Trains a Naive Bayes model over encrypted binary features and encrypted one-hot labels. The trainer automatically determines the optimal SCALE for probability quantization while maximizing the utilization of the specified max_bit_width.

FHE Optimization (Zero-Centered Shifting): Log probabilities are always negative. This wastes half of the available integer space in any bit width (e.g., the positive +1 to +127 range in 8-bit, or higher in 16-bit). This class mathematically shifts the log probabilities by finding the centered_max and adding it entirely to the class Prior. This centers the final circuit score perfectly in the middle of the available bit-width range, effectively doubling the precision (SCALE) for any chosen bit-width (from 8-bit up to 16-bit).

Laplace Smoothing: To prevent log(0) -infinity errors for features that never appeared in the training set, Laplace smoothing is automatically applied to probability calculations.

Example
from concrete_fhe_toolkit.ml.classes import FHENaiveBayesTrainer

trainer = FHENaiveBayesTrainer()
# X_train must be binary (0 or 1), y_train must be one-hot encoded
model = trainer.fit_encrypted(X_train, y_train_ohe, max_bit_width=10)
Source code in src/concrete_fhe_toolkit/ml/classes.py
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
class FHENaiveBayesTrainer:
    """Trainer for Encrypted Bernoulli Naive Bayes.

    Trains a Naive Bayes model over encrypted binary features and encrypted one-hot labels.
    The trainer automatically determines the optimal SCALE for probability quantization
    while maximizing the utilization of the specified `max_bit_width`.

    FHE Optimization (Zero-Centered Shifting):
    Log probabilities are always negative. This wastes half of the available integer 
    space in any bit width (e.g., the positive +1 to +127 range in 8-bit, or higher in 
    16-bit). This class mathematically shifts the log probabilities by finding the 
    `centered_max` and adding it entirely to the class Prior. This centers the final 
    circuit score perfectly in the middle of the available bit-width range, effectively 
    doubling the precision (SCALE) for any chosen bit-width (from 8-bit up to 16-bit).

    Laplace Smoothing:
    To prevent log(0) -infinity errors for features that never appeared in the training 
    set, Laplace smoothing is automatically applied to probability calculations.

    Example:
        ```python
        from concrete_fhe_toolkit.ml.classes import FHENaiveBayesTrainer

        trainer = FHENaiveBayesTrainer()
        # X_train must be binary (0 or 1), y_train must be one-hot encoded
        model = trainer.fit_encrypted(X_train, y_train_ohe, max_bit_width=10)
        ```
    """
    def __init__(self):
        """Initializes the FHENaiveBayesTrainer.

        Returns:
            None
        """
        self.circuit = None
        self.compiler = None

    def prepare_trainer(self, num_samples: int, num_features: int, num_classes: int, max_bit_width: Any=8, thresholds: Any=None) -> Any:
        """Prepares and compiles the trainer circuit.

        Args:
            num_samples (int): Number of training samples.
            num_features (int): Number of features per sample.
            num_classes (int): Number of classes.
            max_bit_width (Any, optional): Maximum bit width for the circuit. Defaults to 8.
            thresholds (Any, optional): Thresholds for training. Defaults to None.

        Returns:
            Any: The compiled FHE circuit.

        Example:
            ```python
            trainer.prepare_trainer(100, 10, 2)
            ```
        """
        if(max_bit_width > 16):
            raise ValueError("The maximum supported bit width is 16")
        if(max_bit_width > 8):
            warnings.warn("Higher bit widths(>8) may result in longer computation times.", UserWarning, stacklevel=2)

        # To prevent 'uint1' inference, use max possible value for bit width
        max_val = (2**(max_bit_width - 1)) - 1
        dummy_X = [[max_val]*num_features for _ in range(num_samples)]
        dummy_y = [[1]*num_classes for _ in range(num_samples)]

        if thresholds is not None:
            from .training import make_raw_naive_bayes_training
            circuit_logic = make_raw_naive_bayes_training(thresholds)
            self.compiler = fhe.Compiler(circuit_logic, {"X_train_raw": "encrypted", "y_train_one_hot": "encrypted"})
        else:
            self.compiler = fhe.Compiler(naive_bayes_training, {"X_train": "encrypted", "y_train_one_hot": "encrypted"})

        self.circuit = self.compiler.compile([(dummy_X, dummy_y)])
        return self.circuit

    def encrypt_data(self, X_train: Any, y_train: Any) -> Any:
        """Encrypts the training data.

        Args:
            X_train (Any): The training features.
            y_train (Any): The training labels.

        Returns:
            Any: The encrypted data tuple.
        """
        if self.circuit is None:
            raise ValueError("Circuit is not compiled. Call compile_trainer first.")

        return self.circuit.encrypt(X_train, y_train)

    def train_encrypted(self, encrypted_X: Any, encrypted_y: Any) -> Any:
        """Trains the model on the server using encrypted data.

        Args:
            encrypted_X (Any): Encrypted training features.
            encrypted_y (Any): Encrypted training labels.

        Returns:
            Any: Encrypted results of the training circuit.
        """
        if self.circuit is None:
            raise ValueError("Circuit is not compiled on server.")

        return self.circuit.run(encrypted_X, encrypted_y)

    def decrypt_and_finalize_model(self, encrypted_results: Any, max_bit_width: Any=8, * ,epsilon: Any = None) -> Any:
        """Decrypts the results and finalizes the Naive Bayes model.

        Args:
            encrypted_results (Any): The encrypted results from the server.
            max_bit_width (Any, optional): Maximum bit width for the circuit. Defaults to 8.
            epsilon (Any, optional): Epsilon for differential privacy. Defaults to None.

        Returns:
            Any: The finalized FHENaiveBayes model.
        """
        raw_feature_counts, priors = self.circuit.decrypt(*encrypted_results)
        if epsilon is not None:
            noisy_feature_counts = []
            for row in raw_feature_counts:
                noisy_feature_counts.append(dp_release(row, sensitivity=1, epsilon=epsilon/2))
            priors_noisy = dp_release(priors, sensitivity=1, epsilon=epsilon/2)
            return self._finalize_model(noisy_feature_counts, priors_noisy, max_bit_width)

        return self._finalize_model(raw_feature_counts, priors, max_bit_width)

    @staticmethod
    def _finalize_model(raw_feature_counts: Any, priors: Any, max_bit_width: Any) -> Any:
        formatted_tables = []
        formatted_priors = []
        total_samples = sum(priors)

        max_abs_score = 0.0
        num_features = len(raw_feature_counts[0])
        for prior in priors:
            class_total = int(prior)
            prior_prob = class_total / total_samples
            min_feature_prob = 1 / (class_total + 2)

            score_abs = abs(math.log(prior_prob)) + (num_features * abs(math.log(min_feature_prob)))
            max_abs_score = max(max_abs_score, score_abs)

        centered_max = max_abs_score / 2.0
        max_target_int = (2**(max_bit_width - 1)) -1

        SCALE = max(1,int(max_target_int / centered_max))

        for c, class_feature_counts in enumerate(raw_feature_counts):
            class_total = int(priors[c])

            # Prior Log Prob
            prior_prob = class_total / total_samples
            unscaled_prior = math.log(prior_prob) + centered_max 
            formatted_priors.append(int(round(unscaled_prior * SCALE)))

            class_tables = []
            for count_of_ones in class_feature_counts:
                count_of_ones = int(count_of_ones)
                count_of_zeros = class_total - count_of_ones

                # Laplace smoothed probabilities: (count + 1) / (class_total + num_classes)
                prob_0 = (count_of_zeros + 1) / (class_total + 2)
                prob_1 = (count_of_ones + 1) / (class_total + 2)

                log_prob_0 = int(round(math.log(prob_0) * SCALE))
                log_prob_1 = int(round(math.log(prob_1) * SCALE))

                class_tables.append([log_prob_0, log_prob_1])
            formatted_tables.append(class_tables)

        model = FHENaiveBayes(formatted_tables, formatted_priors)
        model.scale = SCALE
        return model

    def fit_encrypted(self, X_train: Any, y_train: Any, * ,max_bit_width: Any = 8, thresholds: Any=None, epsilon: Any=None) -> Any:
        """Fits the model securely on encrypted training data.

        Args:
            X_train (Any): The training features.
            y_train (Any): The training labels.
            max_bit_width (Any, optional): Maximum bit width for the circuit. Defaults to 8.
            thresholds (Any, optional): Thresholds for training. Defaults to None.
            epsilon (Any, optional): Epsilon for differential privacy. Defaults to None.

        Returns:
            Any: The trained FHENaiveBayes model.
        """
        if(max_bit_width > 16):
            raise ValueError("The maximum supported bit width is 16")
        if(max_bit_width > 8):
            warnings.warn("Higher bit widths(>8) may result in longer computation times.", UserWarning, stacklevel=2)

        if thresholds is not None:
            from .training import make_raw_naive_bayes_training
            circuit_logic = make_raw_naive_bayes_training(thresholds)
            self.compiler = fhe.Compiler(circuit_logic, {"X_train_raw": "encrypted", "y_train_one_hot": "encrypted"})
        else:
            self.compiler = fhe.Compiler(naive_bayes_training,{"X_train": "encrypted", "y_train_one_hot": "encrypted"})

        self.circuit = self.compiler.compile([(X_train, y_train)])

        # The circuit returns raw counts (feature_counts, class_counts)
        raw_feature_counts, priors = self.circuit.encrypt_run_decrypt(X_train, y_train)
        if epsilon is not None:
            noisy_feature_counts = []
            for row in raw_feature_counts:
                noisy_feature_counts.append(dp_release(row, sensitivity=1, epsilon=epsilon/2))
            priors_noisy = dp_release(priors, sensitivity=1, epsilon=epsilon/2)
            return self._finalize_model(noisy_feature_counts, priors_noisy, max_bit_width)

        return self._finalize_model(raw_feature_counts, priors, max_bit_width)

prepare_trainer

prepare_trainer(num_samples: int, num_features: int, num_classes: int, max_bit_width: Any = 8, thresholds: Any = None) -> Any

Prepares and compiles the trainer circuit.

Parameters:

Name Type Description Default
num_samples int

Number of training samples.

required
num_features int

Number of features per sample.

required
num_classes int

Number of classes.

required
max_bit_width Any

Maximum bit width for the circuit. Defaults to 8.

8
thresholds Any

Thresholds for training. Defaults to None.

None

Returns:

Name Type Description
Any Any

The compiled FHE circuit.

Example
trainer.prepare_trainer(100, 10, 2)
Source code in src/concrete_fhe_toolkit/ml/classes.py
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
def prepare_trainer(self, num_samples: int, num_features: int, num_classes: int, max_bit_width: Any=8, thresholds: Any=None) -> Any:
    """Prepares and compiles the trainer circuit.

    Args:
        num_samples (int): Number of training samples.
        num_features (int): Number of features per sample.
        num_classes (int): Number of classes.
        max_bit_width (Any, optional): Maximum bit width for the circuit. Defaults to 8.
        thresholds (Any, optional): Thresholds for training. Defaults to None.

    Returns:
        Any: The compiled FHE circuit.

    Example:
        ```python
        trainer.prepare_trainer(100, 10, 2)
        ```
    """
    if(max_bit_width > 16):
        raise ValueError("The maximum supported bit width is 16")
    if(max_bit_width > 8):
        warnings.warn("Higher bit widths(>8) may result in longer computation times.", UserWarning, stacklevel=2)

    # To prevent 'uint1' inference, use max possible value for bit width
    max_val = (2**(max_bit_width - 1)) - 1
    dummy_X = [[max_val]*num_features for _ in range(num_samples)]
    dummy_y = [[1]*num_classes for _ in range(num_samples)]

    if thresholds is not None:
        from .training import make_raw_naive_bayes_training
        circuit_logic = make_raw_naive_bayes_training(thresholds)
        self.compiler = fhe.Compiler(circuit_logic, {"X_train_raw": "encrypted", "y_train_one_hot": "encrypted"})
    else:
        self.compiler = fhe.Compiler(naive_bayes_training, {"X_train": "encrypted", "y_train_one_hot": "encrypted"})

    self.circuit = self.compiler.compile([(dummy_X, dummy_y)])
    return self.circuit

encrypt_data

encrypt_data(X_train: Any, y_train: Any) -> Any

Encrypts the training data.

Parameters:

Name Type Description Default
X_train Any

The training features.

required
y_train Any

The training labels.

required

Returns:

Name Type Description
Any Any

The encrypted data tuple.

Source code in src/concrete_fhe_toolkit/ml/classes.py
687
688
689
690
691
692
693
694
695
696
697
698
699
700
def encrypt_data(self, X_train: Any, y_train: Any) -> Any:
    """Encrypts the training data.

    Args:
        X_train (Any): The training features.
        y_train (Any): The training labels.

    Returns:
        Any: The encrypted data tuple.
    """
    if self.circuit is None:
        raise ValueError("Circuit is not compiled. Call compile_trainer first.")

    return self.circuit.encrypt(X_train, y_train)

train_encrypted

train_encrypted(encrypted_X: Any, encrypted_y: Any) -> Any

Trains the model on the server using encrypted data.

Parameters:

Name Type Description Default
encrypted_X Any

Encrypted training features.

required
encrypted_y Any

Encrypted training labels.

required

Returns:

Name Type Description
Any Any

Encrypted results of the training circuit.

Source code in src/concrete_fhe_toolkit/ml/classes.py
702
703
704
705
706
707
708
709
710
711
712
713
714
715
def train_encrypted(self, encrypted_X: Any, encrypted_y: Any) -> Any:
    """Trains the model on the server using encrypted data.

    Args:
        encrypted_X (Any): Encrypted training features.
        encrypted_y (Any): Encrypted training labels.

    Returns:
        Any: Encrypted results of the training circuit.
    """
    if self.circuit is None:
        raise ValueError("Circuit is not compiled on server.")

    return self.circuit.run(encrypted_X, encrypted_y)

decrypt_and_finalize_model

decrypt_and_finalize_model(encrypted_results: Any, max_bit_width: Any = 8, *, epsilon: Any = None) -> Any

Decrypts the results and finalizes the Naive Bayes model.

Parameters:

Name Type Description Default
encrypted_results Any

The encrypted results from the server.

required
max_bit_width Any

Maximum bit width for the circuit. Defaults to 8.

8
epsilon Any

Epsilon for differential privacy. Defaults to None.

None

Returns:

Name Type Description
Any Any

The finalized FHENaiveBayes model.

Source code in src/concrete_fhe_toolkit/ml/classes.py
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
def decrypt_and_finalize_model(self, encrypted_results: Any, max_bit_width: Any=8, * ,epsilon: Any = None) -> Any:
    """Decrypts the results and finalizes the Naive Bayes model.

    Args:
        encrypted_results (Any): The encrypted results from the server.
        max_bit_width (Any, optional): Maximum bit width for the circuit. Defaults to 8.
        epsilon (Any, optional): Epsilon for differential privacy. Defaults to None.

    Returns:
        Any: The finalized FHENaiveBayes model.
    """
    raw_feature_counts, priors = self.circuit.decrypt(*encrypted_results)
    if epsilon is not None:
        noisy_feature_counts = []
        for row in raw_feature_counts:
            noisy_feature_counts.append(dp_release(row, sensitivity=1, epsilon=epsilon/2))
        priors_noisy = dp_release(priors, sensitivity=1, epsilon=epsilon/2)
        return self._finalize_model(noisy_feature_counts, priors_noisy, max_bit_width)

    return self._finalize_model(raw_feature_counts, priors, max_bit_width)

fit_encrypted

fit_encrypted(X_train: Any, y_train: Any, *, max_bit_width: Any = 8, thresholds: Any = None, epsilon: Any = None) -> Any

Fits the model securely on encrypted training data.

Parameters:

Name Type Description Default
X_train Any

The training features.

required
y_train Any

The training labels.

required
max_bit_width Any

Maximum bit width for the circuit. Defaults to 8.

8
thresholds Any

Thresholds for training. Defaults to None.

None
epsilon Any

Epsilon for differential privacy. Defaults to None.

None

Returns:

Name Type Description
Any Any

The trained FHENaiveBayes model.

Source code in src/concrete_fhe_toolkit/ml/classes.py
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
def fit_encrypted(self, X_train: Any, y_train: Any, * ,max_bit_width: Any = 8, thresholds: Any=None, epsilon: Any=None) -> Any:
    """Fits the model securely on encrypted training data.

    Args:
        X_train (Any): The training features.
        y_train (Any): The training labels.
        max_bit_width (Any, optional): Maximum bit width for the circuit. Defaults to 8.
        thresholds (Any, optional): Thresholds for training. Defaults to None.
        epsilon (Any, optional): Epsilon for differential privacy. Defaults to None.

    Returns:
        Any: The trained FHENaiveBayes model.
    """
    if(max_bit_width > 16):
        raise ValueError("The maximum supported bit width is 16")
    if(max_bit_width > 8):
        warnings.warn("Higher bit widths(>8) may result in longer computation times.", UserWarning, stacklevel=2)

    if thresholds is not None:
        from .training import make_raw_naive_bayes_training
        circuit_logic = make_raw_naive_bayes_training(thresholds)
        self.compiler = fhe.Compiler(circuit_logic, {"X_train_raw": "encrypted", "y_train_one_hot": "encrypted"})
    else:
        self.compiler = fhe.Compiler(naive_bayes_training,{"X_train": "encrypted", "y_train_one_hot": "encrypted"})

    self.circuit = self.compiler.compile([(X_train, y_train)])

    # The circuit returns raw counts (feature_counts, class_counts)
    raw_feature_counts, priors = self.circuit.encrypt_run_decrypt(X_train, y_train)
    if epsilon is not None:
        noisy_feature_counts = []
        for row in raw_feature_counts:
            noisy_feature_counts.append(dp_release(row, sensitivity=1, epsilon=epsilon/2))
        priors_noisy = dp_release(priors, sensitivity=1, epsilon=epsilon/2)
        return self._finalize_model(noisy_feature_counts, priors_noisy, max_bit_width)

    return self._finalize_model(raw_feature_counts, priors, max_bit_width)

FHEKMeans

Bases: FHEModel

Encrypted K-Means Inference Model (cluster assignment).

Assigns encrypted samples to the nearest public centroid. Train with FHEKMeansTrainer.fit_encrypted or provide centroids directly.

Parameters:

Name Type Description Default
centroids list

The public list of cluster centroids.

required
max_distance int

Upper bound on the squared distance from any sample to any centroid (sizes the argmin reduction).

required
Example
model = FHEKMeans(centroids=[[0,0], [10,10]], max_distance=200)
model.compile(dummy_inputset, batch_size=1)
Source code in src/concrete_fhe_toolkit/ml/classes.py
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
class FHEKMeans(FHEModel):
    """Encrypted K-Means Inference Model (cluster assignment).

    Assigns encrypted samples to the nearest public centroid. Train with
    ``FHEKMeansTrainer.fit_encrypted`` or provide centroids directly.

    Args:
        centroids (list): The public list of cluster centroids.
        max_distance (int): Upper bound on the squared distance from any
            sample to any centroid (sizes the argmin reduction).

    Example:
        ```python
        model = FHEKMeans(centroids=[[0,0], [10,10]], max_distance=200)
        model.compile(dummy_inputset, batch_size=1)
        ```
    """

    def __init__(self, centroids: Any, *, max_distance: Any):
        super().__init__()
        """Initialize the object."""
        from .models import nearest_centroid_inference

        self._nearest_centroid_inference = nearest_centroid_inference
        self.centroids = [list(centroid) for centroid in centroids]
        self.max_distance = max_distance

    def _circuit_logic(self, features: Any) -> Any:
        return self._nearest_centroid_inference(
            features,
            self.centroids,
            max_distance=self.max_distance,
        )