glasspy.predict package

Submodules

glasspy.predict.base module

Module with base classes for building predictive models.

class glasspy.predict.base.AE(hparams: Dict[str, Any])

Bases: LightningModule, Predict

Base class for creating Autoencoders.

Parameters:

hparams

Dictionary with the hyperparemeters of the network. The possible parameters are: + “n_features”: number of input features (required). Must be a positive

integer. Will be the same as the number of output features.

  • ”num_layers”: number of encoder hidden layers (defaults to 1). Must be a positive integer. NOTE: The decoder will have the same number of hidden layers.

  • ”layer_n_size”: number of neurons in layer n of the encoder (replace n for an integer starting at 1, defaults to 10). Must be a positive integer. NOTE: The decoder architecture will be the same as the encoder, but mirrored.

  • ”layer_n_activation”: activation function of layer n of the encoder (replace n for an integer starting at 1, defaults to Tanh). Available values are [“Tanh”, “Sigmoid”, “ReLU”, “LeakyReLU”, “SELU”, “GELU”, “ELU”, “PReLU”, “SiLU”, “Mish”, “Softplus”, “Linear”].

  • ”layer_n_dropout”: dropout of layer n of the encoder (replace n for an integer starting at 1, defaults to False meaning no dropout). Any value between 0 and 1 (or False) is permitted.

  • ”layer_n_batchnorm”: True will use batch normalization in layer n of the encoder, False will not use batch normalization in layer n (replace n for an integer starting at 1, defaults to False meaning no batch normalization).

  • ”loss”: loss function to use for the backpropagation algorithm (defaults to mse). Use mse for mean squared error loss (L2) or huber for a smooth L1 loss.

  • ”optimizer”: optimizer algorithm to use (defaults SGD). Use SGD for stochastic gradient descend, Adam for Adam, or AdamW for weighted Adam.

  • ”lr”: optimizer learning rate (defaults to 1e-4 if optimizer is SGD or 1e-3 if optimizer is Adam or AdamW).

  • ”momentum”: momentum to use when optmizer is SGD (defaults to 0).

  • ”optimizer_Adam_eps”: eps to use for Adam or AdamW optimizers (defaults to 1e-8).

Raises:

NotImplementedError – When the selected hyperparameters is not one of the permited values.

configure_optimizers()

Choose what optimizers and learning-rate schedulers to use in your optimization. Normally you’d need one. But in the case of GANs or similar you might have multiple.

Returns:

Any of these 6 options.

  • Single optimizer.

  • List or Tuple of optimizers.

  • Two lists - The first list has multiple optimizers, and the second has multiple LR schedulers (or multiple lr_scheduler_config).

  • Dictionary, with an "optimizer" key, and (optionally) a "lr_scheduler" key whose value is a single LR scheduler or lr_scheduler_config.

  • Tuple of dictionaries as described above, with an optional "frequency" key.

  • None - Fit will run without any optimizer.

The lr_scheduler_config is a dictionary which contains the scheduler and its associated configuration. The default configuration is shown below.

lr_scheduler_config = {
    # REQUIRED: The scheduler instance
    "scheduler": lr_scheduler,
    # The unit of the scheduler's step size, could also be 'step'.
    # 'epoch' updates the scheduler on epoch end whereas 'step'
    # updates it after a optimizer update.
    "interval": "epoch",
    # How many epochs/steps should pass between calls to
    # `scheduler.step()`. 1 corresponds to updating the learning
    # rate after every epoch/step.
    "frequency": 1,
    # Metric to to monitor for schedulers like `ReduceLROnPlateau`
    "monitor": "val_loss",
    # If set to `True`, will enforce that the value specified 'monitor'
    # is available when the scheduler is updated, thus stopping
    # training if not found. If set to `False`, it will only produce a warning
    "strict": True,
    # If using the `LearningRateMonitor` callback to monitor the
    # learning rate progress, this keyword can be used to specify
    # a custom logged name
    "name": None,
}

When there are schedulers in which the .step() method is conditioned on a value, such as the torch.optim.lr_scheduler.ReduceLROnPlateau scheduler, Lightning requires that the lr_scheduler_config contains the keyword "monitor" set to the metric name that the scheduler should be conditioned on.

Metrics can be made available to monitor by simply logging it using self.log('metric_to_track', metric_val) in your LightningModule.

Note

The frequency value specified in a dict along with the optimizer key is an int corresponding to the number of sequential batches optimized with the specific optimizer. It should be given to none or to all of the optimizers. There is a difference between passing multiple optimizers in a list, and passing multiple optimizers in dictionaries with a frequency of 1:

  • In the former case, all optimizers will operate on the given batch in each optimization step.

  • In the latter, only one optimizer will operate on the given batch at every step.

This is different from the frequency value specified in the lr_scheduler_config mentioned above.

def configure_optimizers(self):
    optimizer_one = torch.optim.SGD(self.model.parameters(), lr=0.01)
    optimizer_two = torch.optim.SGD(self.model.parameters(), lr=0.01)
    return [
        {"optimizer": optimizer_one, "frequency": 5},
        {"optimizer": optimizer_two, "frequency": 10},
    ]

In this example, the first optimizer will be used for the first 5 steps, the second optimizer for the next 10 steps and that cycle will continue. If an LR scheduler is specified for an optimizer using the lr_scheduler key in the above dict, the scheduler will only be updated when its optimizer is being used.

Examples:

# most cases. no learning rate scheduler
def configure_optimizers(self):
    return Adam(self.parameters(), lr=1e-3)

# multiple optimizer case (e.g.: GAN)
def configure_optimizers(self):
    gen_opt = Adam(self.model_gen.parameters(), lr=0.01)
    dis_opt = Adam(self.model_dis.parameters(), lr=0.02)
    return gen_opt, dis_opt

# example with learning rate schedulers
def configure_optimizers(self):
    gen_opt = Adam(self.model_gen.parameters(), lr=0.01)
    dis_opt = Adam(self.model_dis.parameters(), lr=0.02)
    dis_sch = CosineAnnealing(dis_opt, T_max=10)
    return [gen_opt, dis_opt], [dis_sch]

# example with step-based learning rate schedulers
# each optimizer has its own scheduler
def configure_optimizers(self):
    gen_opt = Adam(self.model_gen.parameters(), lr=0.01)
    dis_opt = Adam(self.model_dis.parameters(), lr=0.02)
    gen_sch = {
        'scheduler': ExponentialLR(gen_opt, 0.99),
        'interval': 'step'  # called after each training step
    }
    dis_sch = CosineAnnealing(dis_opt, T_max=10) # called every epoch
    return [gen_opt, dis_opt], [gen_sch, dis_sch]

# example with optimizer frequencies
# see training procedure in `Improved Training of Wasserstein GANs`, Algorithm 1
# https://arxiv.org/abs/1704.00028
def configure_optimizers(self):
    gen_opt = Adam(self.model_gen.parameters(), lr=0.01)
    dis_opt = Adam(self.model_dis.parameters(), lr=0.02)
    n_critic = 5
    return (
        {'optimizer': dis_opt, 'frequency': n_critic},
        {'optimizer': gen_opt, 'frequency': 1}
    )

Note

Some things to know:

  • Lightning calls .backward() and .step() on each optimizer as needed.

  • If learning rate scheduler is specified in configure_optimizers() with key "interval" (default “epoch”) in the scheduler configuration, Lightning will call the scheduler’s .step() method automatically in case of automatic optimization.

  • If you use 16-bit precision (precision=16), Lightning will automatically handle the optimizers.

  • If you use multiple optimizers, training_step() will have an additional optimizer_idx parameter.

  • If you use torch.optim.LBFGS, Lightning handles the closure function automatically for you.

  • If you use multiple optimizers, gradients will be calculated only for the parameters of current optimizer at each training step.

  • If you need to control how often those optimizers step or override the default .step() schedule, override the optimizer_step() hook.

distance_from_training()
property domain: Domain
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

get_test_dataset()
get_training_dataset()
get_validation_dataset()
is_within_domain()
learning_curve_train = []
learning_curve_val = []
load_training(path)
predict(x)
save_training(path)
training_epoch_end(outputs)

Called at the end of the training epoch with the outputs of all training steps. Use this in case you need to do something with all the outputs returned by training_step().

# the pseudocode for these calls
train_outs = []
for train_batch in train_data:
    out = training_step(train_batch)
    train_outs.append(out)
training_epoch_end(train_outs)
Parameters:

outputs – List of outputs you defined in training_step(). If there are multiple optimizers or when using truncated_bptt_steps > 0, the lists have the dimensions (n_batches, tbptt_steps, n_optimizers). Dimensions of length 1 are squeezed.

Returns:

None

Note

If this method is not overridden, this won’t be called.

def training_epoch_end(self, training_step_outputs):
    # do something with all training_step outputs
    for out in training_step_outputs:
        ...
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:
Returns:

Any of.

  • Tensor - The loss tensor

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

  • None - Training will skip to the next batch. This is only for automatic optimization.

    This is not supported for multi-GPU, TPU, IPU, or DeepSpeed.

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

If you define multiple optimizers, this step will be called with an additional optimizer_idx parameter.

# Multiple optimizers (e.g.: GANs)
def training_step(self, batch, batch_idx, optimizer_idx):
    if optimizer_idx == 0:
        # do training_step with encoder
        ...
    if optimizer_idx == 1:
        # do training_step with decoder
        ...

If you add truncated back propagation through time you will also get an additional argument with the hidden states of the previous step.

# Truncated back-propagation through time
def training_step(self, batch, batch_idx, hiddens):
    # hiddens are the hidden states from the previous truncated backprop step
    out, hiddens = self.lstm(data, hiddens)
    loss = ...
    return {"loss": loss, "hiddens": hiddens}

Note

The loss value shown in the progress bar is smoothed (averaged) over the last values, so it differs from the actual loss returned in train/validation step.

Note

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

validation_epoch_end(outputs)

Called at the end of the validation epoch with the outputs of all validation steps.

# the pseudocode for these calls
val_outs = []
for val_batch in val_data:
    out = validation_step(val_batch)
    val_outs.append(out)
validation_epoch_end(val_outs)
Parameters:

outputs – List of outputs you defined in validation_step(), or if there are multiple dataloaders, a list containing a list of outputs for each dataloader.

Returns:

None

Note

If you didn’t define a validation_step(), this won’t be called.

Examples

With a single dataloader:

def validation_epoch_end(self, val_step_outputs):
    for out in val_step_outputs:
        ...

With multiple dataloaders, outputs will be a list of lists. The outer list contains one entry per dataloader, while the inner list contains the individual outputs of each validation step for that dataloader.

def validation_epoch_end(self, outputs):
    for dataloader_output_result in outputs:
        dataloader_outs = dataloader_output_result.dataloader_i_outputs

    self.log("final_metric", final_value)
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.

# the pseudocode for these calls
val_outs = []
for val_batch in val_data:
    out = validation_step(val_batch)
    val_outs.append(out)
validation_epoch_end(val_outs)
Parameters:
  • batch – The output of your DataLoader.

  • batch_idx – The index of this batch.

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

Returns:

  • Any object or value

  • None - Validation will skip to the next batch

# pseudocode of order
val_outs = []
for val_batch in val_data:
    out = validation_step(val_batch)
    if defined("validation_step_end"):
        out = validation_step_end(out)
    val_outs.append(out)
val_outs = validation_epoch_end(val_outs)
# 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.
    ...

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 glasspy.predict.base.Domain(element: Dict[str, float] | None = None, compound: Dict[str, float] | None = None)

Bases: NamedTuple

Simple class to store chemical domain information.

compound: Dict[str, float]

Alias for field number 1

element: Dict[str, float]

Alias for field number 0

class glasspy.predict.base.MLP(hparams: Dict[str, Any])

Bases: LightningModule, Predict

Base class for creating Multilayer Perceptrons.

Parameters:

hparams

Dictionary with the hyperparemeters of the network. The possible parameters are: + “n_features”: number of input features (required). Must be a positive

integer.

  • ”num_layers”: number of hidden layers (defaults to 1). Must be a positive integer.

  • ”layer_n_size”: number of neurons in layer n (replace n for an integer starting at 1, defaults to 10). Must be a positive integer.

  • ”layer_n_activation”: activation function of layer n (replace n for an integer starting at 1, defaults to Tanh). Available values are [“Tanh”, “Sigmoid”, “ReLU”, “LeakyReLU”, “SELU”, “GELU”, “ELU”, “PReLU”, “SiLU”, “Mish”, “Softplus”, “Linear”].

  • ”layer_n_dropout”: dropout of layer n (replace n for an integer starting at 1, defaults to False meaning no dropout). Any value between 0 and 1 (or False) is permitted.

  • ”layer_n_batchnorm”: True will use batch normalization in layer n, False will not use batch normalization in layer n (replace n for an integer starting at 1, defaults to False meaning no batch normalization).

  • ”loss”: loss function to use for the backpropagation algorithm (defaults to mse). Use mse for mean squared error loss (L2) or huber for a smooth L1 loss.

  • ”optimizer”: optimizer algorithm to use (defaults SGD). Use SGD for stochastic gradient descend, Adam for Adam, or AdamW for weighted Adam.

  • ”lr”: optimizer learning rate (defaults to 1e-4 if optimizer is SGD or 1e-3 if optimizer is Adam or AdamW).

  • ”momentum”: momentum to use when optmizer is SGD (defaults to 0).

  • ”optimizer_Adam_eps”: eps to use for Adam or AdamW optimizers (defaults to 1e-8).

Raises:

NotImplementedError – When the selected hyperparameters is not one of the permited values.

configure_optimizers()

Choose what optimizers and learning-rate schedulers to use in your optimization. Normally you’d need one. But in the case of GANs or similar you might have multiple.

Returns:

Any of these 6 options.

  • Single optimizer.

  • List or Tuple of optimizers.

  • Two lists - The first list has multiple optimizers, and the second has multiple LR schedulers (or multiple lr_scheduler_config).

  • Dictionary, with an "optimizer" key, and (optionally) a "lr_scheduler" key whose value is a single LR scheduler or lr_scheduler_config.

  • Tuple of dictionaries as described above, with an optional "frequency" key.

  • None - Fit will run without any optimizer.

The lr_scheduler_config is a dictionary which contains the scheduler and its associated configuration. The default configuration is shown below.

lr_scheduler_config = {
    # REQUIRED: The scheduler instance
    "scheduler": lr_scheduler,
    # The unit of the scheduler's step size, could also be 'step'.
    # 'epoch' updates the scheduler on epoch end whereas 'step'
    # updates it after a optimizer update.
    "interval": "epoch",
    # How many epochs/steps should pass between calls to
    # `scheduler.step()`. 1 corresponds to updating the learning
    # rate after every epoch/step.
    "frequency": 1,
    # Metric to to monitor for schedulers like `ReduceLROnPlateau`
    "monitor": "val_loss",
    # If set to `True`, will enforce that the value specified 'monitor'
    # is available when the scheduler is updated, thus stopping
    # training if not found. If set to `False`, it will only produce a warning
    "strict": True,
    # If using the `LearningRateMonitor` callback to monitor the
    # learning rate progress, this keyword can be used to specify
    # a custom logged name
    "name": None,
}

When there are schedulers in which the .step() method is conditioned on a value, such as the torch.optim.lr_scheduler.ReduceLROnPlateau scheduler, Lightning requires that the lr_scheduler_config contains the keyword "monitor" set to the metric name that the scheduler should be conditioned on.

Metrics can be made available to monitor by simply logging it using self.log('metric_to_track', metric_val) in your LightningModule.

Note

The frequency value specified in a dict along with the optimizer key is an int corresponding to the number of sequential batches optimized with the specific optimizer. It should be given to none or to all of the optimizers. There is a difference between passing multiple optimizers in a list, and passing multiple optimizers in dictionaries with a frequency of 1:

  • In the former case, all optimizers will operate on the given batch in each optimization step.

  • In the latter, only one optimizer will operate on the given batch at every step.

This is different from the frequency value specified in the lr_scheduler_config mentioned above.

def configure_optimizers(self):
    optimizer_one = torch.optim.SGD(self.model.parameters(), lr=0.01)
    optimizer_two = torch.optim.SGD(self.model.parameters(), lr=0.01)
    return [
        {"optimizer": optimizer_one, "frequency": 5},
        {"optimizer": optimizer_two, "frequency": 10},
    ]

In this example, the first optimizer will be used for the first 5 steps, the second optimizer for the next 10 steps and that cycle will continue. If an LR scheduler is specified for an optimizer using the lr_scheduler key in the above dict, the scheduler will only be updated when its optimizer is being used.

Examples:

# most cases. no learning rate scheduler
def configure_optimizers(self):
    return Adam(self.parameters(), lr=1e-3)

# multiple optimizer case (e.g.: GAN)
def configure_optimizers(self):
    gen_opt = Adam(self.model_gen.parameters(), lr=0.01)
    dis_opt = Adam(self.model_dis.parameters(), lr=0.02)
    return gen_opt, dis_opt

# example with learning rate schedulers
def configure_optimizers(self):
    gen_opt = Adam(self.model_gen.parameters(), lr=0.01)
    dis_opt = Adam(self.model_dis.parameters(), lr=0.02)
    dis_sch = CosineAnnealing(dis_opt, T_max=10)
    return [gen_opt, dis_opt], [dis_sch]

# example with step-based learning rate schedulers
# each optimizer has its own scheduler
def configure_optimizers(self):
    gen_opt = Adam(self.model_gen.parameters(), lr=0.01)
    dis_opt = Adam(self.model_dis.parameters(), lr=0.02)
    gen_sch = {
        'scheduler': ExponentialLR(gen_opt, 0.99),
        'interval': 'step'  # called after each training step
    }
    dis_sch = CosineAnnealing(dis_opt, T_max=10) # called every epoch
    return [gen_opt, dis_opt], [gen_sch, dis_sch]

# example with optimizer frequencies
# see training procedure in `Improved Training of Wasserstein GANs`, Algorithm 1
# https://arxiv.org/abs/1704.00028
def configure_optimizers(self):
    gen_opt = Adam(self.model_gen.parameters(), lr=0.01)
    dis_opt = Adam(self.model_dis.parameters(), lr=0.02)
    n_critic = 5
    return (
        {'optimizer': dis_opt, 'frequency': n_critic},
        {'optimizer': gen_opt, 'frequency': 1}
    )

Note

Some things to know:

  • Lightning calls .backward() and .step() on each optimizer as needed.

  • If learning rate scheduler is specified in configure_optimizers() with key "interval" (default “epoch”) in the scheduler configuration, Lightning will call the scheduler’s .step() method automatically in case of automatic optimization.

  • If you use 16-bit precision (precision=16), Lightning will automatically handle the optimizers.

  • If you use multiple optimizers, training_step() will have an additional optimizer_idx parameter.

  • If you use torch.optim.LBFGS, Lightning handles the closure function automatically for you.

  • If you use multiple optimizers, gradients will be calculated only for the parameters of current optimizer at each training step.

  • If you need to control how often those optimizers step or override the default .step() schedule, override the optimizer_step() hook.

distance_from_training()
property domain: Domain
get_test_dataset()
get_training_dataset()
is_within_domain()
learning_curve_train = []
learning_curve_val = []
load_training(path)
on_train_epoch_end()

Called in the training loop at the very end of the epoch.

To access all batch outputs at the end of the epoch, either:

  1. Implement training_epoch_end in the LightningModule OR

  2. Cache data across steps on the attribute(s) of the LightningModule and access them in this hook

on_validation_epoch_end()

Called in the validation loop at the very end of the epoch.

save_training(path)
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:
Returns:

Any of.

  • Tensor - The loss tensor

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

  • None - Training will skip to the next batch. This is only for automatic optimization.

    This is not supported for multi-GPU, TPU, IPU, or DeepSpeed.

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

If you define multiple optimizers, this step will be called with an additional optimizer_idx parameter.

# Multiple optimizers (e.g.: GANs)
def training_step(self, batch, batch_idx, optimizer_idx):
    if optimizer_idx == 0:
        # do training_step with encoder
        ...
    if optimizer_idx == 1:
        # do training_step with decoder
        ...

If you add truncated back propagation through time you will also get an additional argument with the hidden states of the previous step.

# Truncated back-propagation through time
def training_step(self, batch, batch_idx, hiddens):
    # hiddens are the hidden states from the previous truncated backprop step
    out, hiddens = self.lstm(data, hiddens)
    loss = ...
    return {"loss": loss, "hiddens": hiddens}

Note

The loss value shown in the progress bar is smoothed (averaged) over the last values, so it differs from the actual loss returned in train/validation 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.

# the pseudocode for these calls
val_outs = []
for val_batch in val_data:
    out = validation_step(val_batch)
    val_outs.append(out)
validation_epoch_end(val_outs)
Parameters:
  • batch – The output of your DataLoader.

  • batch_idx – The index of this batch.

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

Returns:

  • Any object or value

  • None - Validation will skip to the next batch

# pseudocode of order
val_outs = []
for val_batch in val_data:
    out = validation_step(val_batch)
    if defined("validation_step_end"):
        out = validation_step_end(out)
    val_outs.append(out)
val_outs = validation_epoch_end(val_outs)
# 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.
    ...

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 glasspy.predict.base.MTL(hparams: Dict[str, Any])

Bases: MLP

Base class for creating Multi-task Learning NN.

Parameters:

hparams

Dictionary with the hyperparemeters of the network. The possible parameters are: + “n_features”: number of input features (required). Must be a positive

integer.

  • ”num_layers”: number of hidden layers (defaults to 1). Must be a positive integer.

  • ”layer_n_size”: number of neurons in layer n (replace n for an integer starting at 1, defaults to 10). Must be a positive integer.

  • ”layer_n_activation”: activation function of layer n (replace n for an integer starting at 1, defaults to Tanh). Available values are [“Tanh”, “Sigmoid”, “ReLU”, “LeakyReLU”, “SELU”, “GELU”, “ELU”, “PReLU”, “SiLU”, “Mish”, “Softplus”, “Linear”].

  • ”layer_n_dropout”: dropout of layer n (replace n for an integer starting at 1, defaults to False meaning no dropout). Any value between 0 and 1 (or False) is permitted.

  • ”layer_n_batchnorm”: True will use batch normalization in layer n, False will not use batch normalization in layer n (replace n for an integer starting at 1, defaults to False meaning no batch normalization).

  • ”loss”: loss function to use for the backpropagation algorithm (defaults to mse). Use mse for mean squared error loss (L2) or huber for a smooth L1 loss.

  • ”optimizer”: optimizer algorithm to use (defaults SGD). Use SGD for stochastic gradient descend, Adam for Adam, or AdamW for weighted Adam.

  • ”lr”: optimizer learning rate (defaults to 1e-4 if optimizer is SGD or 1e-3 if optimizer is Adam or AdamW).

  • ”momentum”: momentum to use when optmizer is SGD (defaults to 0).

  • ”optimizer_Adam_eps”: eps to use for Adam or AdamW optimizers (defaults to 1e-8).

Raises:

NotImplementedError – When the selected hyperparameters is not one of the permited values.

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:
Returns:

Any of.

  • Tensor - The loss tensor

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

  • None - Training will skip to the next batch. This is only for automatic optimization.

    This is not supported for multi-GPU, TPU, IPU, or DeepSpeed.

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

If you define multiple optimizers, this step will be called with an additional optimizer_idx parameter.

# Multiple optimizers (e.g.: GANs)
def training_step(self, batch, batch_idx, optimizer_idx):
    if optimizer_idx == 0:
        # do training_step with encoder
        ...
    if optimizer_idx == 1:
        # do training_step with decoder
        ...

If you add truncated back propagation through time you will also get an additional argument with the hidden states of the previous step.

# Truncated back-propagation through time
def training_step(self, batch, batch_idx, hiddens):
    # hiddens are the hidden states from the previous truncated backprop step
    out, hiddens = self.lstm(data, hiddens)
    loss = ...
    return {"loss": loss, "hiddens": hiddens}

Note

The loss value shown in the progress bar is smoothed (averaged) over the last values, so it differs from the actual loss returned in train/validation 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.

# the pseudocode for these calls
val_outs = []
for val_batch in val_data:
    out = validation_step(val_batch)
    val_outs.append(out)
validation_epoch_end(val_outs)
Parameters:
  • batch – The output of your DataLoader.

  • batch_idx – The index of this batch.

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

Returns:

  • Any object or value

  • None - Validation will skip to the next batch

# pseudocode of order
val_outs = []
for val_batch in val_data:
    out = validation_step(val_batch)
    if defined("validation_step_end"):
        out = validation_step_end(out)
    val_outs.append(out)
val_outs = validation_epoch_end(val_outs)
# 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.
    ...

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 glasspy.predict.base.Predict(**kwargs)

Bases: ABC

Base class for GlassPy predictors.

static MAE(y_true: ndarray, y_pred: ndarray) float

Computes the mean absolute error.

Parameters:
  • y_true – Array with the true values of y. Can be 1D or 2D.

  • y_pred – Aray with the predicted values of y. Can be 1D or 2D.

Returns:

The mean absolute error. Will be 1D if the input arrays are 2D. Will be a scalar otherwise.

static MSE(y_true: ndarray, y_pred: ndarray) float

Computes the mean squared error.

Parameters:
  • y_true – Array with the true values of y. Can be 1D or 2D.

  • y_pred – Aray with the predicted values of y. Can be 1D or 2D.

Returns:

The mean squared error. Will be 1D if the input arrays are 2D. Will be a scalar otherwise.

static MedAE(y_true: ndarray, y_pred: ndarray) float

Computes the median absolute error.

Parameters:
  • y_true – Array with the true values of y. Can be 1D or 2D.

  • y_pred – Aray with the predicted values of y. Can be 1D or 2D.

Returns:

The median absolute error. Will be 1D if the input arrays are 2D. Will be a scalar otherwise.

static PercAE(y_true: ndarray, y_pred: ndarray, q=75) float

Computes the percentile absolute error.

Parameters:
  • y_true – Array with the true values of y. Can be 1D or 2D.

  • y_pred – Aray with the predicted values of y. Can be 1D or 2D.

  • q – Percentile to compute.

Returns:

The percentile absolute error. Will be 1D if the input arrays are 2D. Will be a scalar otherwise.

static R2(y_true: ndarray, y_pred: ndarray, one_param: bool = True) float

Computes the coefficient of determination.

Parameters:
  • y_true – 1D array with the true values of y.

  • y_pred – 1D array with the predicted values of y.

  • one_param – Determines the relationship between y_true and y_pred. If ´True´ then it is a relationship with one parameter (y_true = y_pred * c_0 + error). If ´False´ then it is a relationship with two parameters (y_true = y_pred * c_0 + c_1 + error). In most of regression problems, the first case is desired.

Returns:

The coefficient of determination.

static RD(y_true: ndarray, y_pred: ndarray) float

Computes the relative deviation.

Parameters:
  • y_true – 1D array with the true values of y.

  • y_pred – 1D array with the predicted values of y.

Returns:

The relative deviation.

static RMSE(y_true: ndarray, y_pred: ndarray) float

Computes the root mean squared error.

Parameters:
  • y_true – Array with the true values of y. Can be 1D or 2D.

  • y_pred – Aray with the predicted values of y. Can be 1D or 2D.

Returns:

The root mean squared error. Will be 1D if the input arrays are 2D. Will be a scalar otherwise.

static RRMSE(y_true: ndarray, y_pred: ndarray) float

Computes the relative root mean squared error.

Parameters:
  • y_true – 1D array with the true values of y.

  • y_pred – 1D array with the predicted values of y.

Returns:

The relative root mean squared error.

abstract property domain
abstract get_test_dataset()
abstract get_training_dataset()
abstract is_within_domain()
abstract predict()

glasspy.predict.models module

Predictive models offered by GlassPy.

class glasspy.predict.models.GlassNet(st_models='default')

Bases: GlassNetMTMH

Hybrid neural network for predicting glass properties.

This hybrid model has a multitask neural network to compute most of the properties and especialized neural networks to predict selected properties.

Parameters:

st_models – List of the properties to use especialized models instead of using the multitask network. If default, then the model uses those properties that performed better than the multitask model.

predict(composition: str | List[float] | List[List[float]] | ndarray | Dict[str, float] | Dict[str, List[float]] | Dict[str, ndarray] | DataFrame | ChemArray, input_cols: List[str] = [], return_dataframe: bool = True)

Makes prediction of properties.

Parameters:
  • composition – Any composition-like object.

  • input_cols – List of strings representing the chemical entities related to each column of composition. Necessary only when composition is a list or array, ignored otherwise.

  • return_dataframe – If True, then returns a pandas DataFrame, else returns an array. Default value is True.

Returns:

Predicted values of properties. Will be a DataFrame if return_dataframe is True, otherwise will be an array.

class glasspy.predict.models.GlassNetMTMH

Bases: _BaseGlassNet, _BaseGlassNetViscosity

Multitask neural network for predicting glass properties.

This is the MT-MH model.

forward(x)

Method used for training the neural network.

Consider using the other methods for prediction.

Parameters:

x – Feature tensor.

Returns

Tensor with the predictions.

hparams = {'batch_size': 256, 'layer_1_activation': 'Softplus', 'layer_1_batchnorm': True, 'layer_1_dropout': 0.08118311665886885, 'layer_1_size': 280, 'layer_2_activation': 'Mish', 'layer_2_batchnorm': True, 'layer_2_dropout': 0.0009472891190852595, 'layer_2_size': 500, 'layer_3_activation': 'LeakyReLU', 'layer_3_batchnorm': False, 'layer_3_dropout': 0.08660291424886811, 'layer_3_size': 390, 'layer_4_activation': 'PReLU', 'layer_4_batchnorm': False, 'layer_4_dropout': 0.16775047518280012, 'layer_4_size': 480, 'loss': 'mse', 'lr': 1.3252600209332101e-05, 'max_epochs': 2000, 'n_features': 98, 'n_targets': 85, 'num_layers': 4, 'optimizer': 'AdamW', 'patience': 27}
target_trans = {'AbbeNum': 36, 'CTE328K': 64, 'CTE373K': 65, 'CTE433K': 66, 'CTE483K': 67, 'CTE623K': 68, 'CTEbelowTg': 63, 'Cp1073K': 72, 'Cp1273K': 73, 'Cp1473K': 74, 'Cp1673K': 75, 'Cp293K': 69, 'Cp473K': 70, 'Cp673K': 71, 'CrystallizationOnset': 79, 'CrystallizationPeak': 78, 'Density1073K': 57, 'Density1273K': 58, 'Density1473K': 59, 'Density1673K': 60, 'Density293K': 56, 'MaxGrowthVelocity': 77, 'MeanDispersion': 40, 'Microhardness': 54, 'Permittivity': 41, 'PoissonRatio': 55, 'RefractiveIndex': 37, 'RefractiveIndexHigh': 39, 'RefractiveIndexLow': 38, 'Resistivity1073K': 48, 'Resistivity1273K': 49, 'Resistivity1473K': 50, 'Resistivity1673K': 51, 'Resistivity273K': 44, 'Resistivity373K': 45, 'Resistivity423K': 46, 'Resistivity573K': 47, 'ShearModulus': 53, 'SurfaceTension1173K': 81, 'SurfaceTension1473K': 82, 'SurfaceTension1573K': 83, 'SurfaceTension1673K': 84, 'SurfaceTensionAboveTg': 80, 'T0': 0, 'T1': 1, 'T10': 10, 'T11': 11, 'T12': 12, 'T2': 2, 'T3': 3, 'T4': 4, 'T5': 5, 'T6': 6, 'T7': 7, 'T8': 8, 'T9': 9, 'TAnnealing': 32, 'TLittletons': 31, 'TMaxGrowthVelocity': 76, 'TangentOfLossAngle': 42, 'TdilatometricSoftening': 35, 'Tg': 28, 'ThermalConductivity': 61, 'ThermalShockRes': 62, 'Tliquidus': 30, 'Tmelt': 29, 'TresistivityIs1MOhm.m': 43, 'Tsoft': 34, 'Tstrain': 33, 'Viscosity1073K': 16, 'Viscosity1173K': 17, 'Viscosity1273K': 18, 'Viscosity1373K': 19, 'Viscosity1473K': 20, 'Viscosity1573K': 21, 'Viscosity1673K': 22, 'Viscosity1773K': 23, 'Viscosity1873K': 24, 'Viscosity2073K': 25, 'Viscosity2273K': 26, 'Viscosity2473K': 27, 'Viscosity773K': 13, 'Viscosity873K': 14, 'Viscosity973K': 15, 'YoungModulus': 52}
targets = ['T0', 'T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'T8', 'T9', 'T10', 'T11', 'T12', 'Viscosity773K', 'Viscosity873K', 'Viscosity973K', 'Viscosity1073K', 'Viscosity1173K', 'Viscosity1273K', 'Viscosity1373K', 'Viscosity1473K', 'Viscosity1573K', 'Viscosity1673K', 'Viscosity1773K', 'Viscosity1873K', 'Viscosity2073K', 'Viscosity2273K', 'Viscosity2473K', 'Tg', 'Tmelt', 'Tliquidus', 'TLittletons', 'TAnnealing', 'Tstrain', 'Tsoft', 'TdilatometricSoftening', 'AbbeNum', 'RefractiveIndex', 'RefractiveIndexLow', 'RefractiveIndexHigh', 'MeanDispersion', 'Permittivity', 'TangentOfLossAngle', 'TresistivityIs1MOhm.m', 'Resistivity273K', 'Resistivity373K', 'Resistivity423K', 'Resistivity573K', 'Resistivity1073K', 'Resistivity1273K', 'Resistivity1473K', 'Resistivity1673K', 'YoungModulus', 'ShearModulus', 'Microhardness', 'PoissonRatio', 'Density293K', 'Density1073K', 'Density1273K', 'Density1473K', 'Density1673K', 'ThermalConductivity', 'ThermalShockRes', 'CTEbelowTg', 'CTE328K', 'CTE373K', 'CTE433K', 'CTE483K', 'CTE623K', 'Cp293K', 'Cp473K', 'Cp673K', 'Cp1073K', 'Cp1273K', 'Cp1473K', 'Cp1673K', 'TMaxGrowthVelocity', 'MaxGrowthVelocity', 'CrystallizationPeak', 'CrystallizationOnset', 'SurfaceTensionAboveTg', 'SurfaceTension1173K', 'SurfaceTension1473K', 'SurfaceTension1573K', 'SurfaceTension1673K']
training_file = PosixPath('/home/daniel/data/Git/Work/glasspy/glasspy/predict/models/GlassNetMH.p')
class glasspy.predict.models.GlassNetMTMLP

Bases: _BaseGlassNet, _BaseGlassNetViscosity

Multitask neural network for predicting glass properties.

This is the MT-MLP model.

hparams = {'batch_size': 256, 'layer_1_activation': 'Softplus', 'layer_1_batchnorm': True, 'layer_1_dropout': 0.08118311665886885, 'layer_1_size': 280, 'layer_2_activation': 'Mish', 'layer_2_batchnorm': True, 'layer_2_dropout': 0.0009472891190852595, 'layer_2_size': 500, 'layer_3_activation': 'LeakyReLU', 'layer_3_batchnorm': False, 'layer_3_dropout': 0.08660291424886811, 'layer_3_size': 390, 'layer_4_activation': 'PReLU', 'layer_4_batchnorm': False, 'layer_4_dropout': 0.16775047518280012, 'layer_4_size': 480, 'loss': 'mse', 'lr': 1.3252600209332101e-05, 'max_epochs': 2000, 'n_features': 98, 'n_targets': 85, 'num_layers': 4, 'optimizer': 'AdamW', 'patience': 27}
target_trans = {'AbbeNum': 36, 'CTE328K': 64, 'CTE373K': 65, 'CTE433K': 66, 'CTE483K': 67, 'CTE623K': 68, 'CTEbelowTg': 63, 'Cp1073K': 72, 'Cp1273K': 73, 'Cp1473K': 74, 'Cp1673K': 75, 'Cp293K': 69, 'Cp473K': 70, 'Cp673K': 71, 'CrystallizationOnset': 79, 'CrystallizationPeak': 78, 'Density1073K': 57, 'Density1273K': 58, 'Density1473K': 59, 'Density1673K': 60, 'Density293K': 56, 'MaxGrowthVelocity': 77, 'MeanDispersion': 40, 'Microhardness': 54, 'Permittivity': 41, 'PoissonRatio': 55, 'RefractiveIndex': 37, 'RefractiveIndexHigh': 39, 'RefractiveIndexLow': 38, 'Resistivity1073K': 48, 'Resistivity1273K': 49, 'Resistivity1473K': 50, 'Resistivity1673K': 51, 'Resistivity273K': 44, 'Resistivity373K': 45, 'Resistivity423K': 46, 'Resistivity573K': 47, 'ShearModulus': 53, 'SurfaceTension1173K': 81, 'SurfaceTension1473K': 82, 'SurfaceTension1573K': 83, 'SurfaceTension1673K': 84, 'SurfaceTensionAboveTg': 80, 'T0': 0, 'T1': 1, 'T10': 10, 'T11': 11, 'T12': 12, 'T2': 2, 'T3': 3, 'T4': 4, 'T5': 5, 'T6': 6, 'T7': 7, 'T8': 8, 'T9': 9, 'TAnnealing': 32, 'TLittletons': 31, 'TMaxGrowthVelocity': 76, 'TangentOfLossAngle': 42, 'TdilatometricSoftening': 35, 'Tg': 28, 'ThermalConductivity': 61, 'ThermalShockRes': 62, 'Tliquidus': 30, 'Tmelt': 29, 'TresistivityIs1MOhm.m': 43, 'Tsoft': 34, 'Tstrain': 33, 'Viscosity1073K': 16, 'Viscosity1173K': 17, 'Viscosity1273K': 18, 'Viscosity1373K': 19, 'Viscosity1473K': 20, 'Viscosity1573K': 21, 'Viscosity1673K': 22, 'Viscosity1773K': 23, 'Viscosity1873K': 24, 'Viscosity2073K': 25, 'Viscosity2273K': 26, 'Viscosity2473K': 27, 'Viscosity773K': 13, 'Viscosity873K': 14, 'Viscosity973K': 15, 'YoungModulus': 52}
targets = ['T0', 'T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'T8', 'T9', 'T10', 'T11', 'T12', 'Viscosity773K', 'Viscosity873K', 'Viscosity973K', 'Viscosity1073K', 'Viscosity1173K', 'Viscosity1273K', 'Viscosity1373K', 'Viscosity1473K', 'Viscosity1573K', 'Viscosity1673K', 'Viscosity1773K', 'Viscosity1873K', 'Viscosity2073K', 'Viscosity2273K', 'Viscosity2473K', 'Tg', 'Tmelt', 'Tliquidus', 'TLittletons', 'TAnnealing', 'Tstrain', 'Tsoft', 'TdilatometricSoftening', 'AbbeNum', 'RefractiveIndex', 'RefractiveIndexLow', 'RefractiveIndexHigh', 'MeanDispersion', 'Permittivity', 'TangentOfLossAngle', 'TresistivityIs1MOhm.m', 'Resistivity273K', 'Resistivity373K', 'Resistivity423K', 'Resistivity573K', 'Resistivity1073K', 'Resistivity1273K', 'Resistivity1473K', 'Resistivity1673K', 'YoungModulus', 'ShearModulus', 'Microhardness', 'PoissonRatio', 'Density293K', 'Density1073K', 'Density1273K', 'Density1473K', 'Density1673K', 'ThermalConductivity', 'ThermalShockRes', 'CTEbelowTg', 'CTE328K', 'CTE373K', 'CTE433K', 'CTE483K', 'CTE623K', 'Cp293K', 'Cp473K', 'Cp673K', 'Cp1073K', 'Cp1273K', 'Cp1473K', 'Cp1673K', 'TMaxGrowthVelocity', 'MaxGrowthVelocity', 'CrystallizationPeak', 'CrystallizationOnset', 'SurfaceTensionAboveTg', 'SurfaceTension1173K', 'SurfaceTension1473K', 'SurfaceTension1573K', 'SurfaceTension1673K']
training_file = PosixPath('/home/daniel/data/Git/Work/glasspy/glasspy/predict/models/GlassNet.p')
class glasspy.predict.models.GlassNetSTNN(model_name)

Bases: _BaseGlassNet

Single-task neural network for predicting glass properties.

This is the ST-NN model.

forward(x)

Method used for training the neural network.

Consider using the other methods for prediction.

Parameters:

x – Feature tensor.

Returns

Tensor with the predictions.

hparams = {'batch_size': 256, 'layer_1_activation': 'Softplus', 'layer_1_batchnorm': True, 'layer_1_dropout': 0.08118311665886885, 'layer_1_size': 280, 'layer_2_activation': 'Mish', 'layer_2_batchnorm': True, 'layer_2_dropout': 0.0009472891190852595, 'layer_2_size': 500, 'layer_3_activation': 'LeakyReLU', 'layer_3_batchnorm': False, 'layer_3_dropout': 0.08660291424886811, 'layer_3_size': 390, 'layer_4_activation': 'PReLU', 'layer_4_batchnorm': False, 'layer_4_dropout': 0.16775047518280012, 'layer_4_size': 480, 'loss': 'mse', 'lr': 1.3252600209332101e-05, 'max_epochs': 2000, 'n_features': 98, 'n_targets': 1, 'num_layers': 4, 'optimizer': 'AdamW', 'patience': 27}
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:
Returns:

Any of.

  • Tensor - The loss tensor

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

  • None - Training will skip to the next batch. This is only for automatic optimization.

    This is not supported for multi-GPU, TPU, IPU, or DeepSpeed.

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

If you define multiple optimizers, this step will be called with an additional optimizer_idx parameter.

# Multiple optimizers (e.g.: GANs)
def training_step(self, batch, batch_idx, optimizer_idx):
    if optimizer_idx == 0:
        # do training_step with encoder
        ...
    if optimizer_idx == 1:
        # do training_step with decoder
        ...

If you add truncated back propagation through time you will also get an additional argument with the hidden states of the previous step.

# Truncated back-propagation through time
def training_step(self, batch, batch_idx, hiddens):
    # hiddens are the hidden states from the previous truncated backprop step
    out, hiddens = self.lstm(data, hiddens)
    loss = ...
    return {"loss": loss, "hiddens": hiddens}

Note

The loss value shown in the progress bar is smoothed (averaged) over the last values, so it differs from the actual loss returned in train/validation 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.

# the pseudocode for these calls
val_outs = []
for val_batch in val_data:
    out = validation_step(val_batch)
    val_outs.append(out)
validation_epoch_end(val_outs)
Parameters:
  • batch – The output of your DataLoader.

  • batch_idx – The index of this batch.

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

Returns:

  • Any object or value

  • None - Validation will skip to the next batch

# pseudocode of order
val_outs = []
for val_batch in val_data:
    out = validation_step(val_batch)
    if defined("validation_step_end"):
        out = validation_step_end(out)
    val_outs.append(out)
val_outs = validation_epoch_end(val_outs)
# 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.
    ...

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 glasspy.predict.models.ViscNet

Bases: _BaseViscNet

ViscNet predictor of viscosity and viscosity parameters.

ViscNet is a physics-informed neural network that has the MYEGA [1] viscosity equation embedded in it. See Ref. [2] for the original publication.

References

[1] J.C. Mauro, Y. Yue, A.J. Ellison, P.K. Gupta, D.C. Allan, Viscosity of

glass-forming liquids., Proceedings of the National Academy of Sciences of the United States of America. 106 (2009) 19780–19784. https://doi.org/10.1073/pnas.0911705106.

[2] D.R. Cassar, ViscNet: Neural network for predicting the fragility

index and the temperature-dependency of viscosity, Acta Materialia. 206 (2021) 116602. https://doi.org/10.1016/j.actamat.2020.116602. https://arxiv.org/abs/2007.03719

absolute_features = [('ElectronAffinity', 'std1'), ('FusionEnthalpy', 'std1'), ('GSenergy_pa', 'std1'), ('GSmagmom', 'std1'), ('NdUnfilled', 'std1'), ('NfValence', 'std1'), ('NpUnfilled', 'std1'), ('atomic_radius_rahm', 'std1'), ('c6_gb', 'std1'), ('lattice_constant', 'std1'), ('mendeleev_number', 'std1'), ('num_oxistates', 'std1'), ('nvalence', 'std1'), ('vdw_radius_alvarez', 'std1'), ('vdw_radius_uff', 'std1'), ('zeff', 'std1')]
featurizer(composition: str | List[float] | List[List[float]] | ndarray | Dict[str, float] | Dict[str, List[float]] | Dict[str, ndarray] | DataFrame | ChemArray, input_cols: List[str] = []) ndarray

Compute the chemical features used for viscosity prediction.

Parameters:
  • composition – Any composition like object.

  • input_cols – List of strings representing the chemical entities related to each column of composition. Necessary only when composition is a list or array, ignored otherwise.

Returns:

Array with the computed chemical features

hparams = {'batch_size': 64, 'layer_1_activation': 'ReLU', 'layer_1_batchnorm': False, 'layer_1_dropout': 0.07942161101271952, 'layer_1_size': 192, 'layer_2_activation': 'Tanh', 'layer_2_batchnorm': False, 'layer_2_dropout': 0.05371454289414608, 'layer_2_size': 48, 'loss': 'mse', 'lr': 0.0011695226458761677, 'max_epochs': 500, 'n_features': 35, 'num_layers': 2, 'optimizer': 'AdamW', 'patience': 9}
log_viscosity_fun(T, log_eta_inf, Tg, m)

Computes the base-10 logarithm of viscosity using the MYEGA equation.

parameters_range = {'Tg': [400, 1400], 'log_eta_inf': [-18, 5], 'm': [10, 130]}
state_dict_path = PosixPath('/home/daniel/data/Git/Work/glasspy/glasspy/predict/models/ViscNet_SD.p')
weighted_features = [('FusionEnthalpy', 'min'), ('GSbandgap', 'max'), ('GSmagmom', 'mean'), ('GSvolume_pa', 'max'), ('MiracleRadius', 'std1'), ('NValence', 'max'), ('NValence', 'min'), ('NdUnfilled', 'max'), ('NdValence', 'max'), ('NsUnfilled', 'max'), ('SpaceGroupNumber', 'max'), ('SpaceGroupNumber', 'min'), ('atomic_radius', 'max'), ('atomic_volume', 'max'), ('c6_gb', 'max'), ('c6_gb', 'min'), ('max_ionenergy', 'min'), ('num_oxistates', 'max'), ('nvalence', 'min')]
x_mean = tensor([5.7542e+01, 2.2090e+01, 2.0236e+00, 3.6861e-02, 3.2621e-01, 1.4419e+00,         2.0165e+00, 3.4408e+01, 1.2353e+03, 1.4793e+00, 4.2045e+01, 8.4131e-01,         2.3045e+00, 4.7985e+01, 5.6984e+01, 1.1146e+00, 9.2186e-02, 2.1363e-01,         2.2581e-04, 5.8150e+00, 1.2964e+01, 3.7008e+00, 1.3743e-01, 1.8370e-02,         3.2303e-01, 7.1325e-02, 5.0019e+01, 4.3720e+00, 3.6446e+01, 8.4037e+00,         2.0281e+02, 7.5614e+00, 1.2259e+02, 6.7183e-01, 1.0508e-01])
x_std = tensor([7.6421e+00, 4.7181e+00, 4.5828e-01, 1.6873e-01, 9.7033e-01, 2.7695e+00,         3.3153e-01, 6.4521e+00, 6.3392e+02, 4.0606e-01, 1.1777e+01, 2.8130e-01,         7.9214e-01, 7.5883e+00, 1.1335e+01, 2.8823e-01, 4.4787e-02, 1.1219e-01,         1.2392e-03, 1.1634e+00, 2.9514e+00, 4.7246e-01, 3.1958e-01, 8.8973e-02,         6.7548e-01, 6.2869e-02, 1.0004e+01, 2.7434e+00, 1.9245e+00, 3.4735e-01,         1.2475e+02, 3.2668e+00, 1.5287e+02, 7.3511e-02, 1.6188e-01])
class glasspy.predict.models.ViscNetHuber

Bases: ViscNet

ViscNet-Huber predictor of viscosity and viscosity parameters.

ViscNet-Huber is a physics-informed neural network that has the MYEGA [1] viscosity equation embedded in it. The difference between this model and ViscNet is the loss function: this model has a robust smooth-L1 loss function, while ViscNet has a MSE (L2) loss function. See Ref. [2] for the original publication.

References

[1] J.C. Mauro, Y. Yue, A.J. Ellison, P.K. Gupta, D.C. Allan, Viscosity of

glass-forming liquids., Proceedings of the National Academy of Sciences of the United States of America. 106 (2009) 19780–19784. https://doi.org/10.1073/pnas.0911705106.

[2] D.R. Cassar, ViscNet: Neural network for predicting the fragility

index and the temperature-dependency of viscosity, Acta Materialia. 206 (2021) 116602. https://doi.org/10.1016/j.actamat.2020.116602. https://arxiv.org/abs/2007.03719

class glasspy.predict.models.ViscNetVFT

Bases: ViscNet

ViscNet-VFT predictor of viscosity and viscosity parameters.

ViscNet-VFT is a physics-informed neural network that has the VFT [1-3] viscosity equation embedded in it. See Ref. [4] for the original publication.

References

[1] H. Vogel, Das Temperatureabhängigketsgesetz der Viskosität von

Flüssigkeiten, Physikalische Zeitschrift. 22 (1921) 645–646.

[2] G.S. Fulcher, Analysis of recent measurements of the viscosity of

glasses, Journal of the American Ceramic Society. 8 (1925) 339–355. https://doi.org/10.1111/j.1151-2916.1925.tb16731.x.

[3] G. Tammann, W. Hesse, Die Abhängigkeit der Viscosität von der

Temperatur bie unterkühlten Flüssigkeiten, Z. Anorg. Allg. Chem. 156 (1926) 245–257. https://doi.org/10.1002/zaac.19261560121.

[4] D.R. Cassar, ViscNet: Neural network for predicting the fragility

index and the temperature-dependency of viscosity, Acta Materialia. 206 (2021) 116602. https://doi.org/10.1016/j.actamat.2020.116602. https://arxiv.org/abs/2007.03719

log_viscosity_fun(T, log_eta_inf, Tg, m)

Computes the base-10 logarithm of viscosity using the VFT equation.

Reference:
[1] H. Vogel, Das Temperatureabhängigketsgesetz der Viskosität von

Flüssigkeiten, Physikalische Zeitschrift. 22 (1921) 645–646.

[2] G.S. Fulcher, Analysis of recent measurements of the viscosity of

glasses, Journal of the American Ceramic Society. 8 (1925) 339–355. https://doi.org/10.1111/j.1151-2916.1925.tb16731.x.

[3] G. Tammann, W. Hesse, Die Abhängigkeit der Viscosität von der

Temperatur bie unterkühlten Flüssigkeiten, Z. Anorg. Allg. Chem. 156 (1926) 245–257. https://doi.org/10.1002/zaac.19261560121.

Module contents

class glasspy.predict.GlassNet(st_models='default')

Bases: GlassNetMTMH

Hybrid neural network for predicting glass properties.

This hybrid model has a multitask neural network to compute most of the properties and especialized neural networks to predict selected properties.

Parameters:

st_models – List of the properties to use especialized models instead of using the multitask network. If default, then the model uses those properties that performed better than the multitask model.

predict(composition: str | List[float] | List[List[float]] | ndarray | Dict[str, float] | Dict[str, List[float]] | Dict[str, ndarray] | DataFrame | ChemArray, input_cols: List[str] = [], return_dataframe: bool = True)

Makes prediction of properties.

Parameters:
  • composition – Any composition-like object.

  • input_cols – List of strings representing the chemical entities related to each column of composition. Necessary only when composition is a list or array, ignored otherwise.

  • return_dataframe – If True, then returns a pandas DataFrame, else returns an array. Default value is True.

Returns:

Predicted values of properties. Will be a DataFrame if return_dataframe is True, otherwise will be an array.

class glasspy.predict.GlassNetMTMH

Bases: _BaseGlassNet, _BaseGlassNetViscosity

Multitask neural network for predicting glass properties.

This is the MT-MH model.

allow_zero_length_dataloader_with_multiple_devices: bool
forward(x)

Method used for training the neural network.

Consider using the other methods for prediction.

Parameters:

x – Feature tensor.

Returns

Tensor with the predictions.

hparams = {'batch_size': 256, 'layer_1_activation': 'Softplus', 'layer_1_batchnorm': True, 'layer_1_dropout': 0.08118311665886885, 'layer_1_size': 280, 'layer_2_activation': 'Mish', 'layer_2_batchnorm': True, 'layer_2_dropout': 0.0009472891190852595, 'layer_2_size': 500, 'layer_3_activation': 'LeakyReLU', 'layer_3_batchnorm': False, 'layer_3_dropout': 0.08660291424886811, 'layer_3_size': 390, 'layer_4_activation': 'PReLU', 'layer_4_batchnorm': False, 'layer_4_dropout': 0.16775047518280012, 'layer_4_size': 480, 'loss': 'mse', 'lr': 1.3252600209332101e-05, 'max_epochs': 2000, 'n_features': 98, 'n_targets': 85, 'num_layers': 4, 'optimizer': 'AdamW', 'patience': 27}
precision: int | str
prepare_data_per_node: bool
target_trans = {'AbbeNum': 36, 'CTE328K': 64, 'CTE373K': 65, 'CTE433K': 66, 'CTE483K': 67, 'CTE623K': 68, 'CTEbelowTg': 63, 'Cp1073K': 72, 'Cp1273K': 73, 'Cp1473K': 74, 'Cp1673K': 75, 'Cp293K': 69, 'Cp473K': 70, 'Cp673K': 71, 'CrystallizationOnset': 79, 'CrystallizationPeak': 78, 'Density1073K': 57, 'Density1273K': 58, 'Density1473K': 59, 'Density1673K': 60, 'Density293K': 56, 'MaxGrowthVelocity': 77, 'MeanDispersion': 40, 'Microhardness': 54, 'Permittivity': 41, 'PoissonRatio': 55, 'RefractiveIndex': 37, 'RefractiveIndexHigh': 39, 'RefractiveIndexLow': 38, 'Resistivity1073K': 48, 'Resistivity1273K': 49, 'Resistivity1473K': 50, 'Resistivity1673K': 51, 'Resistivity273K': 44, 'Resistivity373K': 45, 'Resistivity423K': 46, 'Resistivity573K': 47, 'ShearModulus': 53, 'SurfaceTension1173K': 81, 'SurfaceTension1473K': 82, 'SurfaceTension1573K': 83, 'SurfaceTension1673K': 84, 'SurfaceTensionAboveTg': 80, 'T0': 0, 'T1': 1, 'T10': 10, 'T11': 11, 'T12': 12, 'T2': 2, 'T3': 3, 'T4': 4, 'T5': 5, 'T6': 6, 'T7': 7, 'T8': 8, 'T9': 9, 'TAnnealing': 32, 'TLittletons': 31, 'TMaxGrowthVelocity': 76, 'TangentOfLossAngle': 42, 'TdilatometricSoftening': 35, 'Tg': 28, 'ThermalConductivity': 61, 'ThermalShockRes': 62, 'Tliquidus': 30, 'Tmelt': 29, 'TresistivityIs1MOhm.m': 43, 'Tsoft': 34, 'Tstrain': 33, 'Viscosity1073K': 16, 'Viscosity1173K': 17, 'Viscosity1273K': 18, 'Viscosity1373K': 19, 'Viscosity1473K': 20, 'Viscosity1573K': 21, 'Viscosity1673K': 22, 'Viscosity1773K': 23, 'Viscosity1873K': 24, 'Viscosity2073K': 25, 'Viscosity2273K': 26, 'Viscosity2473K': 27, 'Viscosity773K': 13, 'Viscosity873K': 14, 'Viscosity973K': 15, 'YoungModulus': 52}
targets = ['T0', 'T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'T8', 'T9', 'T10', 'T11', 'T12', 'Viscosity773K', 'Viscosity873K', 'Viscosity973K', 'Viscosity1073K', 'Viscosity1173K', 'Viscosity1273K', 'Viscosity1373K', 'Viscosity1473K', 'Viscosity1573K', 'Viscosity1673K', 'Viscosity1773K', 'Viscosity1873K', 'Viscosity2073K', 'Viscosity2273K', 'Viscosity2473K', 'Tg', 'Tmelt', 'Tliquidus', 'TLittletons', 'TAnnealing', 'Tstrain', 'Tsoft', 'TdilatometricSoftening', 'AbbeNum', 'RefractiveIndex', 'RefractiveIndexLow', 'RefractiveIndexHigh', 'MeanDispersion', 'Permittivity', 'TangentOfLossAngle', 'TresistivityIs1MOhm.m', 'Resistivity273K', 'Resistivity373K', 'Resistivity423K', 'Resistivity573K', 'Resistivity1073K', 'Resistivity1273K', 'Resistivity1473K', 'Resistivity1673K', 'YoungModulus', 'ShearModulus', 'Microhardness', 'PoissonRatio', 'Density293K', 'Density1073K', 'Density1273K', 'Density1473K', 'Density1673K', 'ThermalConductivity', 'ThermalShockRes', 'CTEbelowTg', 'CTE328K', 'CTE373K', 'CTE433K', 'CTE483K', 'CTE623K', 'Cp293K', 'Cp473K', 'Cp673K', 'Cp1073K', 'Cp1273K', 'Cp1473K', 'Cp1673K', 'TMaxGrowthVelocity', 'MaxGrowthVelocity', 'CrystallizationPeak', 'CrystallizationOnset', 'SurfaceTensionAboveTg', 'SurfaceTension1173K', 'SurfaceTension1473K', 'SurfaceTension1573K', 'SurfaceTension1673K']
training: bool
training_file = PosixPath('/home/daniel/data/Git/Work/glasspy/glasspy/predict/models/GlassNetMH.p')
class glasspy.predict.GlassNetMTMLP

Bases: _BaseGlassNet, _BaseGlassNetViscosity

Multitask neural network for predicting glass properties.

This is the MT-MLP model.

allow_zero_length_dataloader_with_multiple_devices: bool
hparams = {'batch_size': 256, 'layer_1_activation': 'Softplus', 'layer_1_batchnorm': True, 'layer_1_dropout': 0.08118311665886885, 'layer_1_size': 280, 'layer_2_activation': 'Mish', 'layer_2_batchnorm': True, 'layer_2_dropout': 0.0009472891190852595, 'layer_2_size': 500, 'layer_3_activation': 'LeakyReLU', 'layer_3_batchnorm': False, 'layer_3_dropout': 0.08660291424886811, 'layer_3_size': 390, 'layer_4_activation': 'PReLU', 'layer_4_batchnorm': False, 'layer_4_dropout': 0.16775047518280012, 'layer_4_size': 480, 'loss': 'mse', 'lr': 1.3252600209332101e-05, 'max_epochs': 2000, 'n_features': 98, 'n_targets': 85, 'num_layers': 4, 'optimizer': 'AdamW', 'patience': 27}
precision: int | str
prepare_data_per_node: bool
target_trans = {'AbbeNum': 36, 'CTE328K': 64, 'CTE373K': 65, 'CTE433K': 66, 'CTE483K': 67, 'CTE623K': 68, 'CTEbelowTg': 63, 'Cp1073K': 72, 'Cp1273K': 73, 'Cp1473K': 74, 'Cp1673K': 75, 'Cp293K': 69, 'Cp473K': 70, 'Cp673K': 71, 'CrystallizationOnset': 79, 'CrystallizationPeak': 78, 'Density1073K': 57, 'Density1273K': 58, 'Density1473K': 59, 'Density1673K': 60, 'Density293K': 56, 'MaxGrowthVelocity': 77, 'MeanDispersion': 40, 'Microhardness': 54, 'Permittivity': 41, 'PoissonRatio': 55, 'RefractiveIndex': 37, 'RefractiveIndexHigh': 39, 'RefractiveIndexLow': 38, 'Resistivity1073K': 48, 'Resistivity1273K': 49, 'Resistivity1473K': 50, 'Resistivity1673K': 51, 'Resistivity273K': 44, 'Resistivity373K': 45, 'Resistivity423K': 46, 'Resistivity573K': 47, 'ShearModulus': 53, 'SurfaceTension1173K': 81, 'SurfaceTension1473K': 82, 'SurfaceTension1573K': 83, 'SurfaceTension1673K': 84, 'SurfaceTensionAboveTg': 80, 'T0': 0, 'T1': 1, 'T10': 10, 'T11': 11, 'T12': 12, 'T2': 2, 'T3': 3, 'T4': 4, 'T5': 5, 'T6': 6, 'T7': 7, 'T8': 8, 'T9': 9, 'TAnnealing': 32, 'TLittletons': 31, 'TMaxGrowthVelocity': 76, 'TangentOfLossAngle': 42, 'TdilatometricSoftening': 35, 'Tg': 28, 'ThermalConductivity': 61, 'ThermalShockRes': 62, 'Tliquidus': 30, 'Tmelt': 29, 'TresistivityIs1MOhm.m': 43, 'Tsoft': 34, 'Tstrain': 33, 'Viscosity1073K': 16, 'Viscosity1173K': 17, 'Viscosity1273K': 18, 'Viscosity1373K': 19, 'Viscosity1473K': 20, 'Viscosity1573K': 21, 'Viscosity1673K': 22, 'Viscosity1773K': 23, 'Viscosity1873K': 24, 'Viscosity2073K': 25, 'Viscosity2273K': 26, 'Viscosity2473K': 27, 'Viscosity773K': 13, 'Viscosity873K': 14, 'Viscosity973K': 15, 'YoungModulus': 52}
targets = ['T0', 'T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'T8', 'T9', 'T10', 'T11', 'T12', 'Viscosity773K', 'Viscosity873K', 'Viscosity973K', 'Viscosity1073K', 'Viscosity1173K', 'Viscosity1273K', 'Viscosity1373K', 'Viscosity1473K', 'Viscosity1573K', 'Viscosity1673K', 'Viscosity1773K', 'Viscosity1873K', 'Viscosity2073K', 'Viscosity2273K', 'Viscosity2473K', 'Tg', 'Tmelt', 'Tliquidus', 'TLittletons', 'TAnnealing', 'Tstrain', 'Tsoft', 'TdilatometricSoftening', 'AbbeNum', 'RefractiveIndex', 'RefractiveIndexLow', 'RefractiveIndexHigh', 'MeanDispersion', 'Permittivity', 'TangentOfLossAngle', 'TresistivityIs1MOhm.m', 'Resistivity273K', 'Resistivity373K', 'Resistivity423K', 'Resistivity573K', 'Resistivity1073K', 'Resistivity1273K', 'Resistivity1473K', 'Resistivity1673K', 'YoungModulus', 'ShearModulus', 'Microhardness', 'PoissonRatio', 'Density293K', 'Density1073K', 'Density1273K', 'Density1473K', 'Density1673K', 'ThermalConductivity', 'ThermalShockRes', 'CTEbelowTg', 'CTE328K', 'CTE373K', 'CTE433K', 'CTE483K', 'CTE623K', 'Cp293K', 'Cp473K', 'Cp673K', 'Cp1073K', 'Cp1273K', 'Cp1473K', 'Cp1673K', 'TMaxGrowthVelocity', 'MaxGrowthVelocity', 'CrystallizationPeak', 'CrystallizationOnset', 'SurfaceTensionAboveTg', 'SurfaceTension1173K', 'SurfaceTension1473K', 'SurfaceTension1573K', 'SurfaceTension1673K']
training: bool
training_file = PosixPath('/home/daniel/data/Git/Work/glasspy/glasspy/predict/models/GlassNet.p')
class glasspy.predict.GlassNetSTNN(model_name)

Bases: _BaseGlassNet

Single-task neural network for predicting glass properties.

This is the ST-NN model.

allow_zero_length_dataloader_with_multiple_devices: bool
forward(x)

Method used for training the neural network.

Consider using the other methods for prediction.

Parameters:

x – Feature tensor.

Returns

Tensor with the predictions.

hparams = {'batch_size': 256, 'layer_1_activation': 'Softplus', 'layer_1_batchnorm': True, 'layer_1_dropout': 0.08118311665886885, 'layer_1_size': 280, 'layer_2_activation': 'Mish', 'layer_2_batchnorm': True, 'layer_2_dropout': 0.0009472891190852595, 'layer_2_size': 500, 'layer_3_activation': 'LeakyReLU', 'layer_3_batchnorm': False, 'layer_3_dropout': 0.08660291424886811, 'layer_3_size': 390, 'layer_4_activation': 'PReLU', 'layer_4_batchnorm': False, 'layer_4_dropout': 0.16775047518280012, 'layer_4_size': 480, 'loss': 'mse', 'lr': 1.3252600209332101e-05, 'max_epochs': 2000, 'n_features': 98, 'n_targets': 1, 'num_layers': 4, 'optimizer': 'AdamW', 'patience': 27}
precision: int | str
prepare_data_per_node: bool
training: bool
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:
Returns:

Any of.

  • Tensor - The loss tensor

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

  • None - Training will skip to the next batch. This is only for automatic optimization.

    This is not supported for multi-GPU, TPU, IPU, or DeepSpeed.

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

If you define multiple optimizers, this step will be called with an additional optimizer_idx parameter.

# Multiple optimizers (e.g.: GANs)
def training_step(self, batch, batch_idx, optimizer_idx):
    if optimizer_idx == 0:
        # do training_step with encoder
        ...
    if optimizer_idx == 1:
        # do training_step with decoder
        ...

If you add truncated back propagation through time you will also get an additional argument with the hidden states of the previous step.

# Truncated back-propagation through time
def training_step(self, batch, batch_idx, hiddens):
    # hiddens are the hidden states from the previous truncated backprop step
    out, hiddens = self.lstm(data, hiddens)
    loss = ...
    return {"loss": loss, "hiddens": hiddens}

Note

The loss value shown in the progress bar is smoothed (averaged) over the last values, so it differs from the actual loss returned in train/validation 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.

# the pseudocode for these calls
val_outs = []
for val_batch in val_data:
    out = validation_step(val_batch)
    val_outs.append(out)
validation_epoch_end(val_outs)
Parameters:
  • batch – The output of your DataLoader.

  • batch_idx – The index of this batch.

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

Returns:

  • Any object or value

  • None - Validation will skip to the next batch

# pseudocode of order
val_outs = []
for val_batch in val_data:
    out = validation_step(val_batch)
    if defined("validation_step_end"):
        out = validation_step_end(out)
    val_outs.append(out)
val_outs = validation_epoch_end(val_outs)
# 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.
    ...

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 glasspy.predict.ViscNet

Bases: _BaseViscNet

ViscNet predictor of viscosity and viscosity parameters.

ViscNet is a physics-informed neural network that has the MYEGA [1] viscosity equation embedded in it. See Ref. [2] for the original publication.

References

[1] J.C. Mauro, Y. Yue, A.J. Ellison, P.K. Gupta, D.C. Allan, Viscosity of

glass-forming liquids., Proceedings of the National Academy of Sciences of the United States of America. 106 (2009) 19780–19784. https://doi.org/10.1073/pnas.0911705106.

[2] D.R. Cassar, ViscNet: Neural network for predicting the fragility

index and the temperature-dependency of viscosity, Acta Materialia. 206 (2021) 116602. https://doi.org/10.1016/j.actamat.2020.116602. https://arxiv.org/abs/2007.03719

absolute_features = [('ElectronAffinity', 'std1'), ('FusionEnthalpy', 'std1'), ('GSenergy_pa', 'std1'), ('GSmagmom', 'std1'), ('NdUnfilled', 'std1'), ('NfValence', 'std1'), ('NpUnfilled', 'std1'), ('atomic_radius_rahm', 'std1'), ('c6_gb', 'std1'), ('lattice_constant', 'std1'), ('mendeleev_number', 'std1'), ('num_oxistates', 'std1'), ('nvalence', 'std1'), ('vdw_radius_alvarez', 'std1'), ('vdw_radius_uff', 'std1'), ('zeff', 'std1')]
allow_zero_length_dataloader_with_multiple_devices: bool
featurizer(composition: str | List[float] | List[List[float]] | ndarray | Dict[str, float] | Dict[str, List[float]] | Dict[str, ndarray] | DataFrame | ChemArray, input_cols: List[str] = []) ndarray

Compute the chemical features used for viscosity prediction.

Parameters:
  • composition – Any composition like object.

  • input_cols – List of strings representing the chemical entities related to each column of composition. Necessary only when composition is a list or array, ignored otherwise.

Returns:

Array with the computed chemical features

hparams = {'batch_size': 64, 'layer_1_activation': 'ReLU', 'layer_1_batchnorm': False, 'layer_1_dropout': 0.07942161101271952, 'layer_1_size': 192, 'layer_2_activation': 'Tanh', 'layer_2_batchnorm': False, 'layer_2_dropout': 0.05371454289414608, 'layer_2_size': 48, 'loss': 'mse', 'lr': 0.0011695226458761677, 'max_epochs': 500, 'n_features': 35, 'num_layers': 2, 'optimizer': 'AdamW', 'patience': 9}
log_viscosity_fun(T, log_eta_inf, Tg, m)

Computes the base-10 logarithm of viscosity using the MYEGA equation.

parameters_range = {'Tg': [400, 1400], 'log_eta_inf': [-18, 5], 'm': [10, 130]}
precision: int | str
prepare_data_per_node: bool
state_dict_path = PosixPath('/home/daniel/data/Git/Work/glasspy/glasspy/predict/models/ViscNet_SD.p')
training: bool
weighted_features = [('FusionEnthalpy', 'min'), ('GSbandgap', 'max'), ('GSmagmom', 'mean'), ('GSvolume_pa', 'max'), ('MiracleRadius', 'std1'), ('NValence', 'max'), ('NValence', 'min'), ('NdUnfilled', 'max'), ('NdValence', 'max'), ('NsUnfilled', 'max'), ('SpaceGroupNumber', 'max'), ('SpaceGroupNumber', 'min'), ('atomic_radius', 'max'), ('atomic_volume', 'max'), ('c6_gb', 'max'), ('c6_gb', 'min'), ('max_ionenergy', 'min'), ('num_oxistates', 'max'), ('nvalence', 'min')]
x_mean = tensor([5.7542e+01, 2.2090e+01, 2.0236e+00, 3.6861e-02, 3.2621e-01, 1.4419e+00,         2.0165e+00, 3.4408e+01, 1.2353e+03, 1.4793e+00, 4.2045e+01, 8.4131e-01,         2.3045e+00, 4.7985e+01, 5.6984e+01, 1.1146e+00, 9.2186e-02, 2.1363e-01,         2.2581e-04, 5.8150e+00, 1.2964e+01, 3.7008e+00, 1.3743e-01, 1.8370e-02,         3.2303e-01, 7.1325e-02, 5.0019e+01, 4.3720e+00, 3.6446e+01, 8.4037e+00,         2.0281e+02, 7.5614e+00, 1.2259e+02, 6.7183e-01, 1.0508e-01])
x_std = tensor([7.6421e+00, 4.7181e+00, 4.5828e-01, 1.6873e-01, 9.7033e-01, 2.7695e+00,         3.3153e-01, 6.4521e+00, 6.3392e+02, 4.0606e-01, 1.1777e+01, 2.8130e-01,         7.9214e-01, 7.5883e+00, 1.1335e+01, 2.8823e-01, 4.4787e-02, 1.1219e-01,         1.2392e-03, 1.1634e+00, 2.9514e+00, 4.7246e-01, 3.1958e-01, 8.8973e-02,         6.7548e-01, 6.2869e-02, 1.0004e+01, 2.7434e+00, 1.9245e+00, 3.4735e-01,         1.2475e+02, 3.2668e+00, 1.5287e+02, 7.3511e-02, 1.6188e-01])
class glasspy.predict.ViscNetHuber

Bases: ViscNet

ViscNet-Huber predictor of viscosity and viscosity parameters.

ViscNet-Huber is a physics-informed neural network that has the MYEGA [1] viscosity equation embedded in it. The difference between this model and ViscNet is the loss function: this model has a robust smooth-L1 loss function, while ViscNet has a MSE (L2) loss function. See Ref. [2] for the original publication.

References

[1] J.C. Mauro, Y. Yue, A.J. Ellison, P.K. Gupta, D.C. Allan, Viscosity of

glass-forming liquids., Proceedings of the National Academy of Sciences of the United States of America. 106 (2009) 19780–19784. https://doi.org/10.1073/pnas.0911705106.

[2] D.R. Cassar, ViscNet: Neural network for predicting the fragility

index and the temperature-dependency of viscosity, Acta Materialia. 206 (2021) 116602. https://doi.org/10.1016/j.actamat.2020.116602. https://arxiv.org/abs/2007.03719

class glasspy.predict.ViscNetVFT

Bases: ViscNet

ViscNet-VFT predictor of viscosity and viscosity parameters.

ViscNet-VFT is a physics-informed neural network that has the VFT [1-3] viscosity equation embedded in it. See Ref. [4] for the original publication.

References

[1] H. Vogel, Das Temperatureabhängigketsgesetz der Viskosität von

Flüssigkeiten, Physikalische Zeitschrift. 22 (1921) 645–646.

[2] G.S. Fulcher, Analysis of recent measurements of the viscosity of

glasses, Journal of the American Ceramic Society. 8 (1925) 339–355. https://doi.org/10.1111/j.1151-2916.1925.tb16731.x.

[3] G. Tammann, W. Hesse, Die Abhängigkeit der Viscosität von der

Temperatur bie unterkühlten Flüssigkeiten, Z. Anorg. Allg. Chem. 156 (1926) 245–257. https://doi.org/10.1002/zaac.19261560121.

[4] D.R. Cassar, ViscNet: Neural network for predicting the fragility

index and the temperature-dependency of viscosity, Acta Materialia. 206 (2021) 116602. https://doi.org/10.1016/j.actamat.2020.116602. https://arxiv.org/abs/2007.03719

log_viscosity_fun(T, log_eta_inf, Tg, m)

Computes the base-10 logarithm of viscosity using the VFT equation.

Reference:
[1] H. Vogel, Das Temperatureabhängigketsgesetz der Viskosität von

Flüssigkeiten, Physikalische Zeitschrift. 22 (1921) 645–646.

[2] G.S. Fulcher, Analysis of recent measurements of the viscosity of

glasses, Journal of the American Ceramic Society. 8 (1925) 339–355. https://doi.org/10.1111/j.1151-2916.1925.tb16731.x.

[3] G. Tammann, W. Hesse, Die Abhängigkeit der Viscosität von der

Temperatur bie unterkühlten Flüssigkeiten, Z. Anorg. Allg. Chem. 156 (1926) 245–257. https://doi.org/10.1002/zaac.19261560121.