pyproteonet.imputation.dnn.gnn.heterogeneous.ImputationModule
- class pyproteonet.imputation.dnn.gnn.heterogeneous.ImputationModule(molecule, partner_molecule, mapping, in_dim, layers, lr=0.1, dropout=0.2, gat_heads=10, gat_dim=64, mask_value=-2, num_embeddings: int | None = None, embedding_dim: int | None = 64)
- __init__(molecule, partner_molecule, mapping, in_dim, layers, lr=0.1, dropout=0.2, gat_heads=10, gat_dim=64, mask_value=-2, num_embeddings: int | None = None, embedding_dim: int | None = 64)
Methods
__init__(molecule, partner_molecule, ...[, ...])add_module(name, module)Adds a child module to the current module.
all_gather(data[, group, sync_grads])Gather tensors or collections of tensors from multiple processes.
apply(fn)Applies
fnrecursively to every submodule (as returned by.children()) as well as self.backward(loss, *args, **kwargs)Called to perform backward on the loss returned in
training_step().bfloat16()Casts all floating point parameters and buffers to
bfloat16datatype.buffers([recurse])Returns an iterator over module buffers.
children()Returns an iterator over immediate children modules.
clip_gradients(optimizer[, ...])Handles gradient clipping internally.
compile(*args, **kwargs)Compile this Module's forward using
torch.compile().compute_loss(graph[, partner_loss])configure_callbacks()Configure model-specific callbacks.
configure_gradient_clipping(optimizer[, ...])Perform gradient clipping for the optimizer parameters.
configure_model()Hook to create modules in a strategy and precision aware context.
_summary_
configure_sharded_model()Deprecated.
cpu()See
torch.nn.Module.cpu().cuda([device])Moves all model parameters and buffers to the GPU.
double()See
torch.nn.Module.double().eval()Sets the module in evaluation mode.
extra_repr()Set the extra representation of the module
float()See
torch.nn.Module.float().forward(graph)Same as
torch.nn.Module.forward().freeze()Freeze all params for inference.
get_buffer(target)Returns the buffer given by
targetif it exists, otherwise throws an error.get_extra_state()Returns any extra state to include in the module's state_dict.
get_parameter(target)Returns the parameter given by
targetif it exists, otherwise throws an error.get_submodule(target)Returns the submodule given by
targetif it exists, otherwise throws an error.half()See
torch.nn.Module.half().ipu([device])Moves all model parameters and buffers to the IPU.
load_from_checkpoint(checkpoint_path[, ...])Primary way of loading a model from a checkpoint.
load_state_dict(state_dict[, strict, assign])Copies parameters and buffers from
state_dictinto this module and its descendants.log(name, value[, prog_bar, logger, ...])Log a key, value pair.
log_dict(dictionary[, prog_bar, logger, ...])Log a dictionary of values at once.
lr_scheduler_step(scheduler, metric)Override this method to adjust the default way the
Trainercalls each scheduler.lr_schedulers()Returns the learning rate scheduler(s) that are being used during training.
manual_backward(loss, *args, **kwargs)Call this directly from your
training_step()when doing optimizations manually.modules()Returns an iterator over all modules in the network.
named_buffers([prefix, recurse, ...])Returns an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
named_children()Returns an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
named_modules([memo, prefix, remove_duplicate])Returns an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
named_parameters([prefix, recurse, ...])Returns an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
on_after_backward()Called after
loss.backward()and before optimizers are stepped.on_after_batch_transfer(batch, dataloader_idx)Override to alter or apply batch augmentations to your batch after it is transferred to the device.
on_before_backward(loss)Called before
loss.backward().on_before_batch_transfer(batch, dataloader_idx)Override to alter or apply batch augmentations to your batch before it is transferred to the device.
on_before_optimizer_step(optimizer)Called before
optimizer.step().on_before_zero_grad(optimizer)Called after
training_step()and beforeoptimizer.zero_grad().on_fit_end()Called at the very end of fit.
on_fit_start()Called at the very beginning of fit.
on_load_checkpoint(checkpoint)Called by Lightning to restore your model.
on_predict_batch_end(outputs, batch, batch_idx)Called in the predict loop after the batch.
on_predict_batch_start(batch, batch_idx[, ...])Called in the predict loop before anything happens for that batch.
on_predict_end()Called at the end of predicting.
on_predict_epoch_end()Called at the end of predicting.
on_predict_epoch_start()Called at the beginning of predicting.
on_predict_model_eval()Called when the predict loop starts.
on_predict_start()Called at the beginning of predicting.
on_save_checkpoint(checkpoint)Called by Lightning when saving a checkpoint to give you a chance to store anything else you might want to save.
on_test_batch_end(outputs, batch, batch_idx)Called in the test loop after the batch.
on_test_batch_start(batch, batch_idx[, ...])Called in the test loop before anything happens for that batch.
on_test_end()Called at the end of testing.
on_test_epoch_end()Called in the test loop at the very end of the epoch.
on_test_epoch_start()Called in the test loop at the very beginning of the epoch.
on_test_model_eval()Called when the test loop starts.
on_test_model_train()Called when the test loop ends.
on_test_start()Called at the beginning of testing.
on_train_batch_end(outputs, batch, batch_idx)Called in the training loop after the batch.
on_train_batch_start(batch, batch_idx)Called in the training loop before anything happens for that batch.
on_train_end()Called at the end of training before logger experiment is closed.
on_train_epoch_end()Called in the training loop at the very end of the epoch.
on_train_epoch_start()Called in the training loop at the very beginning of the epoch.
on_train_start()Called at the beginning of training after sanity check.
on_validation_batch_end(outputs, batch, ...)Called in the validation loop after the batch.
on_validation_batch_start(batch, batch_idx)Called in the validation loop before anything happens for that batch.
on_validation_end()Called at the end of validation.
on_validation_epoch_end()Called in the validation loop at the very end of the epoch.
on_validation_epoch_start()Called in the validation loop at the very beginning of the epoch.
on_validation_model_eval()Called when the validation loop starts.
on_validation_model_train()Called when the validation loop ends.
on_validation_model_zero_grad()Called by the training loop to release gradients before entering the validation loop.
on_validation_start()Called at the beginning of validation.
optimizer_step(epoch, batch_idx, optimizer)Override this method to adjust the default way the
Trainercalls the optimizer.optimizer_zero_grad(epoch, batch_idx, optimizer)Override this method to change the default behaviour of
optimizer.zero_grad().optimizers([use_pl_optimizer])Returns the optimizer(s) that are being used during training.
parameters([recurse])Returns an iterator over module parameters.
predict_dataloader()An iterable or collection of iterables specifying prediction samples.
predict_step(graph, batch_idx[, dataloader_idx])Step function called during
predict().prepare_data()Use this to download and prepare data.
print(*args, **kwargs)Prints only from process 0.
register_backward_hook(hook)Registers a backward hook on the module.
register_buffer(name, tensor[, persistent])Adds a buffer to the module.
register_forward_hook(hook, *[, prepend, ...])Registers a forward hook on the module.
register_forward_pre_hook(hook, *[, ...])Registers a forward pre-hook on the module.
register_full_backward_hook(hook[, prepend])Registers a backward hook on the module.
register_full_backward_pre_hook(hook[, prepend])Registers a backward pre-hook on the module.
register_load_state_dict_post_hook(hook)Registers a post hook to be run after module's
load_state_dictis called.register_module(name, module)Alias for
add_module().register_parameter(name, param)Adds a parameter to the module.
register_state_dict_pre_hook(hook)These hooks will be called with arguments:
self,prefix, andkeep_varsbefore callingstate_dictonself.requires_grad_([requires_grad])Change if autograd should record operations on parameters in this module.
save_hyperparameters(*args[, ignore, frame, ...])Save arguments to
hparamsattribute.set_extra_state(state)This function is called from
load_state_dict()to handle any extra state found within the state_dict.setup(stage)Called at the beginning of fit (train + validate), validate, test, or predict.
share_memory()See
torch.Tensor.share_memory_()state_dict(*args[, destination, prefix, ...])Returns a dictionary containing references to the whole state of the module.
teardown(stage)Called at the end of fit (train + validate), validate, test, or predict.
test_dataloader()An iterable or collection of iterables specifying test samples.
test_step(*args, **kwargs)Operates on a single batch of data from the test set.
to(*args, **kwargs)See
torch.nn.Module.to().to_empty(*, device[, recurse])Moves the parameters and buffers to the specified device without copying storage.
to_onnx(file_path[, input_sample])Saves the model in ONNX format.
to_torchscript([file_path, method, ...])By default compiles the whole model to a
ScriptModule.toggle_optimizer(optimizer)Makes sure only the gradients of the current optimizer's parameters are calculated in the training step to prevent dangling gradients in multiple-optimizer setup.
train([mode])Sets the module in training mode.
train_dataloader()An iterable or collection of iterables specifying training samples.
training_step(graph, batch_idx)Here you compute and return the training loss and some additional metrics for e.g. the progress bar or logger.
transfer_batch_to_device(batch, device, ...)Override this hook if your
DataLoaderreturns tensors wrapped in a custom data structure.type(dst_type)See
torch.nn.Module.type().unfreeze()Unfreeze all parameters for training.
untoggle_optimizer(optimizer)Resets the state of required gradients that were toggled with
toggle_optimizer().val_dataloader()An iterable or collection of iterables specifying validation samples.
validation_step(graph, batch_idx)Operates on a single batch of data from the validation set.
xpu([device])Moves all model parameters and buffers to the XPU.
zero_grad([set_to_none])Resets gradients of all model parameters.
Attributes
CHECKPOINT_HYPER_PARAMS_KEYCHECKPOINT_HYPER_PARAMS_NAMECHECKPOINT_HYPER_PARAMS_TYPET_destinationautomatic_optimizationIf set to
Falseyou are responsible for calling.backward(),.step(),.zero_grad().call_super_initcurrent_epochThe current epoch in the
Trainer, or 0 if not attached.devicedtypedump_patchesexample_input_arrayThe example input array is a specification of what the module can consume in the
forward()method.fabricglobal_rankThe index of the current process across all nodes and devices.
global_stepTotal training batches seen across all epochs.
hparamsThe collection of hyperparameters saved with
save_hyperparameters().hparams_initialThe collection of hyperparameters saved with
save_hyperparameters().local_rankThe index of the current process within a single node.
loggerReference to the logger object in the Trainer.
loggersReference to the list of loggers in the Trainer.
on_gpuReturns
Trueif this model is currently located on a GPU.strict_loadingDetermines how Lightning loads this model using .load_state_dict(..., strict=model.strict_loading).
trainertraining- configure_optimizers()
_summary_
- Returns:
_description_
- Return type:
_type_
- forward(graph)
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
- predict_step(graph, batch_idx, dataloader_idx=0)
Step function called during
predict(). By default, it callsforward(). Override to add any processing logic.The
predict_step()is used to scale inference on multi-devices.To prevent an OOM error, it is possible to use
BasePredictionWritercallback to write the predictions to disk or database after each batch or on epoch end.The
BasePredictionWritershould be used while using a spawn based accelerator. This happens forTrainer(strategy="ddp_spawn")or training on 8 TPU cores withTrainer(accelerator="tpu", devices=8)as predictions won’t be returned.- 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:
Predicted output (optional).
Example
class MyModel(LightningModule): def predict_step(self, batch, batch_idx, dataloader_idx=0): return self(batch) dm = ... model = MyModel() trainer = Trainer(accelerator="gpu", devices=2) predictions = trainer.predict(model, dm)
- training_step(graph, 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)
- Returns:
Tensor- The loss tensordict- 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 byaccumulate_grad_batchesinternally.
- validation_step(graph, 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)
- Returns:
Tensor- The loss tensordict- 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. ...
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.