Algorithms

Torch Algorithms

TorchFedAvgAlgo

class substrafl.algorithms.pytorch.TorchFedAvgAlgo(model: torch.nn.modules.module.Module, criterion: torch.nn.modules.loss._Loss, optimizer: torch.optim.optimizer.Optimizer, index_generator: substrafl.index_generator.base.BaseIndexGenerator, dataset: torch.utils.data.dataset.Dataset, scheduler: Optional[torch.optim.lr_scheduler._LRScheduler] = None, with_batch_norm_parameters: bool = False, seed: Optional[int] = None, use_gpu: bool = True, *args, **kwargs)

Bases: substrafl.algorithms.pytorch.torch_base_algo.TorchAlgo

To be inherited. Wraps the necessary operation so a torch model can be trained in the Federated Averaging strategy.

The train method:

  • updates the weights of the model with the aggregated weights,

  • initializes or loads the index generator,

  • calls the _local_train() method to do the local training

  • then gets the weight updates from the models and sends them to the aggregator.

The predict method generates the predictions.

The child class can override the _local_train() and _local_predict() methods, or other methods if necessary.

To add a custom parameter to the __init__ of the class, also add it to the call to super().__init__ as shown in the example with my_custom_extra_parameter. Only primitive types (str, int, …) are supported for extra parameters.

Example

class MyAlgo(TorchFedAvgAlgo):
    def __init__(
        self,
        my_custom_extra_parameter,
    ):
        super().__init__(
            model=perceptron,
            criterion=torch.nn.MSELoss(),
            optimizer=optimizer,
            index_generator=NpIndexGenerator(
                num_updates=100,
                batch_size=32,
            ),
            dataset=MyDataset,
            my_custom_extra_parameter=my_custom_extra_parameter,
        )
    def _local_train(
        self,
        train_dataset: torch.utils.data.Dataset,
    ):

        # Create torch dataloader from the automatically instantiated dataset
        # ``train_dataset = self._dataset(datasamples=datasamples, is_inference=False)`` is executed prior
        #  the execution of this function
        train_data_loader = torch.utils.data.DataLoader(train_dataset, batch_sampler=self._index_generator)

        for x_batch, y_batch in train_data_loader:

            # Forward pass
            y_pred = self._model(x_batch)

            # Compute Loss
            loss = self._criterion(y_pred, y_batch)
            self._optimizer.zero_grad()
            loss.backward()
            self._optimizer.step()

            if self._scheduler is not None:
                self._scheduler.step()

The __init__ functions is called at each call of the train() or predict() function For round>=2, some attributes will then be overwritten by their previous states in the load() function, before the train() or predict() function is ran.

Parameters
  • model (torch.nn.modules.module.Module) – A torch model.

  • criterion (torch.nn.modules.loss._Loss) – A torch criterion (loss).

  • optimizer (torch.optim.Optimizer) – A torch optimizer linked to the model.

  • index_generator (BaseIndexGenerator) – a stateful index generator. Must inherit from BaseIndexGenerator. The __next__ method shall return a python object (batch_index) which is used for selecting each batch from the output of the get_data method of the opener during training in this way: x[batch_index], y[batch_index]. If overridden, the generator class must be defined either as part of a package or in a different file than the one from which the execute_experiment function is called. This generator is used as stateful batch_sampler of the data loader created from the given dataset

  • dataset (torch.utils.data.Dataset) – an instantiable dataset class whose __init__ arguments are x, y and is_inference. The torch datasets used for both training and inference will be instantiate from it prior to the _local_train execution and within the predict method. The __getitem__ methods of those generated datasets must return both x (training data) and y (target values) when is_inference is set to False and only x (testing data) when is_inference is set to True. This behavior can be changed by re-writing the _local_train or predict methods.

  • scheduler (torch.optim.lr_scheduler._LRScheduler, Optional) – A torch scheduler that will be called at every batch. If None, no scheduler will be used. Defaults to None.

  • with_batch_norm_parameters (bool) – Whether to include the batch norm layer parameters in the fed avg strategy. Defaults to False.

  • seed (Optional[int]) – Seed set at the algo initialization on each organization. Defaults to None.

  • use_gpu (bool) – Whether to use the GPUs if they are available. Defaults to True.

_local_predict(predict_dataset: torch.utils.data.dataset.Dataset, predictions_path)

Execute the following operations:

  • Create the torch dataloader using the index generator batch size.

  • Set the model to eval mode

  • Save the predictions using the _save_predictions() function.

Parameters

predict_dataset (torch.utils.data.Dataset) – predict_dataset build from the x returned by the opener.

Important

The onus is on the user to save the compute predictions. Substrafl provides the _save_predictions() to do so. The user can load those predictions from a metric file with the command: y_pred = np.load(inputs['predictions']).

Raises

BatchSizeNotFoundError – No default batch size have been found to perform local prediction. Please overwrite the predict function of your algorithm.

Parameters

predict_dataset (torch.utils.data.dataset.Dataset) –

_local_train(train_dataset: torch.utils.data.dataset.Dataset)

Local train method. Contains the local training loop.

Train the model on num_updates minibatches, using the self._index_generator generator as batch sampler for the torch dataset.

Parameters

train_dataset (torch.utils.data.Dataset) – train_dataset build from the x and y returned by the opener.

Important

You must use next(self._index_generator) as batch sampler, to ensure that the batches you are using are correct between 2 rounds of the federated learning strategy.

Example

# Create torch dataloader
train_data_loader = torch.utils.data.DataLoader(train_dataset, batch_sampler=self._index_generator)

for x_batch, y_batch in train_data_loader:

    # Forward pass
    y_pred = self._model(x_batch)

    # Compute Loss
    loss = self._criterion(y_pred, y_batch)
    self._optimizer.zero_grad()
    loss.backward()
    self._optimizer.step()

    if self._scheduler is not None:
        self._scheduler.step()
_save_predictions(predictions: torch.Tensor, predictions_path: os.PathLike)

Save the predictions under the numpy format.

Parameters
  • predictions (torch.Tensor) – predictions to save.

  • predictions_path (os.PathLike) – destination file to save predictions.

initialize(shared_states)

Empty function, useful to load the algo in the different organizations in order to perform an evaluation before any training step.

Parameters

shared_states – Unused but enforced signature due to the @remote decorator.

load_local_state(path: pathlib.Path) substrafl.algorithms.pytorch.torch_base_algo.TorchAlgo

Load the stateful arguments of this class. Child classes do not need to override that function.

Parameters

path (pathlib.Path) – The path where the class has been saved.

Returns

The class with the loaded elements.

Return type

TorchAlgo

property model: torch.nn.modules.module.Module

Model exposed when the user downloads the model

Returns

model

Return type

torch.nn.Module

predict(datasamples: Any, shared_state: Optional[Any] = None, predictions_path: os.PathLike = None) Any

Execute the following operations:

  • Create the test torch dataset.

  • Execute and return the results of the self._local_predict method

Parameters
  • datasamples (Any) – Input data

  • shared_state (Any) – Latest train task shared state (output of the train method)

  • predictions_path (os.PathLike) – Destination file to save predictions

Return type

Any

save_local_state(path: pathlib.Path) None

Saves all the stateful elements of the class to the specified path. Child classes do not need to override that function.

Parameters

path (pathlib.Path) – A path where to save the class.

Returns

None

Return type

None

property strategies: List[substrafl.strategies.schemas.StrategyName]

List of compatible strategies

Returns

typing.List[StrategyName]

Return type

List

summary()

Summary of the class to be exposed in the experiment summary file

Returns

a json-serializable dict with the attributes the user wants to store

Return type

dict

train(datasamples: Any, shared_state: Optional[substrafl.strategies.schemas.FedAvgAveragedState] = None) substrafl.strategies.schemas.FedAvgSharedState

Train method of the fed avg strategy implemented with torch. This method will execute the following operations:

  • instantiates the provided (or default) batch indexer

  • if a shared state is passed, set the parameters of the model to the provided shared state

  • train the model for n_updates

  • compute the weight update

Parameters
  • datasamples (Any) – Input data returned by the get_data method from the opener.

  • shared_state (FedAvgAveragedState, Optional) – Dict containing torch parameters that will be set to the model. Defaults to None.

Returns

weight update (delta between fine-tuned weights and previous weights)

Return type

FedAvgSharedState

TorchScaffoldAlgo

class substrafl.algorithms.pytorch.torch_scaffold_algo.CUpdateRule(value)

Bases: enum.IntEnum

The rule used to update the client control variate

Values:

  • STABLE (1): The stable rule, I in the Scaffold paper (not implemented)

  • FAST (2): The fast rule, II in the Scaffold paper

class substrafl.algorithms.pytorch.torch_scaffold_algo.TorchScaffoldAlgo(model: torch.nn.modules.module.Module, criterion: torch.nn.modules.loss._Loss, optimizer: torch.optim.optimizer.Optimizer, index_generator: substrafl.index_generator.base.BaseIndexGenerator, dataset: torch.utils.data.dataset.Dataset, scheduler: Optional[torch.optim.lr_scheduler._LRScheduler] = None, with_batch_norm_parameters: bool = False, c_update_rule: substrafl.algorithms.pytorch.torch_scaffold_algo.CUpdateRule = CUpdateRule.FAST, seed: Optional[int] = None, use_gpu: bool = True, *args, **kwargs)

Bases: substrafl.algorithms.pytorch.torch_base_algo.TorchAlgo

To be inherited. Wraps the necessary operation so a torch model can be trained in the Scaffold strategy.

The train method:

  • updates the weights of the model with the aggregated weights,

  • initializes or loads the index generator,

  • calls the _local_train() method to do the local training

  • then gets the weight updates from the models and sends them to the aggregator.

The predict method generates the predictions.

The child class can override the _local_train() and _local_predict() methods, or other methods if necessary.

To add a custom parameter to the __init__``of the class, also add it to the call to ``super().__init__` as shown in the example with my_custom_extra_parameter. Only primitive types (str, int, …) are supported for extra parameters.

Example

class MyAlgo(TorchScaffoldAlgo):
    def __init__(
        self,
        my_custom_extra_parameter,
    ):
        super().__init__(
            model=perceptron,
            criterion=torch.nn.MSELoss(),
            optimizer=optimizer,
            num_updates=100,
            index_generator=NpIndexGenerator(
                num_updates=10,
                batch_size=32,
            ),
            dataset=MyDataset,
            my_custom_extra_parameter=my_custom_extra_parameter,
        )
    def _local_train(
        self,
        train_dataset: torch.utils.data.Dataset,
    ):
        # Create torch dataloader
        # ``train_dataset = self._dataset(datasamples=datasamples, is_inference=False)`` is executed
        # prior the execution of this function
        train_data_loader = torch.utils.data.DataLoader(train_dataset, batch_sampler=self._index_generator)

        for x_batch, y_batch in train_data_loader:

            # Forward pass
            y_pred = self._model(x_batch)
            # Compute Loss
            loss = self._criterion(y_pred, y_batch)
            self._optimizer.zero_grad()
            # backward pass: compute the gradients
            loss.backward()
            # forward pass: update the weights.
            self._optimizer.step()

            # Scaffold specific: to keep between _optimizer.step() and _scheduler.step()
            # _scheduler and Scaffold strategies are not scientifically validated, it is not
            # recommended to use one. If one is used, _scheduler.step() must be called after
            # _scaffold_parameters_update()
            self._scaffold_parameters_update()
            if self._scheduler is not None:
                self._scheduler.step()

The __init__ function is called at each call of the train or predict function For round>2, some attributes will then be overwritten by their previous states in the load() function, before the train() or predict() function is ran.

Parameters
  • model (torch.nn.modules.module.Module) – A torch model.

  • criterion (torch.nn.modules.loss._Loss) – A torch criterion (loss).

  • optimizer (torch.optim.Optimizer) – A torch optimizer linked to the model.

  • index_generator (BaseIndexGenerator) – a stateful index generator. Must inherit from BaseIndexGenerator. The __next__ method shall return a python object (batch_index) which is used for selecting each batch from the output of the get_data method of the opener during training in this way: x[batch_index], y[batch_index]. If overridden, the generator class must be defined either as part of a package or in a different file than the one from which the execute_experiment function is called. This generator is used as stateful batch_sampler of the data loader created from the given dataset

  • dataset (torch.utils.data.Dataset) – an instantiable dataset class whose __init__ arguments are x, y and is_inference. The torch datasets used for both training and inference will be instantiate from it prior to the _local_train execution and within the predict method. The __getitem__ methods of those generated datasets must return both x (training data) and y (target values) when is_inference is set to False and only x (testing data) when is_inference is set to True. This behavior can be changed by re-writing the _local_train or predict methods.

  • scheduler (torch.optim.lr_scheduler._LRScheduler, Optional) – A torch scheduler that will be called at every batch. If None, no scheduler will be used. Defaults to None.

  • with_batch_norm_parameters (bool) – Whether to include the batch norm layer parameters in the fed avg strategy. Defaults to False.

  • c_update_rule (CUpdateRule) – The rule used to update the client control variate. Defaults to CUpdateRule.FAST.

  • seed (Optional[int]) – Seed set at the algo initialization on each organization. Defaults to None.

  • use_gpu (bool) – Whether to use the GPUs if they are available. Defaults to True.

Raises

NumUpdatesValueError – If num_updates is inferior or equal to zero.

_local_predict(predict_dataset: torch.utils.data.dataset.Dataset, predictions_path)

Execute the following operations:

  • Create the torch dataloader using the index generator batch size.

  • Set the model to eval mode

  • Save the predictions using the _save_predictions() function.

Parameters

predict_dataset (torch.utils.data.Dataset) – predict_dataset build from the x returned by the opener.

Important

The onus is on the user to save the compute predictions. Substrafl provides the _save_predictions() to do so. The user can load those predictions from a metric file with the command: y_pred = np.load(inputs['predictions']).

Raises

BatchSizeNotFoundError – No default batch size have been found to perform local prediction. Please overwrite the predict function of your algorithm.

Parameters

predict_dataset (torch.utils.data.dataset.Dataset) –

_local_train(train_dataset: torch.utils.data.dataset.Dataset)

Local train method. Contains the local training loop.

Train the model on num_updates minibatches, using the self._index_generator generator as batch sampler for the torch dataset.

Parameters

train_dataset (torch.utils.data.Dataset) – train_dataset build from the x and y returned by the opener.

Important

You must use next(self._index_generator) at each minibatch, to ensure that you are using the batches are correct between 2 rounds of the federated learning strategy.

Example

# Create torch dataloader
train_data_loader = torch.utils.data.DataLoader(train_dataset, batch_sampler=self._index_generator)

for x_batch, y_batch in train_data_loader:

    # Forward pass
    y_pred = self._model(x_batch)

    # Compute Loss
    loss = self._criterion(y_pred, y_batch)
    self._optimizer.zero_grad()
    loss.backward()
    self._optimizer.step()

    # Scaffold specific function to call between self._optimizer.step() and self._scheduler.step()
    self._scaffold_parameters_update()

    if self._scheduler is not None:
        self._scheduler.step()
_save_predictions(predictions: torch.Tensor, predictions_path: os.PathLike)

Save the predictions under the numpy format.

Parameters
  • predictions (torch.Tensor) – predictions to save.

  • predictions_path (os.PathLike) – destination file to save predictions.

_scaffold_parameters_update()

Must be called for each update after the optimizer.step() operation.

initialize(shared_states)

Empty function, useful to load the algo in the different organizations in order to perform an evaluation before any training step.

Parameters

shared_states – Unused but enforced signature due to the @remote decorator.

load_local_state(path: pathlib.Path) substrafl.algorithms.pytorch.torch_base_algo.TorchAlgo

Load the stateful arguments of this class. Child classes do not need to override that function.

Parameters

path (pathlib.Path) – The path where the class has been saved.

Returns

The class with the loaded elements.

Return type

TorchAlgo

property model: torch.nn.modules.module.Module

Model exposed when the user downloads the model

Returns

model

Return type

torch.nn.Module

predict(datasamples: Any, shared_state: Optional[Any] = None, predictions_path: os.PathLike = None) Any

Execute the following operations:

  • Create the test torch dataset.

  • Execute and return the results of the self._local_predict method

Parameters
  • datasamples (Any) – Input data

  • shared_state (Any) – Latest train task shared state (output of the train method)

  • predictions_path (os.PathLike) – Destination file to save predictions

Return type

Any

save_local_state(path: pathlib.Path) None

Saves all the stateful elements of the class to the specified path. Child classes do not need to override that function.

Parameters

path (pathlib.Path) – A path where to save the class.

Returns

None

Return type

None

property strategies: List[substrafl.strategies.schemas.StrategyName]

List of compatible strategies

Returns

typing.List[StrategyName]

Return type

List

summary()

Summary of the class to be exposed in the experiment summary file

Returns

a json-serializable dict with the attributes the user wants to store

Return type

dict

train(datasamples: Any, shared_state: Optional[substrafl.strategies.schemas.ScaffoldAveragedStates] = None) substrafl.strategies.schemas.ScaffoldSharedState

Train method of the Scaffold strategy implemented with torch. This method will execute the following operations:

  • instantiates the provided (or default) batch indexer

  • if a shared state is passed, set the parameters of the model to the provided shared state

  • train the model for n_updates

  • compute the weight update and control variate update

Parameters
  • datasamples (Any) – Input data returned by the get_data method from the opener.

  • shared_state (Optional[ScaffoldAveragedStates]) – Shared state sent by the aggregate_organization (returned by the func strategies.scaffold.avg_shared_states) Defaults to None.

Returns

the shared states of the Algo

Return type

ScaffoldSharedState

TorchNewtonRaphsonAlgo

class substrafl.algorithms.pytorch.torch_newton_raphson_algo.TorchNewtonRaphsonAlgo(model: torch.nn.modules.module.Module, criterion: torch.nn.modules.loss._Loss, batch_size: Optional[int], dataset: torch.utils.data.dataset.Dataset, l2_coeff: float = 0, with_batch_norm_parameters: bool = False, seed: Optional[int] = None, use_gpu: bool = True, *args, **kwargs)

Bases: substrafl.algorithms.pytorch.torch_base_algo.TorchAlgo

To be inherited. Wraps the necessary operation so a torch model can be trained in the Newton-Raphson strategy.

The train method:

  • updates the weights of the model with the calculated weight updates

  • creates and initializes the index generator with the given batch size

  • calls the _local_train() method to compute the local gradients and Hessian and sends them to the aggregator.

  • a L2 regularization can be applied to the loss by settings l2_coeff different to zero (default value). L2 regularization adds numerical stability when inverting the hessian.

The child class can overwrite _local_train() and _local_predict(), or other methods if necessary.

To add a custom parameter to the __init__ of the class, also add it to the call to super().__init__.

The __init__ function is called at each call of the train or predict function.

For round>=2, some attributes will then be overwritten by their previous states in the load_local_state() function, before the train or predict function is ran.

TorchNewtonRaphsonAlgo computes its NewtonRaphsonSharedState (gradients and Hessian matrix) on all the samples of the dataset. Data might be split into mini-batches to prevent loading too much data at once.

Parameters
  • model (torch.nn.modules.module.Module) – A torch model.

  • criterion (torch.nn.modules.loss._Loss) – A torch criterion (loss).

  • batch_size (int) – The size of the batch. If set to None it will be set to the number of samples in the dataset. Note that dividing the data to batches is done only to avoid the memory issues. The weights are updated only at the end of the epoch.

  • dataset (torch.utils.data.Dataset) – an instantiable dataset class whose __init__ arguments are x, y and is_inference. The torch datasets used for both training and inference will be instantiate from it prior to the _local_train execution and within the predict method. The __getitem__ methods of those generated datasets must return both x (training data) and y (target values) when is_inference is set to False and only x (testing data) when is_inference is set to True. This behavior can be changed by re-writing the _local_train or predict methods.

  • l2_coeff (float) – L2 regularization coefficient. The larger l2_coeff is, the better the stability of the hessian matrix will be, however the convergence might be slower. Defaults to 0.

  • with_batch_norm_parameters (bool) – Whether to include the batch norm layer parameters in the Newton-Raphson strategy. Defaults to False.

  • seed (Optional[int]) – Seed set at the algo initialization on each organization. Defaults to None.

  • use_gpu (bool) – Whether to use the GPUs if they are available. Defaults to True.

_local_predict(predict_dataset: torch.utils.data.dataset.Dataset, predictions_path)

Execute the following operations:

  • Create the torch dataloader using the batch size given at the __init__ of the class

  • Set the model to eval mode

  • Return the predictions

Parameters

predict_dataset (torch.utils.data.Dataset) – predict_dataset build from the x returned by the opener.

_local_train(train_dataset: torch.utils.data.dataset.Dataset)

Local train method. Contains the local training loop.

Train the model on num_updates minibatches, using the self._index_generator generator as batch sampler for the torch dataset.

Parameters

train_dataset (torch.utils.data.Dataset) – train_dataset build from the x and y returned by the opener.

Important

You must use next(self._index_generator) at each minibatch, to ensure that you are using the batches are correct between 2 rounds of the Newton Raphson strategy.

Important

Call the function self._update_gradients_and_hessian(loss, current_batch_size) after computing the loss and the current_batch_size.

Example

# As the parameters of the model don't change during the loop, the l2 regularization is constant and
# can be calculated only once for all the batches.
l2_reg = self._l2_reg()

# Create torch dataloader
train_data_loader = torch.utils.data.DataLoader(train_dataset, batch_sampler=self._index_generator)

for x_batch, y_batch in train_data_loader:

    # Forward pass
    y_pred = self._model(x_batch)

    # Compute Loss
    loss = self._criterion(y_pred, y_batch)

    # L2 regularization
    loss += l2_reg

    current_batch_size = len(x_batch)

    # NEWTON RAPHSON specific function, to call after computing the loss and the current_batch_size.

    self._update_gradients_and_hessian(loss, current_batch_size)
_save_predictions(predictions: torch.Tensor, predictions_path: os.PathLike)

Save the predictions under the numpy format.

Parameters
  • predictions (torch.Tensor) – predictions to save.

  • predictions_path (os.PathLike) – destination file to save predictions.

_update_gradients_and_hessian(loss: torch.Tensor, current_batch_size: int)

Updates the gradients and hessian matrices.

Parameters
  • loss (torch.Tensor) – the loss to compute the gradients and hessian from.

  • current_batch_size (int) – The length of the batch used to compute the given loss.

initialize(shared_states)

Empty function, useful to load the algo in the different organizations in order to perform an evaluation before any training step.

Parameters

shared_states – Unused but enforced signature due to the @remote decorator.

load_local_state(path: pathlib.Path) substrafl.algorithms.pytorch.torch_base_algo.TorchAlgo

Load the stateful arguments of this class. Child classes do not need to override that function.

Parameters

path (pathlib.Path) – The path where the class has been saved.

Returns

The class with the loaded elements.

Return type

TorchAlgo

property model: torch.nn.modules.module.Module

Model exposed when the user downloads the model

Returns

model

Return type

torch.nn.Module

predict(datasamples: Any, shared_state: Optional[Any] = None, predictions_path: os.PathLike = None) Any

Execute the following operations:

  • Create the test torch dataset.

  • Execute and return the results of the self._local_predict method

Parameters
  • datasamples (Any) – Input data

  • shared_state (Any) – Latest train task shared state (output of the train method)

  • predictions_path (os.PathLike) – Destination file to save predictions

Return type

Any

save_local_state(path: pathlib.Path) None

Saves all the stateful elements of the class to the specified path. Child classes do not need to override that function.

Parameters

path (pathlib.Path) – A path where to save the class.

Returns

None

Return type

None

property strategies: List[substrafl.strategies.schemas.StrategyName]

List of compatible strategies

Returns

typing.List[StrategyName]

Return type

List

summary()

Summary of the class to be exposed in the experiment summary file

Returns

a json-serializable dict with the attributes the user wants to store

Return type

dict

train(datasamples: Any, shared_state: Optional[substrafl.strategies.schemas.NewtonRaphsonAveragedStates] = None) substrafl.strategies.schemas.NewtonRaphsonSharedState

Train method of the Newton Raphson strategy implemented with torch. This method will execute the following operations:

  • creates and initializes the index generator

  • if a shared state is passed, set the weights of the model to the provided shared state weights

  • initializes hessians and gradient

  • calls the

    _local_train() method to compute the local gradients and Hessian and sends them to the aggregator.

  • a L2 regularization can be applied to the loss by settings l2_coeff different to zero (default value)

Parameters
  • datasamples (Any) – Input data returned by the get_data method from the opener.

  • shared_state (NewtonRaphsonAveragedStates, Optional) – Dict containing torch parameters that will be set to the model. Defaults to None.

Returns

local gradients, local Hessian and the number of samples they were computed from.

Return type

NewtonRaphsonSharedState

Raises

NegativeHessianMatrixError – Hessian matrix must be positive semi-definite to correspond to a convex problem.

TorchFedPCAAlgo

class substrafl.algorithms.pytorch.torch_fed_pca_algo.TorchFedPCAAlgo(dataset: torch.utils.data.dataset.Dataset, in_features: int, out_features: int, batch_size: Optional[int] = None, seed: int = 1, use_gpu: bool = True, *args, **kwargs)

Bases: substrafl.algorithms.pytorch.torch_base_algo.TorchAlgo

To be inherited. Wraps the necessary operation so a torch model can be trained in the Federated PCA strategy.

The train method:

  • computes the local mean during the first round

  • computes the covariance matrix during the second round

  • computes the eigen vectors regarding the shared covariance matrix for all next rounds

The predict method generates the eigen vectors.

To add a custom parameter to the __init__ of the class, also add it to the call to super().__init__ as shown in the example with my_custom_extra_parameter. Only primitive types (str, int, …) are supported for extra parameters.

Example

class MyAlgo(TorchFedPCAAlgo):
    def __init__(
        self,
        my_custom_extra_parameter,
    ):
        super().__init__(
            in_features=10,
            out_features=2,
            batch_size=16,
            dataset=my_dataset,
            seed=seed,
            my_custom_extra_parameter=my_custom_extra_parameter,
        )

The __init__ function is called at each call of the train() or predict() function Some attributes will then be overwritten by their previous states in the load() function, before the train() or predict() function is run.

Parameters
  • dataset (torch.utils.data.Dataset) – input data on which to perform PCA

  • in_features (int) – input data dimensionality

  • out_features (int) – dimension to keep after PCA

  • batch_size (Optional[int]) – mini-batch size

  • seed (int) – random generator seed. The seed is mandatory. Default to 1.

  • use_gpu (bool) – whether to use GPU or not. Default to True.

_instantiate_index_generator(n_samples: int)

Create a generator for batches data points indices.

Parameters

n_samples (int) – the desired batch size.

Returns

the index generator.

Return type

NpIndexGenerator

_local_predict(predict_dataset: torch.utils.data.dataset.Dataset, predictions_path)

Execute the following operations:

  • Create the torch dataloader using the index generator batch size.

  • Set the model to eval mode

  • Save the predictions using the _save_predictions() function.

Parameters

predict_dataset (torch.utils.data.Dataset) – predict_dataset build from the x returned by the opener.

Important

The onus is on the user to save the compute predictions. Substrafl provides the _save_predictions() to do so. The user can load those predictions from a metric file with the command: y_pred = np.load(inputs['predictions']).

Raises

BatchSizeNotFoundError – No default batch size have been found to perform local prediction. Please overwrite the predict function of your algorithm.

Parameters

predict_dataset (torch.utils.data.dataset.Dataset) –

_local_train(train_dataset: torch.utils.data.dataset.Dataset)

Local train method. Contains the local training loop.

Train the model on num_updates minibatches, using the self._index_generator generator as batch sampler for the torch dataset.

Parameters

train_dataset (torch.utils.data.Dataset) – train_dataset build from the x and y returned by the opener.

Important

You must use next(self._index_generator) as batch sampler, to ensure that the batches you are using are correct between 2 rounds of the federated learning strategy.

Example

# Create torch dataloader
train_data_loader = torch.utils.data.DataLoader(train_dataset, batch_sampler=self._index_generator)

for x_batch, y_batch in train_data_loader:

    # Forward pass
    y_pred = self._model(x_batch)

    # Compute Loss
    loss = self._criterion(y_pred, y_batch)
    self._optimizer.zero_grad()
    loss.backward()
    self._optimizer.step()

    if self._scheduler is not None:
        self._scheduler.step()
_save_predictions(predictions: torch.Tensor, predictions_path: os.PathLike)

Save the predictions under the numpy format.

Parameters
  • predictions (torch.Tensor) – predictions to save.

  • predictions_path (os.PathLike) – destination file to save predictions.

property eigen_vectors: torch.Tensor

Current computed eigen vectors.

Returns

eigen vectors

Return type

torch.Tensor

initialize(shared_states)

Empty function, useful to load the algo in the different organizations in order to perform an evaluation before any training step.

Parameters

shared_states – Unused but enforced signature due to the @remote decorator.

load_local_state(path: pathlib.Path) substrafl.algorithms.pytorch.torch_base_algo.TorchAlgo

Load the stateful arguments of this class. Child classes do not need to override that function.

Parameters

path (pathlib.Path) – The path where the class has been saved.

Returns

The class with the loaded elements.

Return type

TorchAlgo

property model: torch.nn.modules.module.Module

Model exposed when the user downloads the model

Returns

model

Return type

torch.nn.Module

predict(datasamples: Any, shared_state: Optional[Any] = None, predictions_path: pathlib.Path = None) Any

Execute the following operations:

  • Create the test torch dataset.

  • Execute the reduction dimension of the test dataset, and save them as predictions on the prediction path.

Parameters
  • datasamples (Any) – Input data

  • shared_state (Any) – Latest train task shared state (output of the train method)

  • predictions_path (os.PathLike) – Destination file to save predictions

Return type

Any

save_local_state(path: pathlib.Path) None

Saves all the stateful elements of the class to the specified path. Child classes do not need to override that function.

Parameters

path (pathlib.Path) – A path where to save the class.

Returns

None

Return type

None

property strategies: List[substrafl.strategies.schemas.StrategyName]

List of compatible strategies.

Returns

typing.List[StrategyName]

Return type

List

summary()

Summary of the class to be exposed in the experiment summary file. Implement this function in the child class to add strategy-specific variables. The variables must be json-serializable.

Example

def summary(self):
    summary = super().summary()
    summary.update(
        "strategy_specific_variable": self._strategy_specific_variable,
    )
    return summary
Returns

a json-serializable dict with the attributes the user wants to store

Return type

dict

train(datasamples: Any, shared_state: Optional[substrafl.strategies.schemas.FedPCAAveragedState] = None) substrafl.strategies.schemas.FedPCASharedState

Train the local model for one round of the federated algorithm.

Important

This functions behaves differently depending on the round of the federated algorithm for PCA. In the first round, the mean vector is computed. In the second round, the covariance matrix is computed. The computation of the eigenvectors starts from round 3. A sufficient number of rounds is necessary for the method to produce accurate eigenvectors. This can be monitored through mean square reconstruction error which should reach a global minimum when the algorithm has converged.

Parameters
  • datasamples (Any) – input data

  • shared_state (Optional[FedPCAAveragedState]) – incoming FedPCAAveragedState obtained at the previous round of the federated algorithm (after aggregation). It contains the federatively learnt eigenvectors. Defaults to None.

Returns

updated model and parameters shared for aggregation.

Return type

FedPCASharedState

transform(input_tensor: torch.Tensor) torch.Tensor

Project the input vector on the eigen vector subspace. Input tensor shape must be of shape (N, in_features). The returned tensor will be of shape (N, out_features).

Parameters

input_tensor (torch.Tensor) – input tensor to compute the dimension reduction on.

Returns

projected tensor on the computed eigen vector dimension.

Return type

torch.Tensor

class substrafl.algorithms.pytorch.torch_fed_pca_algo.TorchLinearModel(in_features: int, out_features: int)

Bases: torch.nn.modules.module.Module

Define linear model to encapsulate eigenvectors.

Parameters
  • in_features (int) – dimension of input vectors

  • out_features (int) – dimension to keep as part of dimensionality reduction

Initializes internal Module state, shared by both nn.Module and ScriptModule.

add_module(name: str, module: Optional[torch.nn.modules.module.Module]) None

Adds a child module to the current module.

The module can be accessed as an attribute using the given name.

Parameters
  • name (str) – name of the child module. The child module can be accessed from this module using the given name

  • module (Module) – child module to be added to the module.

Return type

None

apply(fn: Callable[[torch.nn.modules.module.Module], None]) torch.nn.modules.module.T

Applies fn recursively to every submodule (as returned by .children()) as well as self. Typical use includes initializing the parameters of a model (see also torch.nn.init).

Parameters
  • fn (Module -> None) – function to be applied to each submodule

  • self (torch.nn.modules.module.T) –

Returns

self

Return type

Module

Example:

>>> @torch.no_grad()
>>> def init_weights(m):
>>>     print(m)
>>>     if type(m) == nn.Linear:
>>>         m.weight.fill_(1.0)
>>>         print(m.weight)
>>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2))
>>> net.apply(init_weights)
Linear(in_features=2, out_features=2, bias=True)
Parameter containing:
tensor([[1., 1.],
        [1., 1.]], requires_grad=True)
Linear(in_features=2, out_features=2, bias=True)
Parameter containing:
tensor([[1., 1.],
        [1., 1.]], requires_grad=True)
Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
)
bfloat16() torch.nn.modules.module.T

Casts all floating point parameters and buffers to bfloat16 datatype.

Note

This method modifies the module in-place.

Returns

self

Return type

Module

Parameters

self (torch.nn.modules.module.T) –

buffers(recurse: bool = True) Iterator[torch.Tensor]

Returns an iterator over module buffers.

Parameters

recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.

Yields

torch.Tensor – module buffer

Return type

Iterator[torch.Tensor]

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> for buf in model.buffers():
>>>     print(type(buf), buf.size())
<class 'torch.Tensor'> (20L,)
<class 'torch.Tensor'> (20L, 1L, 5L, 5L)
children() Iterator[torch.nn.modules.module.Module]

Returns an iterator over immediate children modules.

Yields

Module – a child module

Return type

Iterator[torch.nn.modules.module.Module]

cpu() torch.nn.modules.module.T

Moves all model parameters and buffers to the CPU.

Note

This method modifies the module in-place.

Returns

self

Return type

Module

Parameters

self (torch.nn.modules.module.T) –

cuda(device: Optional[Union[int, torch.device]] = None) torch.nn.modules.module.T

Moves all model parameters and buffers to the GPU.

This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized.

Note

This method modifies the module in-place.

Parameters
  • device (int, optional) – if specified, all parameters will be copied to that device

  • self (torch.nn.modules.module.T) –

Returns

self

Return type

Module

double() torch.nn.modules.module.T

Casts all floating point parameters and buffers to double datatype.

Note

This method modifies the module in-place.

Returns

self

Return type

Module

Parameters

self (torch.nn.modules.module.T) –

eval() torch.nn.modules.module.T

Sets the module in evaluation mode.

This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g. Dropout, BatchNorm, etc.

This is equivalent with self.train(False).

See Locally disabling gradient computation for a comparison between .eval() and several similar mechanisms that may be confused with it.

Returns

self

Return type

Module

Parameters

self (torch.nn.modules.module.T) –

extra_repr() str

Set the extra representation of the module

To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.

Return type

str

float() torch.nn.modules.module.T

Casts all floating point parameters and buffers to float datatype.

Note

This method modifies the module in-place.

Returns

self

Return type

Module

Parameters

self (torch.nn.modules.module.T) –

forward(x: torch.Tensor) torch.Tensor

Performs dimensionality reduction.

Parameters

x (torch.Tensor) – inputs to map to reduced dim space. shape of x is (B, D_IN)

Returns

reduced dim vectors

Return type

torch.Tensor

get_buffer(target: str) torch.Tensor

Returns the buffer given by target if it exists, otherwise throws an error.

See the docstring for get_submodule for a more detailed explanation of this method’s functionality as well as how to correctly specify target.

Parameters

target (str) – The fully-qualified string name of the buffer to look for. (See get_submodule for how to specify a fully-qualified string.)

Returns

The buffer referenced by target

Return type

torch.Tensor

Raises

AttributeError – If the target string references an invalid path or resolves to something that is not a buffer

get_extra_state() Any

Returns any extra state to include in the module’s state_dict. Implement this and a corresponding set_extra_state() for your module if you need to store extra state. This function is called when building the module’s state_dict().

Note that extra state should be pickleable to ensure working serialization of the state_dict. We only provide provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.

Returns

Any extra state to store in the module’s state_dict

Return type

object

get_parameter(target: str) torch.nn.parameter.Parameter

Returns the parameter given by target if it exists, otherwise throws an error.

See the docstring for get_submodule for a more detailed explanation of this method’s functionality as well as how to correctly specify target.

Parameters

target (str) – The fully-qualified string name of the Parameter to look for. (See get_submodule for how to specify a fully-qualified string.)

Returns

The Parameter referenced by target

Return type

torch.nn.Parameter

Raises

AttributeError – If the target string references an invalid path or resolves to something that is not an nn.Parameter

get_submodule(target: str) torch.nn.modules.module.Module

Returns the submodule given by target if it exists, otherwise throws an error.

For example, let’s say you have an nn.Module A that looks like this:

A(
    (net_b): Module(
        (net_c): Module(
            (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2))
        )
        (linear): Linear(in_features=100, out_features=200, bias=True)
    )
)

(The diagram shows an nn.Module A. A has a nested submodule net_b, which itself has two submodules net_c and linear. net_c then has a submodule conv.)

To check whether or not we have the linear submodule, we would call get_submodule("net_b.linear"). To check whether we have the conv submodule, we would call get_submodule("net_b.net_c.conv").

The runtime of get_submodule is bounded by the degree of module nesting in target. A query against named_modules achieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists, get_submodule should always be used.

Parameters

target (str) – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)

Returns

The submodule referenced by target

Return type

torch.nn.Module

Raises

AttributeError – If the target string references an invalid path or resolves to something that is not an nn.Module

half() torch.nn.modules.module.T

Casts all floating point parameters and buffers to half datatype.

Note

This method modifies the module in-place.

Returns

self

Return type

Module

Parameters

self (torch.nn.modules.module.T) –

ipu(device: Optional[Union[int, torch.device]] = None) torch.nn.modules.module.T

Moves all model parameters and buffers to the IPU.

This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on IPU while being optimized.

Note

This method modifies the module in-place.

Parameters
  • device (int, optional) – if specified, all parameters will be copied to that device

  • self (torch.nn.modules.module.T) –

Returns

self

Return type

Module

load_state_dict(state_dict: Mapping[str, Any], strict: bool = True)

Copies parameters and buffers from state_dict into this module and its descendants. If strict is True, then the keys of state_dict must exactly match the keys returned by this module’s state_dict() function.

Parameters
  • state_dict (dict) – a dict containing parameters and persistent buffers.

  • strict (bool, optional) – whether to strictly enforce that the keys in state_dict match the keys returned by this module’s state_dict() function. Default: True

Returns

  • missing_keys is a list of str containing the missing keys

  • unexpected_keys is a list of str containing the unexpected keys

Return type

NamedTuple with missing_keys and unexpected_keys fields

Note

If a parameter or buffer is registered as None and its corresponding key exists in state_dict, load_state_dict() will raise a RuntimeError.

modules() Iterator[torch.nn.modules.module.Module]

Returns an iterator over all modules in the network.

Yields

Module – a module in the network

Return type

Iterator[torch.nn.modules.module.Module]

Note

Duplicate modules are returned only once. In the following example, l will be returned only once.

Example:

>>> l = nn.Linear(2, 2)
>>> net = nn.Sequential(l, l)
>>> for idx, m in enumerate(net.modules()):
...     print(idx, '->', m)

0 -> Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
)
1 -> Linear(in_features=2, out_features=2, bias=True)
named_buffers(prefix: str = '', recurse: bool = True) Iterator[Tuple[str, torch.Tensor]]

Returns an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.

Parameters
  • prefix (str) – prefix to prepend to all buffer names.

  • recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.

Yields

(str, torch.Tensor) – Tuple containing the name and buffer

Return type

Iterator[Tuple[str, torch.Tensor]]

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> for name, buf in self.named_buffers():
>>>    if name in ['running_var']:
>>>        print(buf.size())
named_children() Iterator[Tuple[str, torch.nn.modules.module.Module]]

Returns an iterator over immediate children modules, yielding both the name of the module as well as the module itself.

Yields

(str, Module) – Tuple containing a name and child module

Return type

Iterator[Tuple[str, torch.nn.modules.module.Module]]

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> for name, module in model.named_children():
>>>     if name in ['conv4', 'conv5']:
>>>         print(module)
named_modules(memo: Optional[Set[torch.nn.modules.module.Module]] = None, prefix: str = '', remove_duplicate: bool = True)

Returns an iterator over all modules in the network, yielding both the name of the module as well as the module itself.

Parameters
  • memo (Optional[Set[torch.nn.modules.module.Module]]) – a memo to store the set of modules already added to the result

  • prefix (str) – a prefix that will be added to the name of the module

  • remove_duplicate (bool) – whether to remove the duplicated module instances in the result or not

Yields

(str, Module) – Tuple of name and module

Note

Duplicate modules are returned only once. In the following example, l will be returned only once.

Example:

>>> l = nn.Linear(2, 2)
>>> net = nn.Sequential(l, l)
>>> for idx, m in enumerate(net.named_modules()):
...     print(idx, '->', m)

0 -> ('', Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
))
1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
named_parameters(prefix: str = '', recurse: bool = True) Iterator[Tuple[str, torch.nn.parameter.Parameter]]

Returns an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.

Parameters
  • prefix (str) – prefix to prepend to all parameter names.

  • recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.

Yields

(str, Parameter) – Tuple containing the name and parameter

Return type

Iterator[Tuple[str, torch.nn.parameter.Parameter]]

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> for name, param in self.named_parameters():
>>>    if name in ['bias']:
>>>        print(param.size())
parameters(recurse: bool = True) Iterator[torch.nn.parameter.Parameter]

Returns an iterator over module parameters.

This is typically passed to an optimizer.

Parameters

recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.

Yields

Parameter – module parameter

Return type

Iterator[torch.nn.parameter.Parameter]

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> for param in model.parameters():
>>>     print(type(param), param.size())
<class 'torch.Tensor'> (20L,)
<class 'torch.Tensor'> (20L, 1L, 5L, 5L)
register_backward_hook(hook: Callable[[torch.nn.modules.module.Module, Union[Tuple[torch.Tensor, ...], torch.Tensor], Union[Tuple[torch.Tensor, ...], torch.Tensor]], Union[None, torch.Tensor]]) torch.utils.hooks.RemovableHandle

Registers a backward hook on the module.

This function is deprecated in favor of register_full_backward_hook() and the behavior of this function will change in future versions.

Returns

a handle that can be used to remove the added hook by calling handle.remove()

Return type

torch.utils.hooks.RemovableHandle

Parameters

hook (Callable[[torch.nn.modules.module.Module, Union[Tuple[torch.Tensor, ...], torch.Tensor], Union[Tuple[torch.Tensor, ...], torch.Tensor]], Union[None, torch.Tensor]]) –

register_buffer(name: str, tensor: Optional[torch.Tensor], persistent: bool = True) None

Adds a buffer to the module.

This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s running_mean is not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by setting persistent to False. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’s state_dict.

Buffers can be accessed as attributes using given names.

Parameters
  • name (str) – name of the buffer. The buffer can be accessed from this module using the given name

  • tensor (Tensor or None) – buffer to be registered. If None, then operations that run on buffers, such as cuda, are ignored. If None, the buffer is not included in the module’s state_dict.

  • persistent (bool) – whether the buffer is part of this module’s state_dict.

Return type

None

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> self.register_buffer('running_mean', torch.zeros(num_features))
register_forward_hook(hook: Callable[[...], None]) torch.utils.hooks.RemovableHandle

Registers a forward hook on the module.

The hook will be called every time after forward() has computed an output. It should have the following signature:

hook(module, input, output) -> None or modified output

The input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to the forward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called after forward() is called.

Returns

a handle that can be used to remove the added hook by calling handle.remove()

Return type

torch.utils.hooks.RemovableHandle

Parameters

hook (Callable[[...], None]) –

register_forward_pre_hook(hook: Callable[[...], None]) torch.utils.hooks.RemovableHandle

Registers a forward pre-hook on the module.

The hook will be called every time before forward() is invoked. It should have the following signature:

hook(module, input) -> None or modified input

The input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to the forward. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned(unless that value is already a tuple).

Returns

a handle that can be used to remove the added hook by calling handle.remove()

Return type

torch.utils.hooks.RemovableHandle

Parameters

hook (Callable[[...], None]) –

register_full_backward_hook(hook: Callable[[torch.nn.modules.module.Module, Union[Tuple[torch.Tensor, ...], torch.Tensor], Union[Tuple[torch.Tensor, ...], torch.Tensor]], Union[None, torch.Tensor]]) torch.utils.hooks.RemovableHandle

Registers a backward hook on the module.

The hook will be called every time the gradients with respect to a module are computed, i.e. the hook will execute if and only if the gradients with respect to module outputs are computed. The hook should have the following signature:

hook(module, grad_input, grad_output) -> tuple(Tensor) or None

The grad_input and grad_output are tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place of grad_input in subsequent computations. grad_input will only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries in grad_input and grad_output will be None for all non-Tensor arguments.

For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.

Warning

Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.

Returns

a handle that can be used to remove the added hook by calling handle.remove()

Return type

torch.utils.hooks.RemovableHandle

Parameters

hook (Callable[[torch.nn.modules.module.Module, Union[Tuple[torch.Tensor, ...], torch.Tensor], Union[Tuple[torch.Tensor, ...], torch.Tensor]], Union[None, torch.Tensor]]) –

register_load_state_dict_post_hook(hook)

Registers a post hook to be run after module’s load_state_dict is called.

It should have the following signature::

hook(module, incompatible_keys) -> None

The module argument is the current module that this hook is registered on, and the incompatible_keys argument is a NamedTuple consisting of attributes missing_keys and unexpected_keys. missing_keys is a list of str containing the missing keys and unexpected_keys is a list of str containing the unexpected keys.

The given incompatible_keys can be modified inplace if needed.

Note that the checks performed when calling load_state_dict() with strict=True are affected by modifications the hook makes to missing_keys or unexpected_keys, as expected. Additions to either set of keys will result in an error being thrown when strict=True, and clearning out both missing and unexpected keys will avoid an error.

Returns

a handle that can be used to remove the added hook by calling handle.remove()

Return type

torch.utils.hooks.RemovableHandle

register_module(name: str, module: Optional[torch.nn.modules.module.Module]) None

Alias for add_module().

Parameters
Return type

None

register_parameter(name: str, param: Optional[torch.nn.parameter.Parameter]) None

Adds a parameter to the module.

The parameter can be accessed as an attribute using given name.

Parameters
  • name (str) – name of the parameter. The parameter can be accessed from this module using the given name

  • param (Parameter or None) – parameter to be added to the module. If None, then operations that run on parameters, such as cuda, are ignored. If None, the parameter is not included in the module’s state_dict.

Return type

None

requires_grad_(requires_grad: bool = True) torch.nn.modules.module.T

Change if autograd should record operations on parameters in this module.

This method sets the parameters’ requires_grad attributes in-place.

This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).

See Locally disabling gradient computation for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.

Parameters
  • requires_grad (bool) – whether autograd should record operations on parameters in this module. Default: True.

  • self (torch.nn.modules.module.T) –

Returns

self

Return type

Module

set_extra_state(state: Any)

This function is called from load_state_dict() to handle any extra state found within the state_dict. Implement this function and a corresponding get_extra_state() for your module if you need to store extra state within its state_dict.

Parameters

state (dict) – Extra state from the state_dict

share_memory() torch.nn.modules.module.T

See torch.Tensor.share_memory_()

Parameters

self (torch.nn.modules.module.T) –

Return type

torch.nn.modules.module.T

state_dict(*args, destination=None, prefix='', keep_vars=False)

Returns a dictionary containing references to the whole state of the module.

Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to None are not included.

Note

The returned object is a shallow copy. It contains references to the module’s parameters and buffers.

Warning

Currently state_dict() also accepts positional arguments for destination, prefix and keep_vars in order. However, this is being deprecated and keyword arguments will be enforced in future releases.

Warning

Please avoid the use of argument destination as it is not designed for end-users.

Parameters
  • destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an OrderedDict will be created and returned. Default: None.

  • prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default: ''.

  • keep_vars (bool, optional) – by default the Tensor s returned in the state dict are detached from autograd. If it’s set to True, detaching will not be performed. Default: False.

Returns

a dictionary containing a whole state of the module

Return type

dict

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> module.state_dict().keys()
['bias', 'weight']
to(*args, **kwargs)

Moves and/or casts the parameters and buffers.

This can be called as

to(device=None, dtype=None, non_blocking=False)
to(dtype, non_blocking=False)
to(tensor, non_blocking=False)
to(memory_format=torch.channels_last)

Its signature is similar to torch.Tensor.to(), but only accepts floating point or complex dtypes. In addition, this method will only cast the floating point or complex parameters and buffers to dtype (if given). The integral parameters and buffers will be moved device, if that is given, but with dtypes unchanged. When non_blocking is set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.

See below for examples.

Note

This method modifies the module in-place.

Parameters
  • device (torch.device) – the desired device of the parameters and buffers in this module

  • dtype (torch.dtype) – the desired floating point or complex dtype of the parameters and buffers in this module

  • tensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module

  • memory_format (torch.memory_format) – the desired memory format for 4D parameters and buffers in this module (keyword only argument)

Returns

self

Return type

Module

Examples:

>>> # xdoctest: +IGNORE_WANT("non-deterministic")
>>> linear = nn.Linear(2, 2)
>>> linear.weight
Parameter containing:
tensor([[ 0.1913, -0.3420],
        [-0.5113, -0.2325]])
>>> linear.to(torch.double)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1913, -0.3420],
        [-0.5113, -0.2325]], dtype=torch.float64)
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1)
>>> gpu1 = torch.device("cuda:1")
>>> linear.to(gpu1, dtype=torch.half, non_blocking=True)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1914, -0.3420],
        [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1')
>>> cpu = torch.device("cpu")
>>> linear.to(cpu)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1914, -0.3420],
        [-0.5112, -0.2324]], dtype=torch.float16)

>>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble)
>>> linear.weight
Parameter containing:
tensor([[ 0.3741+0.j,  0.2382+0.j],
        [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128)
>>> linear(torch.ones(3, 2, dtype=torch.cdouble))
tensor([[0.6122+0.j, 0.1150+0.j],
        [0.6122+0.j, 0.1150+0.j],
        [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
to_empty(*, device: Union[str, torch.device]) torch.nn.modules.module.T

Moves the parameters and buffers to the specified device without copying storage.

Parameters
  • device (torch.device) – The desired device of the parameters and buffers in this module.

  • self (torch.nn.modules.module.T) –

Returns

self

Return type

Module

train(mode: bool = True) torch.nn.modules.module.T

Sets the module in training mode.

This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g. Dropout, BatchNorm, etc.

Parameters
  • mode (bool) – whether to set training mode (True) or evaluation mode (False). Default: True.

  • self (torch.nn.modules.module.T) –

Returns

self

Return type

Module

type(dst_type: Union[torch.dtype, str]) torch.nn.modules.module.T

Casts all parameters and buffers to dst_type.

Note

This method modifies the module in-place.

Parameters
  • dst_type (type or string) – the desired type

  • self (torch.nn.modules.module.T) –

Returns

self

Return type

Module

xpu(device: Optional[Union[int, torch.device]] = None) torch.nn.modules.module.T

Moves all model parameters and buffers to the XPU.

This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.

Note

This method modifies the module in-place.

Parameters
  • device (int, optional) – if specified, all parameters will be copied to that device

  • self (torch.nn.modules.module.T) –

Returns

self

Return type

Module

zero_grad(set_to_none: bool = False) None

Sets gradients of all model parameters to zero. See similar function under torch.optim.Optimizer for more context.

Parameters

set_to_none (bool) – instead of setting to zero, set the grads to None. See torch.optim.Optimizer.zero_grad() for details.

Return type

None

TorchSingleOrganizationAlgo

class substrafl.algorithms.pytorch.TorchSingleOrganizationAlgo(model: torch.nn.modules.module.Module, criterion: torch.nn.modules.loss._Loss, optimizer: torch.optim.optimizer.Optimizer, index_generator: substrafl.index_generator.base.BaseIndexGenerator, dataset: torch.utils.data.dataset.Dataset, scheduler: Optional[torch.optim.lr_scheduler._LRScheduler] = None, seed: Optional[int] = None, use_gpu: bool = True, *args, **kwargs)

Bases: substrafl.algorithms.pytorch.torch_base_algo.TorchAlgo

To be inherited. Wraps the necessary operation so a torch model can be trained in the Single organization strategy.

The train method:

  • initializes or loads the index generator,

  • calls the _local_train() method to do the local training

The predict method generates the predictions.

The child class can override the _local_train() and _local_predict() methods, or other methods if necessary.

To add a custom parameter to the __init__``of the class, also add it to the call to ``super().__init__` as shown in the example with my_custom_extra_parameter. Only primitive types (str, int, …) are supported for extra parameters.

Example

class MyAlgo(TorchSingleOrganizationAlgo):
    def __init__(
        self,
        my_custom_extra_parameter,
    ):
        super().__init__(
            model=perceptron,
            criterion=torch.nn.MSELoss(),
            optimizer=optimizer,
            index_generator=NpIndexGenerator(
                num_updates=100,
                batch_size=32,
            ),
            dataset=MyDataset,
            my_custom_extra_parameter=my_custom_extra_parameter,
        )
    def _local_train(
        self,
        train_dataset: torch.utils.data.Dataset,
    ):
        # Create torch dataloader
        # ``train_dataset = self._dataset(datasamples=datasamples, is_inference=False)`` is executed
        # prior the execution of this function
        train_data_loader = torch.utils.data.DataLoader(train_dataset, batch_sampler=self._index_generator)

        for x_batch, y_batch in train_data_loader:

            # Forward pass
            y_pred = self._model(x_batch)
            # Compute Loss
            loss = self._criterion(y_pred, y_batch)
            self._optimizer.zero_grad()
            # backward pass: compute the gradients
            loss.backward()
            # forward pass: update the weights.
            self._optimizer.step()

            if self._scheduler is not None:
                self._scheduler.step()

The __init__ functions is called at each call of the train() or predict() function For round>=2, some attributes will then be overwritten by their previous states in the load() function, before the train() or predict() function is ran.

Parameters
  • Args

  • model (torch.nn.modules.module.Module) – A torch model.

  • criterion (torch.nn.modules.loss._Loss) – A torch criterion (loss).

  • optimizer (torch.optim.Optimizer) – A torch optimizer linked to the model.

  • index_generator (BaseIndexGenerator) – a stateful index generator. Must inherit from BaseIndexGenerator. The __next__ method shall return a python object (batch_index) which is used for selecting each batch from the output of the the get_data method of the opener during training in this way: x[batch_index], y[batch_index]. If overridden, the generator class must be defined either as part of a package or in a different file than the one from which the execute_experiment function is called. This generator is used as stateful batch_sampler of the data loader created from the given dataset

  • dataset (torch.utils.data.Dataset) – an instantiable dataset class whose __init__ arguments are x, y and is_inference. The torch datasets used for both training and inference will be instantiate from it prior to the _local_train execution and within the predict method. The __getitem__ methods of those generated datasets must return both x (training data) and y (target values) when is_inference is set to False and only x (testing data) when is_inference is set to True. This behavior can be changed by re-writing the _local_train or predict methods.

  • scheduler (torch.optim.lr_scheduler._LRScheduler, Optional) – A torch scheduler that will be called at every batch. If None, no scheduler will be used. Defaults to None.

  • seed (Optional[int]) – Seed set at the algo initialization on each organization. Defaults to None.

  • use_gpu (bool) – Whether to use the GPUs if they are available. Defaults to True.

_local_predict(predict_dataset: torch.utils.data.dataset.Dataset, predictions_path)

Execute the following operations:

  • Create the torch dataloader using the index generator batch size.

  • Set the model to eval mode

  • Save the predictions using the _save_predictions() function.

Parameters

predict_dataset (torch.utils.data.Dataset) – predict_dataset build from the x returned by the opener.

Important

The onus is on the user to save the compute predictions. Substrafl provides the _save_predictions() to do so. The user can load those predictions from a metric file with the command: y_pred = np.load(inputs['predictions']).

Raises

BatchSizeNotFoundError – No default batch size have been found to perform local prediction. Please overwrite the predict function of your algorithm.

Parameters

predict_dataset (torch.utils.data.dataset.Dataset) –

_local_train(train_dataset: torch.utils.data.dataset.Dataset)

Local train method. Contains the local training loop.

Train the model on num_updates minibatches, using the self._index_generator generator as batch sampler for the torch dataset.

Parameters

train_dataset (torch.utils.data.Dataset) – train_dataset build from the x and y returned by the opener.

Important

You must use next(self._index_generator) as batch sampler, to ensure that the batches you are using are correct between 2 rounds of the federated learning strategy.

Example

# Create torch dataloader
train_data_loader = torch.utils.data.DataLoader(train_dataset, batch_sampler=self._index_generator)

for x_batch, y_batch in train_data_loader:

    # Forward pass
    y_pred = self._model(x_batch)

    # Compute Loss
    loss = self._criterion(y_pred, y_batch)
    self._optimizer.zero_grad()
    loss.backward()
    self._optimizer.step()

    if self._scheduler is not None:
        self._scheduler.step()
_save_predictions(predictions: torch.Tensor, predictions_path: os.PathLike)

Save the predictions under the numpy format.

Parameters
  • predictions (torch.Tensor) – predictions to save.

  • predictions_path (os.PathLike) – destination file to save predictions.

initialize(shared_states)

Empty function, useful to load the algo in the different organizations in order to perform an evaluation before any training step.

Parameters

shared_states – Unused but enforced signature due to the @remote decorator.

load_local_state(path: pathlib.Path) substrafl.algorithms.pytorch.torch_base_algo.TorchAlgo

Load the stateful arguments of this class. Child classes do not need to override that function.

Parameters

path (pathlib.Path) – The path where the class has been saved.

Returns

The class with the loaded elements.

Return type

TorchAlgo

property model: torch.nn.modules.module.Module

Model exposed when the user downloads the model

Returns

model

Return type

torch.nn.Module

predict(datasamples: Any, shared_state: Optional[Any] = None, predictions_path: os.PathLike = None) Any

Execute the following operations:

  • Create the test torch dataset.

  • Execute and return the results of the self._local_predict method

Parameters
  • datasamples (Any) – Input data

  • shared_state (Any) – Latest train task shared state (output of the train method)

  • predictions_path (os.PathLike) – Destination file to save predictions

Return type

Any

save_local_state(path: pathlib.Path) None

Saves all the stateful elements of the class to the specified path. Child classes do not need to override that function.

Parameters

path (pathlib.Path) – A path where to save the class.

Returns

None

Return type

None

property strategies: List[substrafl.strategies.schemas.StrategyName]

List of compatible strategies

Returns

typing.List[StrategyName]

Return type

List

summary()

Summary of the class to be exposed in the experiment summary file. Implement this function in the child class to add strategy-specific variables. The variables must be json-serializable.

Example

def summary(self):
    summary = super().summary()
    summary.update(
        "strategy_specific_variable": self._strategy_specific_variable,
    )
    return summary
Returns

a json-serializable dict with the attributes the user wants to store

Return type

dict

train(datasamples: Any, shared_state=None) Dict[str, numpy.ndarray]

Train method of the SingleOrganization strategy implemented with torch.

Parameters
  • x (Any) – Input data.

  • y (Any) – Input target.

  • shared_state (Dict[str, numpy.ndarray], Optional) – Kept for consistency, setting this parameter won’t have any effect. Defaults to None.

  • datasamples (Any) –

Returns

weight update which is an empty array. SingleOrganization strategy is not using shared state and this return is only for consistency.

Return type

Dict[str, numpy.ndarray]

Torch Base Class

class substrafl.algorithms.pytorch.torch_base_algo.TorchAlgo(model: torch.nn.modules.module.Module, criterion: torch.nn.modules.loss._Loss, index_generator: Optional[substrafl.index_generator.base.BaseIndexGenerator], dataset: torch.utils.data.dataset.Dataset, optimizer: Optional[torch.optim.optimizer.Optimizer] = None, scheduler: Optional[torch.optim.lr_scheduler._LRScheduler] = None, seed: Optional[int] = None, use_gpu: bool = True, *args, **kwargs)

Bases: algorithms.algo.Algo

Base TorchAlgo class, all the torch algo classes inherit from it.

To implement a new strategy:

  • add the strategy specific parameters in the __init__

  • implement the train() function: it must use the _local_train() function, which can be overridden by the user and must contain as little strategy-specific code as possible

  • Reimplement the _update_from_checkpoint() and _get_state_to_save() functions to add strategy-specific variables to the local state

The __init__ functions is called at each call of the train() or predict() function For round>2, some attributes will then be overwritten by their previous states in the load() function, before the train() or predict() function is ran.

Parameters
_get_state_to_save() dict

Create the algo checkpoint: a dictionary saved with torch.save. In this algo, it contains the state to save for every strategy. Reimplement in the child class to add strategy-specific variables.

Example

def _get_state_to_save(self) -> dict:
    local_state = super()._get_state_to_save()
    local_state.update({
        "strategy_specific_variable": self._strategy_specific_variable,
    })
    return local_state
Returns

checkpoint to save

Return type

dict

_get_torch_device(use_gpu: bool) torch.device

Get the torch device, CPU or GPU, depending on availability and user input.

Parameters

use_gpu (bool) – whether to use GPUs if available or not.

Returns

Torch device

Return type

torch.device

_local_predict(predict_dataset: torch.utils.data.dataset.Dataset, predictions_path)

Execute the following operations:

  • Create the torch dataloader using the index generator batch size.

  • Set the model to eval mode

  • Save the predictions using the _save_predictions() function.

Parameters

predict_dataset (torch.utils.data.Dataset) – predict_dataset build from the x returned by the opener.

Important

The onus is on the user to save the compute predictions. Substrafl provides the _save_predictions() to do so. The user can load those predictions from a metric file with the command: y_pred = np.load(inputs['predictions']).

Raises

BatchSizeNotFoundError – No default batch size have been found to perform local prediction. Please overwrite the predict function of your algorithm.

Parameters

predict_dataset (torch.utils.data.dataset.Dataset) –

_local_train(train_dataset: torch.utils.data.dataset.Dataset)

Local train method. Contains the local training loop.

Train the model on num_updates minibatches, using the self._index_generator generator as batch sampler for the torch dataset.

Parameters

train_dataset (torch.utils.data.Dataset) – train_dataset build from the x and y returned by the opener.

Important

You must use next(self._index_generator) as batch sampler, to ensure that the batches you are using are correct between 2 rounds of the federated learning strategy.

Example

# Create torch dataloader
train_data_loader = torch.utils.data.DataLoader(train_dataset, batch_sampler=self._index_generator)

for x_batch, y_batch in train_data_loader:

    # Forward pass
    y_pred = self._model(x_batch)

    # Compute Loss
    loss = self._criterion(y_pred, y_batch)
    self._optimizer.zero_grad()
    loss.backward()
    self._optimizer.step()

    if self._scheduler is not None:
        self._scheduler.step()
_save_predictions(predictions: torch.Tensor, predictions_path: os.PathLike)

Save the predictions under the numpy format.

Parameters
  • predictions (torch.Tensor) – predictions to save.

  • predictions_path (os.PathLike) – destination file to save predictions.

_update_from_checkpoint(path: pathlib.Path) dict

Load the checkpoint and update the internal state from it. Pop the values from the checkpoint so that we can ensure that it is empty at the end, i.e. all the values have been used.

Parameters

path (pathlib.Path) – path where the checkpoint is saved

Returns

checkpoint

Return type

dict

Example

def _update_from_checkpoint(self, path: Path) -> dict:
    checkpoint = super()._update_from_checkpoint(path=path)
    self._strategy_specific_variable = checkpoint.pop("strategy_specific_variable")
    return checkpoint
initialize(shared_states)

Empty function, useful to load the algo in the different organizations in order to perform an evaluation before any training step.

Parameters

shared_states – Unused but enforced signature due to the @remote decorator.

load_local_state(path: pathlib.Path) substrafl.algorithms.pytorch.torch_base_algo.TorchAlgo

Load the stateful arguments of this class. Child classes do not need to override that function.

Parameters

path (pathlib.Path) – The path where the class has been saved.

Returns

The class with the loaded elements.

Return type

TorchAlgo

property model: torch.nn.modules.module.Module

Model exposed when the user downloads the model

Returns

model

Return type

torch.nn.Module

predict(datasamples: Any, shared_state: Optional[Any] = None, predictions_path: os.PathLike = None) Any

Execute the following operations:

  • Create the test torch dataset.

  • Execute and return the results of the self._local_predict method

Parameters
  • datasamples (Any) – Input data

  • shared_state (Any) – Latest train task shared state (output of the train method)

  • predictions_path (os.PathLike) – Destination file to save predictions

Return type

Any

save_local_state(path: pathlib.Path) None

Saves all the stateful elements of the class to the specified path. Child classes do not need to override that function.

Parameters

path (pathlib.Path) – A path where to save the class.

Returns

None

Return type

None

abstract property strategies: List[StrategyName]

List of compatible strategies

Returns

typing.List[StrategyName]

Return type

List

summary()

Summary of the class to be exposed in the experiment summary file. Implement this function in the child class to add strategy-specific variables. The variables must be json-serializable.

Example

def summary(self):
    summary = super().summary()
    summary.update(
        "strategy_specific_variable": self._strategy_specific_variable,
    )
    return summary
Returns

a json-serializable dict with the attributes the user wants to store

Return type

dict

abstract train(datasamples: Any, shared_state: Optional[Any] = None) Any

Is executed for each TrainDataOrganizations. This functions takes the output of the get_data method from the opener, plus the shared state from the aggregator if there is one, and returns a shared state (state to send to the aggregator). Any variable that needs to be saved and updated from one round to another should be an attribute of self (e.g. self._my_local_state_variable), and be saved and loaded in the save_local_state() and load_local_state() functions.

Parameters
  • datasamples (Any) – The output of the get_data method of the opener.

  • shared_state (Any) – None for the first round of the computation graph then the returned object from the previous organization of the computation graph.

Raises

NotImplementedError

Returns

The object passed to the next organization of the computation graph.

Return type

Any

Torch functions

substrafl.algorithms.pytorch.weight_manager.add_parameters(parameters: List[torch.nn.parameter.Parameter], parameters_to_add: List[torch.nn.parameter.Parameter]) List[torch.nn.parameter.Parameter]

add the given list of torch parameters i.e. : parameters - parameters_to_add. Those elements can be extracted from a model thanks to the get_parameters() function.

Parameters
Returns

The addition of the given parameters.

Return type

List[torch.nn.parameter.Parameter]

substrafl.algorithms.pytorch.weight_manager.batch_norm_param(model: torch.nn.modules.module.Module) Generator[torch.nn.parameter.Parameter, None, None]

Generator of the internal parameters of the batch norm layers of the model. This yields references hence all modification done to the yielded object will be applied to the input model.

The internal parameters of a batch norm layer include the running mean and the running variance.

Parameters

model (torch.nn.Module) – A torch model.

Yields

float – The running mean and variance of all batch norm layers parameters from the given model.

Return type

Generator[torch.nn.parameter.Parameter, None, None]

substrafl.algorithms.pytorch.weight_manager.get_parameters(model: torch.nn.modules.module.Module, with_batch_norm_parameters: bool) List[torch.nn.parameter.Parameter]

Model parameters from the provided torch model. This function returns a copy not a reference. If with_batch_norm_parameters is set to True, the running mean and the running variance of the batch norm layers will be added after the “classic” parameters of the model.

Parameters
  • model (torch.nn.Module) – A torch model.

  • with_batch_norm_parameters (bool) – If set to True, the running mean and the running variance of each batch norm layer will be added after the “classic” parameters.

Returns

The list of torch parameters of the provided model.

Return type

List[torch.nn.parameter.Parameter]

substrafl.algorithms.pytorch.weight_manager.increment_parameters(model: torch.nn.modules.module.Module, updates: List[torch.nn.parameter.Parameter], *, with_batch_norm_parameters: bool, updates_multiplier: float = 1.0)

Add the given update to the model parameters. If with_batch_norm_parameters is set to True, the operation will include the running mean and the running variance of the batch norm layers (in this case, they must be included in the given update). This function modifies the given model internally and therefore returns nothing.

Parameters
  • model (torch.nn.Module) – The torch model to modify.

  • updates (List[torch.nn.parameter.Parameter]) – A list of torch parameters to add to the model, as ordered by the standard iterators. The trainable parameters should come first followed by the batch norm parameters if with_batch_norm_parameters is set to True. If the type is np.ndarray, it is converted in torch.Tensor.

  • with_batch_norm_parameters (bool) – If set to True, the running mean and the running variance of each batch norm layer will be included, after the trainable layers, in the model parameters to modify.

  • updates_multiplier (float, Optional) – The coefficient which multiplies the updates before being added to the model. Defaults to 1.0.

substrafl.algorithms.pytorch.weight_manager.is_batchnorm_layer(layer: torch.nn.modules.module.Module) bool

Checks if the provided layer is a Batch Norm layer (either 1D, 2D or 3D).

Parameters

layer (torch.nn.Module) – Pytorch module.

Returns

Whether the given module is a batch norm one.

Return type

bool

substrafl.algorithms.pytorch.weight_manager.model_parameters(model: torch.nn.modules.module.Module, with_batch_norm_parameters: bool) torch.nn.parameter.Parameter

A generator of the given model parameters. The returned generator yields references hence all modification done to the yielded object will be applied to the input model. If with_batch_norm_parameters is set to True, the running mean and the running variance of each batch norm layer will be added after the “classic” parameters.

Parameters
  • model (torch.nn.Module) – A torch model.

  • with_batch_norm_parameters (bool) – If set to True, the running mean and the running variance of each batch norm layer will be added after the “classic” parameters.

Returns

A python generator of torch parameters.

Return type

Generator[torch.nn.parameter.Parameter, Any, Any]

substrafl.algorithms.pytorch.weight_manager.set_parameters(model: torch.nn.modules.module.Module, parameters: List[torch.nn.parameter.Parameter], with_batch_norm_parameters: bool)

Sets the parameters of a pytorch model to the provided parameters. If with_batch_norm_parameters is set to True, the operation will include the running mean and the running variance of the batch norm layers (in this case, they must be included in the given parameters). This function modifies the given model internally and therefore returns nothing.

Parameters
  • model (torch.nn.Module) – The torch model to modify.

  • parameters (List[torch.nn.parameter.Parameter]) – Model parameters, as ordered by the standard iterators.

  • with_batch_norm_parameters (bool) – is set to True.

  • with_batch_norm_parameters – Whether to the batch norm layers’ internal parameters are provided and need to be included in the operation.

substrafl.algorithms.pytorch.weight_manager.subtract_parameters(parameters: List[torch.nn.parameter.Parameter], parameters_to_subtract: List[torch.nn.parameter.Parameter]) List[torch.nn.parameter.Parameter]

subtract the given list of torch parameters i.e. : parameters - parameters_to_subtract. Those elements can be extracted from a model thanks to the get_parameters() function.

Parameters
Returns

The subtraction of the given parameters.

Return type

List[torch.nn.parameter.Parameter]

substrafl.algorithms.pytorch.weight_manager.weighted_sum_parameters(parameters_list: List[List[torch.Tensor]], coefficient_list: List[float]) List[torch.Tensor]

Do a weighted sum of the given lists of torch parameters. Those elements can be extracted from a model thanks to the get_parameters() function.

Parameters
  • parameters_list (List[List[torch.Tensor]]) – A list of List of torch parameters.

  • coefficient_list (List[float]) – A list of coefficients which will be applied to each list of parameters.

Returns

The weighted sum of the given list of torch parameters.

Return type

List[torch.nn.parameter.Parameter]

substrafl.algorithms.pytorch.weight_manager.zeros_like_parameters(model: torch.nn.modules.module.Module, with_batch_norm_parameters: bool, device: torch.device) List[torch.Tensor]

Copy the model parameters from the provided torch model and sets values to zero. If with_batch_norm_parameters is set to True, the running mean and the running variance of the batch norm layers will be added after the “classic” parameters of the model.

Parameters
  • model (torch.nn.Module) – A torch model.

  • with_batch_norm_parameters (bool) – If set to True, the running mean and the running variance of each batch norm layer will be added after the “classic” parameters.

  • device (torch.device) – torch device on which to save the parameters

Returns

The list of torch parameters of the provided model with values set to zero.

Return type

List[torch.nn.parameter.Parameter]

Base Class

class substrafl.algorithms.algo.Algo(*args, **kwargs)

Bases: abc.ABC

The base class to be inherited for substrafl algorithms.

initialize(shared_states)

Empty function, useful to load the algo in the different organizations in order to perform an evaluation before any training step.

Parameters

shared_states – Unused but enforced signature due to the @remote decorator.

abstract load_local_state(path: pathlib.Path) Any

Executed at the beginning of each step of the computation graph so for each organization, at each step of the computation graph the previous local state can be retrieved.

Parameters

path (pathlib.Path) – The path where the previous local state has been saved.

Raises

NotImplementedError

Returns

The loaded element.

Return type

Any

abstract property model: Any

Model exposed when the user downloads the model

Returns

model

Return type

Any

abstract predict(datasamples: Any, shared_state: Optional[Any] = None, predictions_path: Optional[pathlib.Path] = None) Any

Is executed for each TestDataOrganizations. The predictions will be saved on the predictions_path. The predictions are then loaded and used to calculate the metric.

Parameters
  • datasamples (Any) – The output of the get_data method of the opener.

  • shared_state (Any) – None for the first round of the computation graph then the returned object from the previous organization of the computation graph.

  • predictions_path (pathlib.Path) – Destination file to save predictions.

Raises

NotImplementedError

Return type

Any

abstract save_local_state(path: pathlib.Path) None

Executed at the end of each step of the computation graph so for each organization, the local state can be saved.

Parameters

path (pathlib.Path) – The path where the previous local state has been saved.

Raises

NotImplementedError

Returns

None

Return type

None

abstract property strategies: List[StrategyName]

List of compatible strategies

Returns

typing.List[StrategyName]

Return type

List

summary() dict

Summary of the class to be exposed in the experiment summary file. For child classes, override this function and add super.summary()

Example

def summary(self):

    summary = super().summary()
    summary.update(
        {
            "attribute": self.attribute,
            ...
        }
    )
    return summary
Returns

a json-serializable dict with the attributes the user wants to store

Return type

dict

abstract train(datasamples, shared_state: Any) Any

Is executed for each TrainDataOrganizations. This functions takes the output of the get_data method from the opener, plus the shared state from the aggregator if there is one, and returns a shared state (state to send to the aggregator). Any variable that needs to be saved and updated from one round to another should be an attribute of self (e.g. self._my_local_state_variable), and be saved and loaded in the save_local_state() and load_local_state() functions.

Parameters
  • datasamples (Any) – The output of the get_data method of the opener.

  • shared_state (Any) – None for the first round of the computation graph then the returned object from the previous organization of the computation graph.

Raises

NotImplementedError

Returns

The object passed to the next organization of the computation graph.

Return type

Any