Skip to content

Serialization

mpneuralnetwork.serialization.save_model(model, filepath)

Saves the full model state to a .npz archive.

The archive contains: 1. architecture (JSON): Configuration of layers (type, size, etc.). 2. model_config (JSON): Loss, Optimizer config, and Optimizer globals (learning rate, etc.). 3. layer_{i}_{param}: Raw numpy arrays for weights and biases. 4. layer_{i}_state_{name}: Internal state (e.g., BatchNorm moving averages). 5. optimizer_{param}_{layer_param}: Optimizer state (momentum, velocity) for each parameter.

Parameters:

Name Type Description Default
model Model

The model instance to save.

required
filepath str

Destination path. If extension is missing, .npz is appended.

required
Source code in src/mpneuralnetwork/serialization.py
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
def save_model(model: "Model", filepath: str) -> None:
    """Saves the full model state to a `.npz` archive.

    The archive contains:
    1.  `architecture` (JSON): Configuration of layers (type, size, etc.).
    2.  `model_config` (JSON): Loss, Optimizer config, and Optimizer globals (learning rate, etc.).
    3.  `layer_{i}_{param}`: Raw numpy arrays for weights and biases.
    4.  `layer_{i}_state_{name}`: Internal state (e.g., BatchNorm moving averages).
    5.  `optimizer_{param}_{layer_param}`: Optimizer state (momentum, velocity) for each parameter.

    Args:
        model (Model): The model instance to save.
        filepath (str): Destination path. If extension is missing, `.npz` is appended.
    """
    layers_config: list = []
    for layer in model.layers:
        layers_config.append(layer.get_config())

    optimizer_globals: dict = {}
    optimizer_params: dict = {}

    if model.optimizer.params:
        for param_name, param in model.optimizer.params.items():
            if isinstance(param, (int, float, str, bool)) or param is None:
                optimizer_globals[param_name] = param
            else:
                optimizer_params[param_name] = param

    model_config: dict = {
        "loss": model.loss.get_config(),
        "optimizer": model.optimizer.get_config(),
        "optimizer_globals": optimizer_globals,
    }

    weights_dict: dict = get_model_weights(model.layers, optimizer_params)

    if filepath[-4:] != ".npz":
        filepath = f"{filepath}.npz"

    save_data: dict = weights_dict.copy()
    save_data["architecture"] = json.dumps(layers_config, cls=NumpyEncoder)
    save_data["model_config"] = json.dumps(model_config, cls=NumpyEncoder)

    np.savez_compressed(filepath, **save_data)

mpneuralnetwork.serialization.load_model(path)

Loads a full model from a .npz archive.

This function instantiates a new Model object, rebuilds the layer graph, initializes the optimizer and loss function, and then loads all weights and states (including optimizer momentum) into memory.

Parameters:

Name Type Description Default
path str | Path

Path to the .npz file.

required

Returns:

Name Type Description
Model Model

The fully restored model, ready for training or inference.

Source code in src/mpneuralnetwork/serialization.py
 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
def load_model(path: str | Path) -> "Model":
    """Loads a full model from a `.npz` archive.

    This function instantiates a new `Model` object, rebuilds the layer graph,
    initializes the optimizer and loss function, and then loads all weights
    and states (including optimizer momentum) into memory.

    Args:
        path (str | Path): Path to the `.npz` file.

    Returns:
        Model: The fully restored model, ready for training or inference.
    """
    from .model import Model

    filepath: str = str(path) if isinstance(path, Path) else path

    if filepath[-4:] != ".npz":
        filepath = f"{filepath}.npz"

    data: dict = np.load(filepath, allow_pickle=True)

    layers_config: dict = json.loads(str(data["architecture"]))
    model_config: dict = json.loads(str(data["model_config"]))

    model_layers: list = []
    for conf in layers_config:
        layer_type: str = str(conf.pop("type"))
        layer_class: Callable = _get_class(layer_type)
        layer = layer_class(**conf)
        model_layers.append(layer)

    loss_conf: dict = model_config["loss"]
    loss_type: str = str(loss_conf.pop("type"))
    loss_class: Callable = _get_class(loss_type)
    loss = loss_class(**loss_conf)

    optim_conf: dict | str = model_config["optimizer"]
    optim_type: str

    if isinstance(optim_conf, dict):
        optim_type = str(optim_conf.pop("type"))
    else:
        optim_type = str(optim_conf)
        optim_conf = {}

    optim_class: Callable = _get_class(optim_type)
    optimizer = optim_class(**optim_conf)

    if "optimizer_globals" in model_config:
        for param_name, param in model_config["optimizer_globals"].items():
            setattr(optimizer, param_name, param)

    model = Model(model_layers, loss, optimizer)
    restore_model_weights(model.layers, data, optimizer)

    return model