API Reference

PyTorch Spherinator Models

class spherinator.models.Autoencoder(encoder, decoder, reconstruction_loss=MSELoss())

Bases: LightningModule

Parameters:
  • encoder (Module)

  • decoder (Module)

  • reconstruction_loss (Module)

configure_optimizers()

Default Adam optimizer if missing from the configuration file.

decode(x)
encode(x)
forward(x)

Same as torch.nn.Module.forward().

Parameters:
  • *args – Whatever you decide to pass into the forward method.

  • **kwargs – Keyword arguments are also possible.

Returns:

Your model’s output

reconstruct(x)
test_step(batch, batch_idx)

Operates on a single batch of data from the test set. In this step you’d normally generate examples or calculate anything of interest such as accuracy.

Parameters:
  • batch – The output of your data iterable, normally a DataLoader.

  • batch_idx – The index of this batch.

  • dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)

Return type:

Tensor

Returns:

  • Tensor - The loss tensor

  • dict - A dictionary. Can include any keys, but must include the key 'loss'.

  • None - Skip to the next batch.

# if you have one test dataloader:
def test_step(self, batch, batch_idx): ...


# if you have multiple test dataloaders:
def test_step(self, batch, batch_idx, dataloader_idx=0): ...

Examples:

# CASE 1: A single test dataset
def test_step(self, batch, batch_idx):
    x, y = batch

    # implement your own
    out = self(x)
    loss = self.loss(out, y)

    # log 6 example images
    # or generated text... or whatever
    sample_imgs = x[:6]
    grid = torchvision.utils.make_grid(sample_imgs)
    self.logger.experiment.add_image('example_images', grid, 0)

    # calculate acc
    labels_hat = torch.argmax(out, dim=1)
    test_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0)

    # log the outputs!
    self.log_dict({'test_loss': loss, 'test_acc': test_acc})

If you pass in multiple test dataloaders, test_step() will have an additional argument. We recommend setting the default value of 0 so that you can quickly switch between single and multiple dataloaders.

# CASE 2: multiple test dataloaders
def test_step(self, batch, batch_idx, dataloader_idx=0):
    # dataloader_idx tells you which dataset this is.
    x, y = batch

    # implement your own
    out = self(x)

    if dataloader_idx == 0:
        loss = self.loss0(out, y)
    else:
        loss = self.loss1(out, y)

    # calculate acc
    labels_hat = torch.argmax(out, dim=1)
    acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0)

    # log the outputs separately for each dataloader
    self.log_dict({f"test_loss_{dataloader_idx}": loss, f"test_acc_{dataloader_idx}": acc})

Note

If you don’t need to test you don’t need to implement this method.

Note

When the test_step() is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of the test epoch, the model goes back to training mode and gradients are enabled.

training_step(batch, batch_idx)

Here you compute and return the training loss and some additional metrics for e.g. the progress bar or logger.

Parameters:
  • batch – The output of your data iterable, normally a DataLoader.

  • batch_idx – The index of this batch.

  • dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)

Return type:

Tensor

Returns:

  • Tensor - The loss tensor

  • dict - A dictionary which can include any keys, but must include the key 'loss' in the case of automatic optimization.

  • None - In automatic optimization, this will skip to the next batch (but is not supported for multi-GPU, TPU, or DeepSpeed). For manual optimization, this has no special meaning, as returning the loss is not required.

In this step you’d normally do the forward pass and calculate the loss for a batch. You can also do fancier things like multiple forward passes or something model specific.

Example:

def training_step(self, batch, batch_idx):
    x, y, z = batch
    out = self.encoder(x)
    loss = self.loss(out, x)
    return loss

To use multiple optimizers, you can switch to ‘manual optimization’ and control their stepping:

def __init__(self):
    super().__init__()
    self.automatic_optimization = False


# Multiple optimizers (e.g.: GANs)
def training_step(self, batch, batch_idx):
    opt1, opt2 = self.optimizers()

    # do training_step with encoder
    ...
    opt1.step()
    # do training_step with decoder
    ...
    opt2.step()

Note

When accumulate_grad_batches > 1, the loss returned here will be automatically normalized by accumulate_grad_batches internally.

validation_step(batch, batch_idx)

Operates on a single batch of data from the validation set. In this step you’d might generate examples or calculate anything of interest like accuracy.

Parameters:
  • batch – The output of your data iterable, normally a DataLoader.

  • batch_idx – The index of this batch.

  • dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)

Return type:

Tensor

Returns:

  • Tensor - The loss tensor

  • dict - A dictionary. Can include any keys, but must include the key 'loss'.

  • None - Skip to the next batch.

# if you have one val dataloader:
def validation_step(self, batch, batch_idx): ...


# if you have multiple val dataloaders:
def validation_step(self, batch, batch_idx, dataloader_idx=0): ...

Examples:

# CASE 1: A single validation dataset
def validation_step(self, batch, batch_idx):
    x, y = batch

    # implement your own
    out = self(x)
    loss = self.loss(out, y)

    # log 6 example images
    # or generated text... or whatever
    sample_imgs = x[:6]
    grid = torchvision.utils.make_grid(sample_imgs)
    self.logger.experiment.add_image('example_images', grid, 0)

    # calculate acc
    labels_hat = torch.argmax(out, dim=1)
    val_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0)

    # log the outputs!
    self.log_dict({'val_loss': loss, 'val_acc': val_acc})

If you pass in multiple val dataloaders, validation_step() will have an additional argument. We recommend setting the default value of 0 so that you can quickly switch between single and multiple dataloaders.

# CASE 2: multiple validation dataloaders
def validation_step(self, batch, batch_idx, dataloader_idx=0):
    # dataloader_idx tells you which dataset this is.
    x, y = batch

    # implement your own
    out = self(x)

    if dataloader_idx == 0:
        loss = self.loss0(out, y)
    else:
        loss = self.loss1(out, y)

    # calculate acc
    labels_hat = torch.argmax(out, dim=1)
    acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0)

    # log the outputs separately for each dataloader
    self.log_dict({f"val_loss_{dataloader_idx}": loss, f"val_acc_{dataloader_idx}": acc})

Note

If you don’t need to validate you don’t need to implement this method.

Note

When the validation_step() is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of validation, the model goes back to training mode and gradients are enabled.

class spherinator.models.ConsecutiveConv1DLayer(kernel_size=3, stride=1, padding=0, out_channels=[1], activation=<class 'torch.nn.modules.activation.ReLU'>, norm=<class 'torch.nn.modules.batchnorm.BatchNorm1d'>, pooling=None)

Bases: object

Parameters:
  • kernel_size (int)

  • stride (int)

  • padding (int)

  • out_channels (list[int])

  • activation (Callable[[...], Module] | None)

  • norm (Callable[[...], Module] | None)

  • pooling (Module | None)

get_model()
Return type:

Module

class spherinator.models.ConsecutiveConv2DLayer(kernel_size=3, stride=1, padding=0, out_channels=[1], activation=<class 'torch.nn.modules.activation.ReLU'>, norm=<class 'torch.nn.modules.batchnorm.BatchNorm2d'>, pooling=None)

Bases: object

Parameters:
  • kernel_size (int)

  • stride (int)

  • padding (int)

  • out_channels (list[int])

  • activation (Callable[[...], Module] | None)

  • norm (Callable[[...], Module] | None)

  • pooling (Module | None)

get_model()
Return type:

Module

class spherinator.models.ConsecutiveConvTranspose1DLayer(kernel_size=3, stride=1, padding=0, output_padding=0, dilation=1, bias=True, out_channels=[1], activation=<class 'torch.nn.modules.activation.ReLU'>, norm=<class 'torch.nn.modules.batchnorm.BatchNorm1d'>, pooling=None)

Bases: object

Parameters:
  • kernel_size (int)

  • stride (int)

  • padding (int)

  • output_padding (int)

  • dilation (int)

  • bias (bool)

  • out_channels (list[int])

  • activation (Callable[[...], Module] | None)

  • norm (Callable[[...], Module] | None)

  • pooling (Callable[[...], Module] | None)

get_model()
Return type:

Module

class spherinator.models.ConsecutiveConvTranspose2DLayer(kernel_size=3, stride=1, padding=0, output_padding=0, dilation=1, bias=True, out_channels=[1], activation=<class 'torch.nn.modules.activation.ReLU'>, norm=<class 'torch.nn.modules.batchnorm.BatchNorm2d'>, pooling=None)

Bases: object

Parameters:
  • kernel_size (int)

  • stride (int)

  • padding (int)

  • output_padding (int)

  • dilation (int)

  • bias (bool)

  • out_channels (list[int])

  • activation (Callable[[...], Module] | None)

  • norm (Callable[[...], Module] | None)

  • pooling (Callable[[...], Module] | None)

get_model()
Return type:

Module

class spherinator.models.ConvolutionalDecoder1D(input_dim, output_dim, cnn_input_dim, cnn_layers=[], weights=None, freeze=False)

Bases: Module

Parameters:
forward(x)

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

Return type:

Tensor

Parameters:

x (Tensor)

class spherinator.models.ConvolutionalDecoder2D(input_dim, output_dim, cnn_input_dim, cnn_layers=[], weights=None, freeze=False)

Bases: Module

Parameters:
forward(x)

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

Return type:

Tensor

Parameters:

x (Tensor)

class spherinator.models.ConvolutionalEncoder1D(input_dim, output_dim, cnn_layers=[], weights=None, freeze=False)

Bases: Module

Parameters:
forward(x)

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

Return type:

Tensor

Parameters:

x (Tensor)

class spherinator.models.ConvolutionalEncoder2D(input_dim, output_dim, cnn_layers=[], weights=None, freeze=False)

Bases: Module

Parameters:
forward(x)

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

Return type:

Tensor

Parameters:

x (Tensor)

class spherinator.models.EmbeddingReconstruction(embedding, decoder)

Bases: LightningModule

Parameters:
  • embedding (Module)

  • decoder (Module)

configure_optimizers()

Default Adam optimizer if missing from the configuration file.

forward(x)

Same as torch.nn.Module.forward().

Parameters:
  • *args – Whatever you decide to pass into the forward method.

  • **kwargs – Keyword arguments are also possible.

Returns:

Your model’s output

training_step(batch, _)

Here you compute and return the training loss and some additional metrics for e.g. the progress bar or logger.

Parameters:
  • batch – The output of your data iterable, normally a DataLoader.

  • batch_idx – The index of this batch.

  • dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)

Returns:

  • Tensor - The loss tensor

  • dict - A dictionary which can include any keys, but must include the key 'loss' in the case of automatic optimization.

  • None - In automatic optimization, this will skip to the next batch (but is not supported for multi-GPU, TPU, or DeepSpeed). For manual optimization, this has no special meaning, as returning the loss is not required.

In this step you’d normally do the forward pass and calculate the loss for a batch. You can also do fancier things like multiple forward passes or something model specific.

Example:

def training_step(self, batch, batch_idx):
    x, y, z = batch
    out = self.encoder(x)
    loss = self.loss(out, x)
    return loss

To use multiple optimizers, you can switch to ‘manual optimization’ and control their stepping:

def __init__(self):
    super().__init__()
    self.automatic_optimization = False


# Multiple optimizers (e.g.: GANs)
def training_step(self, batch, batch_idx):
    opt1, opt2 = self.optimizers()

    # do training_step with encoder
    ...
    opt1.step()
    # do training_step with decoder
    ...
    opt2.step()

Note

When accumulate_grad_batches > 1, the loss returned here will be automatically normalized by accumulate_grad_batches internally.

class spherinator.models.HuggingFaceResNetEncoder(model_name='microsoft/resnet-18', output_dim=None, freeze=False, weights=None)

Bases: Module

HuggingFaceResNetEncoder is a PyTorch module that wraps a Hugging Face ResNetModel to be used as an encoder in the Spherinator framework. It takes an image input and produces a fixed-size embedding vector. The pooled output from the ResNet model is used as the output representation, and an optional linear projection can be applied on top of it to match a desired output dimension.

Parameters:
  • model_name (str) – HuggingFace model name. Defaults to “microsoft/resnet-18”.

  • output_dim (Optional[int]) – If set, adds a linear projection on top of the pooled output. Defaults to None (uses the model’s hidden size directly).

  • freeze (bool) – Whether to freeze the ResNet backbone weights. Defaults to False.

  • weights (Optional[WeightsProvider]) – Weights to load. Defaults to None.

forward(x)

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

Return type:

Tensor

Parameters:

x (Tensor)

class spherinator.models.HuggingFaceViTEncoder(model_name='google/vit-base-patch16-224', output_dim=None, freeze=False, weights=None)

Bases: Module

HuggingFaceViTEncoder is a PyTorch module that wraps a Hugging Face ViTModel to be used as an encoder in the Spherinator framework. It takes an image input and produces a fixed-size embedding vector. The CLS token from the ViT model is used as the output representation, and an optional linear projection can be applied on top of it to match a desired output dimension.

Parameters:
  • model_name (str) – HuggingFace model name. Defaults to “google/vit-base-patch16-224”.

  • output_dim (Optional[int]) – If set, adds a linear projection on top of the CLS token. Defaults to None (uses the model’s hidden size directly).

  • freeze (bool) – Whether to freeze the ViT backbone weights. Defaults to False.

  • weights (Optional[WeightsProvider]) – Weights to load. Defaults to None.

forward(x)

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

Return type:

Tensor

Parameters:

x (Tensor)

class spherinator.models.MLP(input_size, hidden_sizes, output_size, activation=<class 'torch.nn.modules.activation.ReLU'>)

Bases: Module

A simple multi-layer perceptron (MLP) model.

Parameters:
  • input_size (int) – The size of the input features.

  • hidden_sizes (list[int]) – A list of hidden layer sizes.

  • output_size (int) – The size of the output features.

  • activation (Optional[Callable[..., Module]]) – The activation function to use. Defaults to nn.ReLU.

forward(x)

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

Return type:

Tensor

Parameters:

x (Tensor)

class spherinator.models.Sequential(modules)

Bases: Sequential

A drop-in for torch.nn.Sequential that accepts a modules keyword argument instead of *args, making it compatible with jsonargparse / LightningCLI YAML configs.

Example YAML usage:

class_path: spherinator.models.Sequential
init_args:
  modules:
    - class_path: spherinator.models.HuggingFaceResNetEncoder
      init_args: ...
    - class_path: torch.nn.Linear
      init_args: ...
Parameters:

modules (List[Module])

class spherinator.models.UpsamplingDecoder2D(input_dim, output_dim, base_channels=512, seed_size=7, weights=None, freeze=False)

Bases: Module

Image decoder using bilinear upsampling + convolutions.

Avoids the checkerboard artifacts of transposed convolutions. Designed to decode a low-dimensional latent vector back to a full-resolution image matching the ViT input (224×224 by default).

Architecture:
z → Linear → reshape (base_channels, seed_size, seed_size)

→ 5× UpsampleBlock (each 2×) → final 1×1 conv → output

Spatial path: seed_size × 2^n_upsample = output_size

Parameters:
  • input_dim (int) – Latent vector size.

  • output_dim (list[int]) – Output shape [C, H, W].

  • base_channels (int) – Channels at the spatial seed. Defaults to 512.

  • seed_size (int) – Spatial size of the seed feature map. Defaults to 7.

  • weights (Optional[WeightsProvider]) – Optional pre-trained weights.

  • freeze (bool) – Freeze all parameters. Defaults to False.

forward(x)

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

Return type:

Tensor

Parameters:

x (Tensor)

class spherinator.models.VariationalAutoencoder(encoder, decoder, encoder_out_dim, z_dim=3, beta=1.0, reconstruction_loss=MSELoss(), max_scale=None)

Bases: LightningModule

Variational Autoencoder with a hyperspherical latent space.

Parameters:
  • encoder (Module)

  • decoder (Module)

  • encoder_out_dim (int)

  • z_dim (int)

  • beta (float)

  • reconstruction_loss (Module)

  • max_scale (float | None)

configure_optimizers()

Default Adam optimizer if missing from the configuration file.

decode(z)

Decode from the latent space.

encode(x)

Return sphere embedding (z_location, z_scale).

forward(x)

Same as torch.nn.Module.forward().

Parameters:
  • *args – Whatever you decide to pass into the forward method.

  • **kwargs – Keyword arguments are also possible.

Returns:

Your model’s output

is_variational = True
reconstruct(x)
reparameterize(z_location, z_scale)
test_step(batch, batch_idx)

Operates on a single batch of data from the test set. In this step you’d normally generate examples or calculate anything of interest such as accuracy.

Parameters:
  • batch – The output of your data iterable, normally a DataLoader.

  • batch_idx – The index of this batch.

  • dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)

Return type:

Tensor

Returns:

  • Tensor - The loss tensor

  • dict - A dictionary. Can include any keys, but must include the key 'loss'.

  • None - Skip to the next batch.

# if you have one test dataloader:
def test_step(self, batch, batch_idx): ...


# if you have multiple test dataloaders:
def test_step(self, batch, batch_idx, dataloader_idx=0): ...

Examples:

# CASE 1: A single test dataset
def test_step(self, batch, batch_idx):
    x, y = batch

    # implement your own
    out = self(x)
    loss = self.loss(out, y)

    # log 6 example images
    # or generated text... or whatever
    sample_imgs = x[:6]
    grid = torchvision.utils.make_grid(sample_imgs)
    self.logger.experiment.add_image('example_images', grid, 0)

    # calculate acc
    labels_hat = torch.argmax(out, dim=1)
    test_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0)

    # log the outputs!
    self.log_dict({'test_loss': loss, 'test_acc': test_acc})

If you pass in multiple test dataloaders, test_step() will have an additional argument. We recommend setting the default value of 0 so that you can quickly switch between single and multiple dataloaders.

# CASE 2: multiple test dataloaders
def test_step(self, batch, batch_idx, dataloader_idx=0):
    # dataloader_idx tells you which dataset this is.
    x, y = batch

    # implement your own
    out = self(x)

    if dataloader_idx == 0:
        loss = self.loss0(out, y)
    else:
        loss = self.loss1(out, y)

    # calculate acc
    labels_hat = torch.argmax(out, dim=1)
    acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0)

    # log the outputs separately for each dataloader
    self.log_dict({f"test_loss_{dataloader_idx}": loss, f"test_acc_{dataloader_idx}": acc})

Note

If you don’t need to test you don’t need to implement this method.

Note

When the test_step() is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of the test epoch, the model goes back to training mode and gradients are enabled.

training_step(batch, batch_idx)

Here you compute and return the training loss and some additional metrics for e.g. the progress bar or logger.

Parameters:
  • batch – The output of your data iterable, normally a DataLoader.

  • batch_idx – The index of this batch.

  • dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)

Return type:

Tensor

Returns:

  • Tensor - The loss tensor

  • dict - A dictionary which can include any keys, but must include the key 'loss' in the case of automatic optimization.

  • None - In automatic optimization, this will skip to the next batch (but is not supported for multi-GPU, TPU, or DeepSpeed). For manual optimization, this has no special meaning, as returning the loss is not required.

In this step you’d normally do the forward pass and calculate the loss for a batch. You can also do fancier things like multiple forward passes or something model specific.

Example:

def training_step(self, batch, batch_idx):
    x, y, z = batch
    out = self.encoder(x)
    loss = self.loss(out, x)
    return loss

To use multiple optimizers, you can switch to ‘manual optimization’ and control their stepping:

def __init__(self):
    super().__init__()
    self.automatic_optimization = False


# Multiple optimizers (e.g.: GANs)
def training_step(self, batch, batch_idx):
    opt1, opt2 = self.optimizers()

    # do training_step with encoder
    ...
    opt1.step()
    # do training_step with decoder
    ...
    opt2.step()

Note

When accumulate_grad_batches > 1, the loss returned here will be automatically normalized by accumulate_grad_batches internally.

validation_step(batch, batch_idx)

Operates on a single batch of data from the validation set. In this step you’d might generate examples or calculate anything of interest like accuracy.

Parameters:
  • batch – The output of your data iterable, normally a DataLoader.

  • batch_idx – The index of this batch.

  • dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)

Return type:

Tensor

Returns:

  • Tensor - The loss tensor

  • dict - A dictionary. Can include any keys, but must include the key 'loss'.

  • None - Skip to the next batch.

# if you have one val dataloader:
def validation_step(self, batch, batch_idx): ...


# if you have multiple val dataloaders:
def validation_step(self, batch, batch_idx, dataloader_idx=0): ...

Examples:

# CASE 1: A single validation dataset
def validation_step(self, batch, batch_idx):
    x, y = batch

    # implement your own
    out = self(x)
    loss = self.loss(out, y)

    # log 6 example images
    # or generated text... or whatever
    sample_imgs = x[:6]
    grid = torchvision.utils.make_grid(sample_imgs)
    self.logger.experiment.add_image('example_images', grid, 0)

    # calculate acc
    labels_hat = torch.argmax(out, dim=1)
    val_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0)

    # log the outputs!
    self.log_dict({'val_loss': loss, 'val_acc': val_acc})

If you pass in multiple val dataloaders, validation_step() will have an additional argument. We recommend setting the default value of 0 so that you can quickly switch between single and multiple dataloaders.

# CASE 2: multiple validation dataloaders
def validation_step(self, batch, batch_idx, dataloader_idx=0):
    # dataloader_idx tells you which dataset this is.
    x, y = batch

    # implement your own
    out = self(x)

    if dataloader_idx == 0:
        loss = self.loss0(out, y)
    else:
        loss = self.loss1(out, y)

    # calculate acc
    labels_hat = torch.argmax(out, dim=1)
    acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0)

    # log the outputs separately for each dataloader
    self.log_dict({f"val_loss_{dataloader_idx}": loss, f"val_acc_{dataloader_idx}": acc})

Note

If you don’t need to validate you don’t need to implement this method.

Note

When the validation_step() is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of validation, the model goes back to training mode and gradients are enabled.

class spherinator.models.WeightsProvider(weight_path, prefix=None)

Bases: object

Class to load and provide weights for the model.

Parameters:
  • weight_path (str) – The path to the weights file

  • prefix (Optional[str]) – The prefix to use when loading the weights. Defaults to None.

get_state_dict()

Get the state dict of the model.

Return type:

Mapping[str, Any]

spherinator.models.export_onnx(ckpt_file, model_file, export_path, input_shape, latent_shape, opset_version=19)

Exports the encoder, decoder, and reconstruction graph of a Spherinator model to ONNX format.

Parameters:
  • ckpt_file (str) – Path to the checkpoint file.

  • model_file (str) – Path to the model YAML file.

  • export_path (str) – Directory to save the ONNX files.

  • input_shape (tuple) – Shape of the input tensor.

  • latent_shape (tuple) – Shape of the latent tensor.

  • opset_version (int) – ONNX opset version. Defaults to 19.

spherinator.models.yaml2model(yaml_path)

Initialize a PyTorch model from a YAML file

Return type:

Module

Parameters:

yaml_path (str)