gents.model.diffeq package
Module contents
- class gents.model.diffeq.LS4(seq_len: int, seq_dim: int, latent_dim: int = 10, bidirectional: bool = False, condition: str | None = None, sigma: float = 0.1, enc_hidden_size: int = 64, enc_n_layers: int = 4, enc_backbone: str = 'autoreg', enc_use_unet: bool = False, enc_pool: List[int] = [], enc_ff_layers: int = 2, enc_expand: int = 2, enc_s4type: str = 's4', enc_dropout: float = 0.0, enc_use_latent: bool = True, enc_latent_type: str = 'split', enc_lr: float = 0.001, dec_activation: str = 'identity', dec_hidden_size: int = 64, dec_n_layers: int = 4, dec_backbone: str = 'autoreg', dec_use_unet: bool = False, dec_pool: List[int] = [], dec_ff_layers: int = 2, dec_expand: int = 2, dec_s4type: str = 's4', dec_dropout: float = 0.0, dec_use_latent: bool = False, dec_latent_type: str = 'none', dec_lr: float = 0.001, prior_hidden_size: int = 64, prior_n_layers: int = 4, prior_backbone: str = 'autoreg', prior_use_unet: bool = False, prior_pool: List[int] = [], prior_ff_layers: int = 2, prior_expand: int = 2, prior_s4type: str = 's4', prior_dropout: float = 0.0, prior_use_latent: bool = True, prior_latent_type: str = 'split', prior_lr: float = 0.001, lr: float = 0.001, weight_decay: float = 1e-05, **kwargs)
Bases:
BaseModelDeep Latent State Space Models for Time-Series Generation
Adapted from the official codes
Note
LS4 allows for irregular data. Imputation in LS4 is only interpolation, i.e. only impute the missing steps that all channels are missing.
- Parameters:
seq_len (int) – Target sequence length
seq_dim (int) – Target sequence dimension, for univariate time series, set as 1
condition (str, optional) – Given condition type, should be one of ALLOW_CONDITION. Defaults to None.
latent_dim (int, optional) – Latent dimension. Defaults to 10.
bidirectional (bool, optional) – Whether to be bidirectional. Defaults to False.
sigma (float, optional) – Std of generated data. Seems to be useless Defaults to 0.1.
enc_hidden_size (int, optional) – Encoder hidden size. Defaults to 64.
enc_n_layers (int, optional) – Encoder layers. Defaults to 4.
enc_backbone (str, optional) – Encoder backbone. Choose from [‘autoreg’, ‘seq’]. Defaults to “autoreg”.
enc_use_unet (bool, optional) – If True, encoder will use a unet-like architecture, adding (Residual (S4) –> Residual (FF)) layers before downpooling. All else fixed, this slows down inference (and slightly slows training), but generally improves performance. We use this variant when dropping in SaShiMi into diffusion models, and this should generally be preferred for non-autoregressive models. Defaults to False.
enc_pool (List[int], optional) – Pooling factor at each level. Pooling shrinks the sequence length at lower levels. We experimented with a pooling factor of 4 with 1 to 4 tiers of pooling and found 2 tiers to be best. It’s possible that a different combination of pooling factors and number of tiers may perform better. Defaults to [].
enc_ff_layers (int, optional) – Expansion factor for the FF inverted bottleneck. We generally found 2 to perform best (among 2, 4). Defaults to 2.
enc_expand (int, optional) – Expansion factor when pooling. Features are expanded (i.e. the model becomes wider) at lower levels of the architecture. We generally found 2 to perform best (among 2, 4). Defaults to 2.
enc_s4type (str, optional) – S4 network type for encoder. Choose from [‘s4’, ‘s4d’, ‘s4d_joint’]. Defaults to “s4”.
enc_dropout (float, optional) – Encoder dropout. Defaults to 0.0.
enc_use_latent (bool, optional) – Whether to use latent variables. Defaults to True.
enc_latent_type (str, optional) – If enc_use_latent=True, choose from [‘none’, ‘split’, ‘const_std’, ‘single’, ‘joint’]. Defaults to “split”.
enc_lr (float, optional) – Encoder learning rate. Defaults to 1e-3.
dec_activation (str, optional) – Decoder activation type. Choose from [None, ‘id’, ‘identity’, ‘linear’, ‘tanh’, ‘relu’, ‘gelu’, ‘swish’, ‘silu’, ‘glu’, ‘sigmoid’, ‘modrelu’] Defaults to “identity”.
dec_hidden_size (int, optional) – Decoder hidden size. Defaults to 64.
dec_n_layers (int, optional) – Decoder layers. Defaults to 4.
dec_backbone (str, optional) – Decoder backbone. Choose from [‘autoreg’, ‘seq’]. Defaults to “autoreg”.
dec_use_unet (bool, optional) – If True, encoder will use a unet-like architecture, adding (Residual (S4) –> Residual (FF)) layers before downpooling. All else fixed, this slows down inference (and slightly slows training), but generally improves performance. We use this variant when dropping in SaShiMi into diffusion models, and this should generally be preferred for non-autoregressive models. Defaults to False.
dec_pool (List[int], optional) – Pooling factor at each level. Pooling shrinks the sequence length at lower levels. We experimented with a pooling factor of 4 with 1 to 4 tiers of pooling and found 2 tiers to be best. It’s possible that a different combination of pooling factors and number of tiers may perform better. Defaults to [].
dec_ff_layers (int, optional) – Expansion factor for the FF inverted bottleneck. We generally found 2 to perform best (among 2, 4). Defaults to 2.
dec_expand (int, optional) – Expansion factor when pooling. Features are expanded (i.e. the model becomes wider) at lower levels of the architecture. We generally found 2 to perform best (among 2, 4). Defaults to 2.
dec_s4type (str, optional) – S4 network type for encoder. Choose from [‘s4’, ‘s4d’, ‘s4d_joint’]. Defaults to “s4”.
dec_dropout (float, optional) – Decoder dropout. Defaults to 0.0.
dec_use_latent (bool, optional) – Whether to use latent variable. Defaults to False.
dec_latent_type (str, optional) – If enc_use_latent=True, choose from [‘none’, ‘split’, ‘const_std’, ‘single’, ‘joint’]. Defaults to “none”.
dec_lr (float, optional) – Decoder learning rate. Defaults to 1e-3.
prior_hidden_size (int, optional) – Prior net hidden size. Defaults to 64.
prior_n_layers (int, optional) – Prior net layers. Defaults to 4.
prior_backbone (str, optional) – Prior net backbone. Choose from [‘autoreg’, ‘seq’]. Defaults to “autoreg”.
prior_use_unet (bool, optional) – If True, encoder will use a unet-like architecture, adding (Residual (S4) –> Residual (FF)) layers before downpooling. All else fixed, this slows down inference (and slightly slows training), but generally improves performance. We use this variant when dropping in SaShiMi into diffusion models, and this should generally be preferred for non-autoregressive models. Defaults to False.
prior_pool (List[int], optional) – Pooling factor at each level. Pooling shrinks the sequence length at lower levels. We experimented with a pooling factor of 4 with 1 to 4 tiers of pooling and found 2 tiers to be best. It’s possible that a different combination of pooling factors and number of tiers may perform better. Defaults to [].
prior_ff_layers (int, optional) – Expansion factor for the FF inverted bottleneck. We generally found 2 to perform best (among 2, 4). Defaults to 2.
prior_expand (int, optional) – Expansion factor when pooling. Features are expanded (i.e. the model becomes wider) at lower levels of the architecture. We generally found 2 to perform best (among 2, 4). Defaults to 2.
prior_s4type (str, optional) – S4 network type for encoder. Choose from [‘s4’, ‘s4d’, ‘s4d_joint’]. Defaults to “s4”.
prior_dropout (float, optional) – Prior net dropout rate. Defaults to 0.0.
prior_use_latent (bool, optional) – Whether to use latent variable.. Defaults to True.
prior_latent_type (str, optional) – If enc_use_latent=True, choose from [‘none’, ‘split’, ‘const_std’, ‘single’, ‘joint’]. Defaults to “split”.
prior_lr (float, optional) – Prior net learning rate. Defaults to 1e-3.
lr (float, optional) – Learning rate for other parameters. Defaults to 1e-3.
weight_decay (float, optional) – Weight decay. Defaults to 1e-5.
**kwargs – Arbitrary keyword arguments, e.g. obs_len, class_num, etc.
- ALLOW_CONDITION = [None, 'predict', 'impute']
- 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. Optimization with multiple optimizers only works in the manual optimization mode.
- 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 orlr_scheduler_config.None - Fit will run without any optimizer.
The
lr_scheduler_configis 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 thetorch.optim.lr_scheduler.ReduceLROnPlateauscheduler, Lightning requires that thelr_scheduler_configcontains the keyword"monitor"set to the metric name that the scheduler should be conditioned on.# The ReduceLROnPlateau scheduler requires a monitor def configure_optimizers(self): optimizer = Adam(...) return { "optimizer": optimizer, "lr_scheduler": { "scheduler": ReduceLROnPlateau(optimizer, ...), "monitor": "metric_to_track", "frequency": "indicates how often the metric is updated", # If "monitor" references validation metrics, then "frequency" should be set to a # multiple of "trainer.check_val_every_n_epoch". }, } # In the case of two optimizers, only one using the ReduceLROnPlateau scheduler def configure_optimizers(self): optimizer1 = Adam(...) optimizer2 = SGD(...) scheduler1 = ReduceLROnPlateau(optimizer1, ...) scheduler2 = LambdaLR(optimizer2, ...) return ( { "optimizer": optimizer1, "lr_scheduler": { "scheduler": scheduler1, "monitor": "metric_to_track", }, }, {"optimizer": optimizer2, "lr_scheduler": scheduler2}, )
Metrics can be made available to monitor by simply logging it using
self.log('metric_to_track', metric_val)in yourLightningModule.Note
Some things to know:
Lightning calls
.backward()and.step()automatically in case of automatic optimization.If a 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 optimizer.If you use
torch.optim.LBFGS, Lightning handles the closure function automatically for you.If you use multiple optimizers, you will have to switch to ‘manual optimization’ mode and step them yourself.
If you need to control how often the optimizer steps, override the
optimizer_step()hook.
- training_step(batch, batch_idx)
Here you compute and return the training loss and some additional metrics for e.g. the progress bar or logger.
- Parameters:
batch – The output of your data iterable, normally a
DataLoader.batch_idx – The index of this batch.
dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)
- 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(batch, batch_idx)
Operates on a single batch of data from the validation set. In this step you’d might generate examples or calculate anything of interest like accuracy.
- Parameters:
batch – The output of your data iterable, normally a
DataLoader.batch_idx – The index of this batch.
dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)
- 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.
- class gents.model.diffeq.LatentODE(seq_len: int, seq_dim: int, condition: str | None = None, latent_dim: int = 6, z0_encoder: str = 'odernn', rec_layers: int = 1, rec_dim: int = 20, gen_layers: int = 1, d_model: int = 32, obsrv_std: float = 0.01, poisson: bool = False, lr: float = 0.001, weight_decay: float = 1e-05, **kwargs)
Bases:
BaseModelLatent ODEs for Irregularly-Sampled Time Series
Adapted from the official codes
Note
LatentODE allows for irregular data. Imputation in Latent ODE is only interpolation, i.e. only impute the missing steps that all channels are missing.
- Parameters:
seq_len (int) – Target sequence length
seq_dim (int) – Target sequence dimension, for univariate time series, set as 1
condition (str, optional) – Given condition type, should be one of ALLOW_CONDITION. Defaults to None.
latent_dim (int, optional) – Latent variable dimension. Defaults to 6.
z0_encoder (str, optional) – Type of encoder. Choose from [‘odernn’,’rnn] Defaults to “odernn”.
rec_layers (int, optional) – Number of encoding (recognition) layers. Defaults to 1.
rec_dim (int, optional) – Number of encoding (recognition) layer size. Defaults to 20.
gen_layers (int, optional) – Number of generation layers. Defaults to 1.
d_model (int, optional) – Model size. Defaults to 32.
obsrv_std (float, optional) – Std of Gaussian distribution for observed data. Used for computing likelihood loss. Defaults to 0.01.
poisson (bool, optional) – Whether to use poisson distribution. Defaults to False.
lr (float, optional) – Learning rate. Defaults to 1e-3.
weight_decay (float, optional) – Weight decay. Defaults to 1e-5.
**kwargs – Arbitrary keyword arguments, e.g. obs_len, class_num, etc.
- ALLOW_CONDITION = [None, 'impute', 'predict']
- 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. Optimization with multiple optimizers only works in the manual optimization mode.
- 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 orlr_scheduler_config.None - Fit will run without any optimizer.
The
lr_scheduler_configis 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 thetorch.optim.lr_scheduler.ReduceLROnPlateauscheduler, Lightning requires that thelr_scheduler_configcontains the keyword"monitor"set to the metric name that the scheduler should be conditioned on.# The ReduceLROnPlateau scheduler requires a monitor def configure_optimizers(self): optimizer = Adam(...) return { "optimizer": optimizer, "lr_scheduler": { "scheduler": ReduceLROnPlateau(optimizer, ...), "monitor": "metric_to_track", "frequency": "indicates how often the metric is updated", # If "monitor" references validation metrics, then "frequency" should be set to a # multiple of "trainer.check_val_every_n_epoch". }, } # In the case of two optimizers, only one using the ReduceLROnPlateau scheduler def configure_optimizers(self): optimizer1 = Adam(...) optimizer2 = SGD(...) scheduler1 = ReduceLROnPlateau(optimizer1, ...) scheduler2 = LambdaLR(optimizer2, ...) return ( { "optimizer": optimizer1, "lr_scheduler": { "scheduler": scheduler1, "monitor": "metric_to_track", }, }, {"optimizer": optimizer2, "lr_scheduler": scheduler2}, )
Metrics can be made available to monitor by simply logging it using
self.log('metric_to_track', metric_val)in yourLightningModule.Note
Some things to know:
Lightning calls
.backward()and.step()automatically in case of automatic optimization.If a 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 optimizer.If you use
torch.optim.LBFGS, Lightning handles the closure function automatically for you.If you use multiple optimizers, you will have to switch to ‘manual optimization’ mode and step them yourself.
If you need to control how often the optimizer steps, override the
optimizer_step()hook.
- on_train_batch_start(batch, batch_idx)
Called in the training loop before anything happens for that batch.
If you return -1 here, you will skip training for the rest of the current epoch.
- Parameters:
batch – The batched data as it is returned by the training DataLoader.
batch_idx – the index of the batch
- training_step(batch, batch_idx)
Here you compute and return the training loss and some additional metrics for e.g. the progress bar or logger.
- Parameters:
batch – The output of your data iterable, normally a
DataLoader.batch_idx – The index of this batch.
dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)
- 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(batch, batch_idx)
Operates on a single batch of data from the validation set. In this step you’d might generate examples or calculate anything of interest like accuracy.
- Parameters:
batch – The output of your data iterable, normally a
DataLoader.batch_idx – The index of this batch.
dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)
- 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.
- class gents.model.diffeq.LatentSDE(seq_len: int, seq_dim: int, condition: str | None = None, latent_size: int = 8, context_size: int = 64, hidden_size: int = 128, noise_std: float = 0.01, solver: str = 'euler', adjoint: bool = False, kl_anneal_iters: int = 1000, lr_gamma: float = 0.997, lr: float = 0.001, weight_decay: float = 1e-06, **kwargs)
Bases:
BaseModelAdapted from the official codes
- Parameters:
seq_len (int) – Target sequence length
seq_dim (int) – Target sequence dimension, for univariate time series, set as 1
condition (str, optional) – Given condition type, should be one of ALLOW_CONDITION. Defaults to None.
latent_size (int, optional) – Latent variable dimension. Defaults to 4.
context_size (int, optional) – Embedding size for encoding input data. Defaults to 64.
hidden_size (int, optional) – Encoder hidden size. Defaults to 128.
noise_std (float, optional) – Std of Gaussian distribution for observed data. Used for computing likelihood loss. Defaults to 1e-2.
solver (str, optional) – SDE solver. Choose from [‘euler’, ‘milstein’, ‘srk’, ‘midpoint’, ‘reversible_heun’, ‘adjoint_reversible_heun’, ‘heun’, ‘log_ode’, ‘euler_heun’] Defaults to “euler”.
adjoint (bool, optional) – If True, use adjoint backward to save memory. Defaults to False.
kl_anneal_iters (int, optional) – Iterations that KL loss weight takes to decay. Defaults to 1000.
lr_gamma (float, optional) – Learning rate schedule. Defaults to 0.997.
lr (float, optional) – Learning rate. Defaults to 1e-2.
weight_decay (float, optional) – Weight decay. Defaults to 1e-6.
**kwargs – Arbitrary keyword arguments, e.g. obs_len, class_num, etc.
- ALLOW_CONDITION = [None]
- 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. Optimization with multiple optimizers only works in the manual optimization mode.
- 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 orlr_scheduler_config.None - Fit will run without any optimizer.
The
lr_scheduler_configis 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 thetorch.optim.lr_scheduler.ReduceLROnPlateauscheduler, Lightning requires that thelr_scheduler_configcontains the keyword"monitor"set to the metric name that the scheduler should be conditioned on.# The ReduceLROnPlateau scheduler requires a monitor def configure_optimizers(self): optimizer = Adam(...) return { "optimizer": optimizer, "lr_scheduler": { "scheduler": ReduceLROnPlateau(optimizer, ...), "monitor": "metric_to_track", "frequency": "indicates how often the metric is updated", # If "monitor" references validation metrics, then "frequency" should be set to a # multiple of "trainer.check_val_every_n_epoch". }, } # In the case of two optimizers, only one using the ReduceLROnPlateau scheduler def configure_optimizers(self): optimizer1 = Adam(...) optimizer2 = SGD(...) scheduler1 = ReduceLROnPlateau(optimizer1, ...) scheduler2 = LambdaLR(optimizer2, ...) return ( { "optimizer": optimizer1, "lr_scheduler": { "scheduler": scheduler1, "monitor": "metric_to_track", }, }, {"optimizer": optimizer2, "lr_scheduler": scheduler2}, )
Metrics can be made available to monitor by simply logging it using
self.log('metric_to_track', metric_val)in yourLightningModule.Note
Some things to know:
Lightning calls
.backward()and.step()automatically in case of automatic optimization.If a 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 optimizer.If you use
torch.optim.LBFGS, Lightning handles the closure function automatically for you.If you use multiple optimizers, you will have to switch to ‘manual optimization’ mode and step them yourself.
If you need to control how often the optimizer steps, override the
optimizer_step()hook.
- training_step(batch, batch_idx)
Here you compute and return the training loss and some additional metrics for e.g. the progress bar or logger.
- Parameters:
batch – The output of your data iterable, normally a
DataLoader.batch_idx – The index of this batch.
dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)
- 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(batch, batch_idx)
Operates on a single batch of data from the validation set. In this step you’d might generate examples or calculate anything of interest like accuracy.
- Parameters:
batch – The output of your data iterable, normally a
DataLoader.batch_idx – The index of this batch.
dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)
- 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.
- class gents.model.diffeq.SDEGAN(seq_len: int, seq_dim: int, condition: str | None = None, initial_noise_size: int = 5, noise_size: int = 3, hidden_size: int = 16, d_model: int = 16, n_layers: int = 1, init_mult1: float = 3, init_mult2: float = 0.5, swa_step_start: int = 5000, lr: Dict[str, float] = {'D': 0.001, 'G': 0.0002}, weight_decay: float = 0.01, **kwargs)
Bases:
BaseModelNeural SDEs as Infinite-Dimensional GANs
Adapted from the official codes
Note
SDEGAN allows for irregular data.
- Parameters:
seq_len (int) – Target sequence length
seq_dim (int) – Target sequence dimension, for univariate time series, set as 1
condition (str, optional) – Given condition type, should be one of ALLOW_CONDITION. Defaults to None.
initial_noise_size (int, optional) – Gaussian distribution dimension that used for sampling. Defaults to 5.
noise_size (int, optional) – Diffusion size for SDE. Defaults to 3.
hidden_size (int, optional) – latent SDE size. Defaults to 16.
d_model (int, optional) – MLP size. Defaults to 16.
n_layers (int, optional) – MLP layers. Defaults to 1.
init_mult1 (float, optional) – Scale ratio for Generator’s encoder initial parameter. Defaults to 3.
init_mult2 (float, optional) – Scale ratio for Generator’s neural SDE initial parameter. Defaults to 0.5.
swa_step_start (int, optional) – Start step for stochastic weight average (SWA) of model parameters. Defaults to 5000.
lr (Dict[str, float], optional) – Learning rate for different networks. G: generator, D: discriminator.. Defaults to {“G”: 2e-4, “D”: 1e-3}.
weight_decay (float, optional) – Weight decay. Defaults to 0.01.
**kwargs – Arbitrary keyword arguments, e.g. obs_len, class_num, etc.
- ALLOW_CONDITION = [None]
- 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. Optimization with multiple optimizers only works in the manual optimization mode.
- 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 orlr_scheduler_config.None - Fit will run without any optimizer.
The
lr_scheduler_configis 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 thetorch.optim.lr_scheduler.ReduceLROnPlateauscheduler, Lightning requires that thelr_scheduler_configcontains the keyword"monitor"set to the metric name that the scheduler should be conditioned on.# The ReduceLROnPlateau scheduler requires a monitor def configure_optimizers(self): optimizer = Adam(...) return { "optimizer": optimizer, "lr_scheduler": { "scheduler": ReduceLROnPlateau(optimizer, ...), "monitor": "metric_to_track", "frequency": "indicates how often the metric is updated", # If "monitor" references validation metrics, then "frequency" should be set to a # multiple of "trainer.check_val_every_n_epoch". }, } # In the case of two optimizers, only one using the ReduceLROnPlateau scheduler def configure_optimizers(self): optimizer1 = Adam(...) optimizer2 = SGD(...) scheduler1 = ReduceLROnPlateau(optimizer1, ...) scheduler2 = LambdaLR(optimizer2, ...) return ( { "optimizer": optimizer1, "lr_scheduler": { "scheduler": scheduler1, "monitor": "metric_to_track", }, }, {"optimizer": optimizer2, "lr_scheduler": scheduler2}, )
Metrics can be made available to monitor by simply logging it using
self.log('metric_to_track', metric_val)in yourLightningModule.Note
Some things to know:
Lightning calls
.backward()and.step()automatically in case of automatic optimization.If a 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 optimizer.If you use
torch.optim.LBFGS, Lightning handles the closure function automatically for you.If you use multiple optimizers, you will have to switch to ‘manual optimization’ mode and step them yourself.
If you need to control how often the optimizer steps, override the
optimizer_step()hook.
- on_fit_end()
Called at the very end of fit.
If on DDP it is called on every process
- training_step(batch, batch_idx)
Here you compute and return the training loss and some additional metrics for e.g. the progress bar or logger.
- Parameters:
batch – The output of your data iterable, normally a
DataLoader.batch_idx – The index of this batch.
dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)
- 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(batch, batch_idx)
Operates on a single batch of data from the validation set. In this step you’d might generate examples or calculate anything of interest like accuracy.
- Parameters:
batch – The output of your data iterable, normally a
DataLoader.batch_idx – The index of this batch.
dataloader_idx – The index of the dataloader that produced this batch. (only if multiple dataloaders used)
- 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.