Skip to content

Serialization

concrete_fhe_toolkit.ml.serialization

Save and load FHE models as portable JSON files.

Every parametric model class can be serialized: its public parameters (weights, trees, centroids, tables) go into a small JSON document that can be versioned, shipped to a server, or reloaded years later. Compiled circuits and keys are not serialized — recompile after loading (that is cheap and keeps key material out of model files).

Example
from concrete_fhe_toolkit.ml import FHELogisticRegression
from concrete_fhe_toolkit.ml.serialization import load_model, save_model

model = FHELogisticRegression(weights=[3, 2], bias=-7)
save_model(model, "diagnosis.json")

restored = load_model("diagnosis.json")
restored.compile(inputset)
restored.predict(sample)

save_model

save_model(model: Any, path: str) -> None

[Client-Side Helper] Serialize a model's public parameters to a JSON file.

Parameters:

Name Type Description Default
model Any

Any registered FHEModel subclass instance (including trainer outputs).

required
path str

Destination file path.

required

Raises:

Type Description
ValueError

When the model class is not serializable (for example a custom subclass or an FHEPipeline — persist a pipeline by saving its final model and reconstructing the transformers).

Example
model = trainer.fit_encrypted(X_train, y_train)
save_model(model, "scorecard.json")

Returns:

Name Type Description
None None

This function does not return a value.

Source code in src/concrete_fhe_toolkit/ml/serialization.py
 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
@client_side_helper
def save_model(model: Any, path: str) -> None:
    """[Client-Side Helper] Serialize a model's public parameters to a JSON file.

    Args:
        model: Any registered ``FHEModel`` subclass instance (including
            trainer outputs).
        path: Destination file path.

    Raises:
        ValueError: When the model class is not serializable (for example
            a custom subclass or an ``FHEPipeline`` — persist a pipeline by
            saving its final model and reconstructing the transformers).

    Example:
        ```python
        model = trainer.fit_encrypted(X_train, y_train)
        save_model(model, "scorecard.json")
        ```

    Returns:
        None: This function does not return a value.
    """
    name = type(model).__name__
    if name not in _REGISTRY:
        raise ValueError(
            f"{name} is not serializable; supported models: "
            + ", ".join(sorted(_REGISTRY))
        )
    _, positional, keyword_only = _REGISTRY[name]
    params = {attr: getattr(model, attr) for attr in positional + keyword_only}
    extras = {
        attr: getattr(model, attr)
        for attr in _EXTRAS
        if hasattr(model, attr)
    }
    document = {
        "format": FORMAT,
        "format_version": FORMAT_VERSION,
        "model": name,
        "params": params,
        "extras": extras,
    }
    with open(path, "w", encoding="utf-8") as handle:
        json.dump(document, handle, indent=2)

load_model

load_model(path: str) -> Any

Load a model saved with :func:save_model.

The returned model is uncompiled — call compile(inputset) before predicting.

Parameters:

Name Type Description Default
path str

Path to a JSON file produced by :func:save_model.

required

Returns:

Type Description
Any

A fresh instance of the original model class.

Example
model = load_model("scorecard.json")
model.compile(inputset)
print(model.predict(sample))
Source code in src/concrete_fhe_toolkit/ml/serialization.py
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
@client_side_helper
def load_model(path: str) -> Any:
    """Load a model saved with :func:`save_model`.

    The returned model is uncompiled — call ``compile(inputset)`` before
    predicting.

    Args:
        path: Path to a JSON file produced by :func:`save_model`.

    Returns:
        A fresh instance of the original model class.

    Example:
        ```python
        model = load_model("scorecard.json")
        model.compile(inputset)
        print(model.predict(sample))
        ```
    """
    with open(path, encoding="utf-8") as handle:
        document = json.load(handle)

    if not isinstance(document, dict) or document.get("format") != FORMAT:
        raise ValueError(f"{path} is not a {FORMAT} file")
    version = document.get("format_version")
    if type(version) is not int or version != FORMAT_VERSION:
        raise ValueError(f"unsupported model format_version: {version!r}")
    name = document.get("model")
    if not isinstance(name, str) or name not in _REGISTRY:
        raise ValueError(f"unknown model class in file: {name!r}")

    cls, positional, keyword_only = _REGISTRY[name]
    params = document.get("params", {})
    if not isinstance(params, dict):
        raise ValueError("model params must be an object")
    extras = document.get("extras", {})
    if not isinstance(extras, dict):
        raise ValueError("model extras must be an object")
    missing = [attr for attr in positional + keyword_only if attr not in params]
    if missing:
        raise ValueError(f"model file is missing parameters: {', '.join(missing)}")

    model = cls(
        *[params[attr] for attr in positional],
        **{attr: params[attr] for attr in keyword_only},
    )
    for attr, value in extras.items():
        if attr in _EXTRAS:
            setattr(model, attr, value)
    return model