Skip to content

config

High level definition of CNN architectures.

@author: Nicola VIGANÒ, CEA-MEM, Grenoble, France

Classes:

Functions:

  • create_network

    Create and return a neural network model based on the provided network configuration.

  • create_optimizer

    Instantiates the desired optimizer for the given model.

NetworkParams

NetworkParams(
    n_features: int,
    n_channels_in: int = 1,
    n_channels_out: int = 1,
)

Bases: ABC

Abstract base class for storing network parameters.

Methods:

  • get_model

    Get the associated model with the selected parameters.

Source code in src/autoden/models/config.py
43
44
45
46
def __init__(self, n_features: int, n_channels_in: int = 1, n_channels_out: int = 1) -> None:
    self.n_channels_in = n_channels_in
    self.n_channels_out = n_channels_out
    self.n_features = n_features

get_model abstractmethod

get_model(
    device: str = "cuda" if is_available() else "cpu",
) -> Module

Get the associated model with the selected parameters.

Parameters:

  • device (str, default: 'cuda' if is_available() else 'cpu' ) –

    The device that the the model should run on, by default "cuda" if cuda is available, otherwise "cpu".

Returns:

  • Module

    The model.

Source code in src/autoden/models/config.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
@abstractmethod
def get_model(self, device: str = "cuda" if is_cuda_available() else "cpu") -> Module:
    """Get the associated model with the selected parameters.

    Parameters
    ----------
    device : str, optional
        The device that the the model should run on, by default "cuda" if cuda is available, otherwise "cpu".

    Returns
    -------
    Module
        The model.
    """

NetworkParamsDnCNN

NetworkParamsDnCNN(
    n_channels_in: int = 1,
    n_channels_out: int = 1,
    n_layers: int = 20,
    n_features: int = 64,
    kernel_size: int = 3,
    pad_mode: str = "replicate",
)

Bases: NetworkParams

Store DnCNN parameters.

Parameters:

  • n_channels_in (int, default: 1 ) –

    Number of input channels. Default is 1.

  • n_channels_out (int, default: 1 ) –

    Number of output channels. Default is 1.

  • n_layers (int, default: 20 ) –

    Number of layers. Default is 20.

  • n_features (int, default: 64 ) –

    Number of features. Default is 64.

  • kernel_size (int, default: 3 ) –

    Size of the convolutional kernel. Default is 3.

  • pad_mode (str, default: 'replicate' ) –

    Padding mode for the convolutional layers. Default is "replicate".

Methods:

  • get_model

    Get a DnCNN model with the selected parameters.

Source code in src/autoden/models/config.py
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
def __init__(
    self,
    n_channels_in: int = 1,
    n_channels_out: int = 1,
    n_layers: int = 20,
    n_features: int = 64,
    kernel_size: int = 3,
    pad_mode: str = "replicate",
) -> None:
    """Initialize the DnCNN network parameters definition.

    Parameters
    ----------
    n_channels_in : int, optional
        Number of input channels. Default is 1.
    n_channels_out : int, optional
        Number of output channels. Default is 1.
    n_layers : int, optional
        Number of layers. Default is 20.
    n_features : int, optional
        Number of features. Default is 64.
    kernel_size : int, optional
        Size of the convolutional kernel. Default is 3.
    pad_mode : str, optional
        Padding mode for the convolutional layers. Default is "replicate".
    """
    super().__init__(n_features=n_features, n_channels_in=n_channels_in, n_channels_out=n_channels_out)
    self.n_layers = n_layers
    self.kernel_size = kernel_size
    self.pad_mode = pad_mode

get_model

get_model(
    device: str = "cuda" if is_available() else "cpu",
) -> Module

Get a DnCNN model with the selected parameters.

Parameters:

  • device (str, default: 'cuda' if is_available() else 'cpu' ) –

    The device that the the model should run on, by default "cuda" if cuda is available, otherwise "cpu".

Returns:

  • Module

    The DnCNN model.

Source code in src/autoden/models/config.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
def get_model(self, device: str = "cuda" if is_cuda_available() else "cpu") -> Module:
    """Get a DnCNN model with the selected parameters.

    Parameters
    ----------
    device : str, optional
        The device that the the model should run on, by default "cuda" if cuda is available, otherwise "cpu".

    Returns
    -------
    Module
        The DnCNN model.
    """
    return DnCNN(
        n_channels_in=self.n_channels_in,
        n_channels_out=self.n_channels_out,
        n_layers=self.n_layers,
        n_features=self.n_features,
        kernel_size=self.kernel_size,
        pad_mode=self.pad_mode,
        device=device,
    )

NetworkParamsMSD

NetworkParamsMSD(
    n_channels_in: int = 1,
    n_channels_out: int = 1,
    n_layers: int = 12,
    n_features: int = 1,
    dilations: Sequence[int] | NDArray[integer] = arange(
        1, 4
    ),
    use_dilations: bool = True,
)

Bases: NetworkParams

Store MS-D net parameters.

Parameters:

  • n_channels_in (int, default: 1 ) –

    Number of input channels, by default 1.

  • n_channels_out (int, default: 1 ) –

    Number of output channels, by default 1.

  • n_layers (int, default: 12 ) –

    Number of layers in the network, by default 12.

  • n_features (int, default: 1 ) –

    Number of features, by default 1.

  • dilations (Sequence[int] | NDArray[integer], default: arange(1, 4) ) –

    Dilation values for the network, by default np.arange(1, 4).

  • use_dilations (bool, default: True ) –

    Whether to use dilations in the network, by default True.

Methods:

  • get_model

    Get a MS-D net model with the selected parameters.

Source code in src/autoden/models/config.py
 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
def __init__(
    self,
    n_channels_in: int = 1,
    n_channels_out: int = 1,
    n_layers: int = 12,
    n_features: int = 1,
    dilations: Sequence[int] | NDArray[np.integer] = np.arange(1, 4),
    use_dilations: bool = True,
) -> None:
    """Initialize the MS-D network parameters definition.

    Parameters
    ----------
    n_channels_in : int, optional
        Number of input channels, by default 1.
    n_channels_out : int, optional
        Number of output channels, by default 1.
    n_layers : int, optional
        Number of layers in the network, by default 12.
    n_features : int, optional
        Number of features, by default 1.
    dilations : Sequence[int] | NDArray[np.integer], optional
        Dilation values for the network, by default np.arange(1, 4).
    use_dilations : bool, optional
        Whether to use dilations in the network, by default True.
    """
    super().__init__(n_features=n_features, n_channels_in=n_channels_in, n_channels_out=n_channels_out)
    self.n_layers = n_layers
    self.dilations = dilations
    self.use_dilations = use_dilations

get_model

get_model(
    device: str = "cuda" if is_available() else "cpu",
) -> Module

Get a MS-D net model with the selected parameters.

Parameters:

  • device (str, default: 'cuda' if is_available() else 'cpu' ) –

    The device that the the model should run on, by default "cuda" if cuda is available, otherwise "cpu".

Returns:

  • Module

    The model.

Source code in src/autoden/models/config.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
def get_model(self, device: str = "cuda" if is_cuda_available() else "cpu") -> Module:
    """Get a MS-D net model with the selected parameters.

    Parameters
    ----------
    device : str, optional
        The device that the the model should run on, by default "cuda" if cuda is available, otherwise "cpu".

    Returns
    -------
    Module
        The model.
    """
    return MSDnet(
        n_channels_in=self.n_channels_in,
        n_channels_out=self.n_channels_out,
        n_layers=self.n_layers,
        n_features=self.n_features,
        dilations=list(self.dilations),
        device=device,
        use_dilations=self.use_dilations,
    )

NetworkParamsResnet

NetworkParamsResnet(
    n_channels_in: int = 1,
    n_channels_out: int = 1,
    n_layers: int = 10,
    n_features: int = 24,
    kernel_size: int = 3,
    pad_mode: str = "replicate",
)

Bases: NetworkParams

Store Resnet parameters.

Parameters:

  • n_channels_in (int, default: 1 ) –

    Number of input channels. Default is 1.

  • n_channels_out (int, default: 1 ) –

    Number of output channels. Default is 1.

  • n_layers (int, default: 10 ) –

    Number of layers. Default is 10.

  • n_features (int, default: 24 ) –

    Number of features. Default is 24.

  • kernel_size (int, default: 3 ) –

    Size of the convolutional kernel. Default is 3.

  • pad_mode (str, default: 'replicate' ) –

    Padding mode for the convolutional layers. Default is "replicate".

Methods:

  • get_model

    Get a Resnet model with the selected parameters.

Source code in src/autoden/models/config.py
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
def __init__(
    self,
    n_channels_in: int = 1,
    n_channels_out: int = 1,
    n_layers: int = 10,
    n_features: int = 24,
    kernel_size: int = 3,
    pad_mode: str = "replicate",
) -> None:
    """Initialize the Resnet network parameters definition.

    Parameters
    ----------
    n_channels_in : int, optional
        Number of input channels. Default is 1.
    n_channels_out : int, optional
        Number of output channels. Default is 1.
    n_layers : int, optional
        Number of layers. Default is 10.
    n_features : int, optional
        Number of features. Default is 24.
    kernel_size : int, optional
        Size of the convolutional kernel. Default is 3.
    pad_mode : str, optional
        Padding mode for the convolutional layers. Default is "replicate".
    """
    super().__init__(n_features=n_features, n_channels_in=n_channels_in, n_channels_out=n_channels_out)
    self.n_layers = n_layers
    self.kernel_size = kernel_size
    self.pad_mode = pad_mode

get_model

get_model(
    device: str = "cuda" if is_available() else "cpu",
) -> Module

Get a Resnet model with the selected parameters.

Parameters:

  • device (str, default: 'cuda' if is_available() else 'cpu' ) –

    The device that the the model should run on, by default "cuda" if cuda is available, otherwise "cpu".

Returns:

  • Module

    The Resnet model.

Source code in src/autoden/models/config.py
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
def get_model(self, device: str = "cuda" if is_cuda_available() else "cpu") -> Module:
    """Get a Resnet model with the selected parameters.

    Parameters
    ----------
    device : str, optional
        The device that the the model should run on, by default "cuda" if cuda is available, otherwise "cpu".

    Returns
    -------
    Module
        The Resnet model.
    """
    return Resnet(
        n_channels_in=self.n_channels_in,
        n_channels_out=self.n_channels_out,
        n_layers=self.n_layers,
        n_features=self.n_features,
        kernel_size=self.kernel_size,
        pad_mode=self.pad_mode,
        device=device,
    )

NetworkParamsUNet

NetworkParamsUNet(
    n_channels_in: int = 1,
    n_channels_out: int = 1,
    n_levels: int = DEFAULT_LEVELS,
    n_features: int = DEFAULT_FEATURES,
    n_channels_skip: int | None = None,
    bilinear: bool = True,
    pad_mode: str = "replicate",
)

Bases: NetworkParams

Store UNet parameters.

Parameters:

  • n_channels_in (int, default: 1 ) –

    Number of input channels. Default is 1.

  • n_channels_out (int, default: 1 ) –

    Number of output channels. Default is 1.

  • n_levels (int, default: DEFAULT_LEVELS ) –

    Number of levels in the UNet. Default is 3.

  • n_features (int, default: DEFAULT_FEATURES ) –

    Number of features in the UNet. Default is 32.

  • n_channels_skip (int, default: None ) –

    Number of skip connections channels. Default is None.

  • bilinear (bool, default: True ) –

    Whether to use bilinear interpolation. Default is True.

  • pad_mode (str, default: 'replicate' ) –

    Padding mode for convolutional layers. Default is "replicate".

Methods:

  • get_model

    Get a U-net model with the selected parameters.

Source code in src/autoden/models/config.py
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
def __init__(
    self,
    n_channels_in: int = 1,
    n_channels_out: int = 1,
    n_levels: int = DEFAULT_LEVELS,
    n_features: int = DEFAULT_FEATURES,
    n_channels_skip: int | None = None,
    bilinear: bool = True,
    pad_mode: str = "replicate",
) -> None:
    """Initialize the UNet network parameters definition.

    Parameters
    ----------
    n_channels_in : int, optional
        Number of input channels. Default is 1.
    n_channels_out : int, optional
        Number of output channels. Default is 1.
    n_levels : int, optional
        Number of levels in the UNet. Default is 3.
    n_features : int, optional
        Number of features in the UNet. Default is 32.
    n_channels_skip : int, optional
        Number of skip connections channels. Default is None.
    bilinear : bool, optional
        Whether to use bilinear interpolation. Default is True.
    pad_mode : str, optional
        Padding mode for convolutional layers. Default is "replicate".
    """
    super().__init__(n_features=n_features, n_channels_in=n_channels_in, n_channels_out=n_channels_out)
    self.n_levels = n_levels
    self.n_channels_skip = n_channels_skip
    self.bilinear = bilinear
    self.pad_mode = pad_mode

get_model

get_model(
    device: str = "cuda" if is_available() else "cpu",
) -> Module

Get a U-net model with the selected parameters.

Parameters:

  • device (str, default: 'cuda' if is_available() else 'cpu' ) –

    The device that the the model should run on, by default "cuda" if cuda is available, otherwise "cpu".

Returns:

  • Module

    The U-net model.

Source code in src/autoden/models/config.py
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
def get_model(self, device: str = "cuda" if is_cuda_available() else "cpu") -> Module:
    """Get a U-net model with the selected parameters.

    Parameters
    ----------
    device : str, optional
        The device that the the model should run on, by default "cuda" if cuda is available, otherwise "cpu".

    Returns
    -------
    Module
        The U-net model.
    """
    return UNet(
        n_channels_in=self.n_channels_in,
        n_channels_out=self.n_channels_out,
        n_features=self.n_features,
        n_levels=self.n_levels,
        n_channels_skip=self.n_channels_skip,
        bilinear=self.bilinear,
        pad_mode=self.pad_mode,
        device=device,
    )

SerializableModel

Bases: Protocol

Protocol for serializable models.

Provides a dictionary containing the initialization parameters of the model.

create_network

create_network(
    model: str | NetworkParams | Mapping | Module,
    init_params: Mapping | None = None,
    state_dict: Mapping | None = None,
    device: str = "cuda" if is_available() else "cpu",
) -> Module

Create and return a neural network model based on the provided network configuration.

Parameters:

  • model (str | NetworkParams | Mapping | Module) –

    The network configuration. It can be a string specifying the network type, an instance of NetworkParams, or an already instantiated Module. If a string is provided, it must be one of the supported network types: "msd", "unet", or "dncnn".

  • state_dict (Mapping | None, default: None ) –

    A dictionary containing the state dictionary of the model. If provided, the model's parameters will be loaded from this dictionary. Default is None.

  • device (str, default: 'cuda' if is_available() else 'cpu' ) –

    The device to which the model should be moved. Default is "cuda" if CUDA is available, otherwise "cpu".

Returns:

  • Module

    The created neural network model.

Raises:

  • ValueError

    If the provided network name is invalid or the network type is not supported.

Notes

The function supports the following network types: - "msd": Multi-Scale Dense Network. - "unet": U-Net. - "dncnn": Denoising Convolutional Neural Network.

Examples:

>>> net = create_network("unet")
>>> print(net)
Model UNet - num. parameters: 1234567
Source code in src/autoden/models/config.py
323
324
325
326
327
328
329
330
331
332
333
334
335
336
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
362
363
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
def create_network(
    model: str | NetworkParams | Mapping | Module,
    init_params: Mapping | None = None,
    state_dict: Mapping | None = None,
    device: str = "cuda" if is_cuda_available() else "cpu",
) -> Module:
    """
    Create and return a neural network model based on the provided network configuration.

    Parameters
    ----------
    model : str | NetworkParams | Mapping | Module
        The network configuration. It can be a string specifying the network type,
        an instance of `NetworkParams`, or an already instantiated `Module`.
        If a string is provided, it must be one of the supported network types:
        "msd", "unet", or "dncnn".
    state_dict : Mapping | None, optional
        A dictionary containing the state dictionary of the model. If provided,
        the model's parameters will be loaded from this dictionary. Default is None.
    device : str, optional
        The device to which the model should be moved. Default is "cuda" if CUDA is available,
        otherwise "cpu".

    Returns
    -------
    Module
        The created neural network model.

    Raises
    ------
    ValueError
        If the provided network name is invalid or the network type is not supported.

    Notes
    -----
    The function supports the following network types:
    - "msd": Multi-Scale Dense Network.
    - "unet": U-Net.
    - "dncnn": Denoising Convolutional Neural Network.

    Examples
    --------
    >>> net = create_network("unet")
    >>> print(net)
    Model UNet - num. parameters: 1234567
    """
    if isinstance(model, Mapping):
        if not all(key in model for key in ("model_class", "init_params", "state_dict")):
            raise ValueError(
                "Malformed model state dictionary. Expected mandatory fields: 'model_class', 'init_params', and 'state_dict'"
            )
        state_dict = model["state_dict"]
        init_params = model["init_params"]
        model = model["model_class"]

    if init_params is None:
        init_params = dict()
    else:
        init_params = dict(**init_params)

    for par in ("device", "verbose"):
        if par in init_params:
            del init_params[par]

    if isinstance(model, str):
        if model.lower() in ("msd", MSDnet.__name__.lower()):
            model = NetworkParamsMSD(**init_params)
        elif model.lower() == UNet.__name__.lower():
            model = NetworkParamsUNet(**init_params)
        elif model.lower() == DnCNN.__name__.lower():
            model = NetworkParamsDnCNN(**init_params)
        elif model.lower() == Resnet.__name__.lower():
            model = NetworkParamsResnet(**init_params)
        else:
            raise ValueError(f"Invalid model name: {model}")

    if isinstance(model, NetworkParams):
        net = model.get_model(device)
    elif isinstance(model, Module):
        net = model.to(device=device)
    else:
        raise ValueError(f"Invalid model type: {type(model)}")

    if state_dict is not None:
        net.load_state_dict(state_dict)
        net.to(device)  # Needed to ensure that the model lives in the correct device

    print(f"Model {net.__class__.__name__} - num. parameters: {sum(p.numel() for p in net.parameters() if p.requires_grad)}")
    return net

create_optimizer

create_optimizer(
    network: Module,
    algo: str = "adam",
    learning_rate: float = 0.001,
    weight_decay: float = 0.01,
    optim_state: Mapping | None = None,
) -> Optimizer

Instantiates the desired optimizer for the given model.

Parameters:

  • network (Module) –

    The network to train.

  • algo (str, default: 'adam' ) –

    The requested optimizer, by default "adam".

  • learning_rate (float, default: 0.001 ) –

    The desired learning rate, by default 1e-3.

  • weight_decay (float, default: 0.01 ) –

    The desired weight decay, by default 1e-2.

  • optim_state (Mapping | None, default: None ) –

    The state dictionary for the optimizer, by default None.

Returns:

  • Optimizer

    The chosen optimizer.

Raises:

  • ValueError

    If an unsupported algorithm is requested.

Source code in src/autoden/models/config.py
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
def create_optimizer(
    network: Module,
    algo: str = "adam",
    learning_rate: float = 1e-3,
    weight_decay: float = 1e-2,
    optim_state: Mapping | None = None,
) -> Optimizer:
    """Instantiates the desired optimizer for the given model.

    Parameters
    ----------
    network : torch.nn.Module
        The network to train.
    algo : str, optional
        The requested optimizer, by default "adam".
    learning_rate : float, optional
        The desired learning rate, by default 1e-3.
    weight_decay : float, optional
        The desired weight decay, by default 1e-2.
    optim_state : Mapping | None, optional
        The state dictionary for the optimizer, by default None.

    Returns
    -------
    torch.optim.Optimizer
        The chosen optimizer.

    Raises
    ------
    ValueError
        If an unsupported algorithm is requested.
    """
    if algo.lower() == "adam":
        optimizer = pt.optim.AdamW(network.parameters(), lr=learning_rate, weight_decay=weight_decay)
    elif algo.lower() == "sgd":
        optimizer = pt.optim.SGD(network.parameters(), lr=learning_rate, weight_decay=weight_decay)
    elif algo.lower() == "rmsprop":
        optimizer = pt.optim.RMSprop(network.parameters(), lr=learning_rate, weight_decay=weight_decay)
    elif algo.lower() == "lbfgs":
        optimizer = pt.optim.LBFGS(network.parameters(), lr=learning_rate, max_iter=10000, history_size=50)
    else:
        raise ValueError(f"Unknown algorithm: {algo}")

    if optim_state is not None:
        optimizer.load_state_dict(dict(**optim_state))

    return optimizer