Add a processor¶
A processor sits between the encoders and decoder in the encode-process-decode pipeline. It receives the concatenated latent representations of all inputs and produces a latent forecast.
The processor interface¶
All CryoCast processors extend BaseProcessor from cryocast.models.processors.
They operate on tensors in NTCHW format, taking in a tensor with a number of history steps and returning a tensor with a number of forecast steps.
For example, with 3 history steps, and 4 forecast steps, a processor will convert a tensor of shape (N, 3, C, H, W) to (N, 4, C, H, W)
The base class exposes two entry points, and you only need to implement one:
| Method | Signature | When to override |
|---|---|---|
forward |
(x: TensorNCHW) -> TensorNCHW |
Stateless single-timestep transforms |
rollout |
(x: TensorNTCHW, y: TensorNTCHW \| None) -> ProcessorOutput |
Any model that needs access to the full temporal history, or that behaves differently during training vs. inference |
The default rollout implementation calls forward once per forecast step, passing each prediction back as the next input.
If your architecture works on one timestep at a time and uses the same logic during training and inference, only overriding forward is sufficient.
Simple processor: override forward¶
from typing import Any
from cryocast.models.processors import BaseProcessor
from cryocast.types import TensorNCHW
class MyProcessor(BaseProcessor):
def __init__(self, *, hidden_dim: int = 128, **kwargs: Any) -> None:
super().__init__(**kwargs)
in_channels = self.data_space.channels
self.model = ... # your nn.Module here
def forward(self, x: TensorNCHW) -> TensorNCHW:
return self.model(x)
This model can be trained in either single-stage or multistage mode.
Training vs. inference: override rollout¶
Some processors do different operations during training and during inference. A diffusion model is an example of this type of processor. During training, it adds noise to the ground truth and predicts that noise. During inference, it starts from random noise and removes the noise step by step.
These processors can be trained in single-stage or multistage mode. In single-stage training, the reconstruction loss and the prediction loss train the encoders and the decoder together with the processor. You must enable at least one of them, see Loss in latent space. In multistage training, CryoCast trains the encoders and the decoder before the processor. CryoCast then trains the processor on a fixed latent space.
The rollout method gets two tensors:
xcontains the encoded inputs for the history steps. Its shape is(N, T_history, C, H, W).ycontains the encoded inputs for the forecast steps. Its shape is(N, T_forecast, C, H, W).
x and y are in the same latent space.
They have the same channels C, in the same sequence.
y contains all the input groups, not only the target group.
Thus, the processor does not have to find the target channels in the latent space.
The value of y tells the processor which step is in progress:
- If
yis a tensor, the step is training. - If
yisNone, the step is inference.
The model gives y to rollout only if the processor sets computes_loss_in_latent_space=True.
For all other processors, y is always None.
from typing import Any
from cryocast.models.processors import BaseProcessor
from cryocast.types import ProcessorOutput, TensorNTCHW
class MyDiffusionProcessor(BaseProcessor):
def __init__(self, **kwargs: Any) -> None:
super().__init__(computes_loss_in_latent_space=True, **kwargs)
def rollout(self, x: TensorNTCHW, y: TensorNTCHW | None = None) -> ProcessorOutput:
# x: (N, T_history, C, H, W) - encoded inputs for the history steps
# y: (N, T_forecast, C, H, W) - encoded inputs for the forecast steps
if y is not None:
# Training: calculate a custom loss and return it with the prediction.
prediction, loss = self._training(x, y)
return ProcessorOutput(prediction=prediction, loss=loss)
# Inference: no loss is necessary.
return ProcessorOutput(prediction=self._inference(x))
Loss in latent space¶
By default, the model decodes the prediction from rollout and calculates the loss against the target.
The model ignores the loss field of ProcessorOutput.
To use your own loss, give computes_loss_in_latent_space=True to BaseProcessor.__init__.
During training, rollout must then set loss on the ProcessorOutput that it returns.
If loss is None, the model raises a ValueError.
The model uses this loss for the backward pass.
It decodes the prediction under torch.no_grad().
Thus, the decoder makes output for the metrics and the callbacks, but this output does not change the gradients.
CryoCast also does these steps automatically:
- The data module loads each input group for the forecast steps.
Each batch gets one
future_<input>key for each input group. - The model encodes these inputs and gives the result to
rolloutasy. The model detachesyfrom the computation graph. Thus, the loss cannot change its own target. - If the weight
loss_weights.reconstructionis greater than0(default0), the model decodes the encoded inputs and compares them to the target. This reconstruction loss trains the encoders and the decoder, because the latent loss does not go through the decoder. The model adds it to the latent loss, with the weightloss_weights.reconstruction. The model logs the two parts astrain_latent_lossandtrain_reconstruction_loss.
You do not set a configuration key for steps 1 and 2. To enable the reconstruction loss, set its weight at the top level of the model config:
The weight must not be negative.
If the weight is 0, the model does not calculate the reconstruction loss.
If the weight is 0 and the encoders or the decoder are trainable, the model logs a warning.
Without the reconstruction loss, the latent space can drift away from what the decoder expects.
Prediction loss¶
During training, the prediction from rollout can have gradients back to the processor.
For example, a diffusion processor returns its estimate of the clean latent x_0.
The prediction can also have fewer forecast steps than n_forecast_steps.
For example, an autoregressive diffusion processor predicts only the first forecast step.
The processor can also set sample_mask on the ProcessorOutput.
This is a boolean mask with one value for each sample.
For DiffusionProcessor, it is True for the samples whose diffusion timestep is below prediction_loss_cutoff (default 0.5) of timesteps.
If the weight loss_weights.prediction is greater than 0 (default 0), the model does these steps:
- It decodes
predictionand compares it to the target. It compares only the forecast steps in the prediction. - It uses only the samples in
sample_mask. Ifsample_maskisNone, it uses all the samples. For a diffusion processor, these are the samples with a low timestep: at high timesteps, the x_0 estimate is mostly noise. If no sample is in the mask, this loss is0. - It adds this loss to the total loss, with the weight
loss_weights.prediction. It logs this loss astrain_prediction_loss.
This loss trains the processor, the decoder and the encoders against the target in physical space.
The weight must not be negative.
If the prediction has no gradients during training, training raises a ValueError.
loss_weights:
reconstruction: 1.0
prediction: 0.5
processor:
_target_: cryocast.models.processors.DiffusionProcessor
timesteps: 250
The model freezes the decoder only if both weights are 0.
In this case, the training loss does not use the decoder.
Warning
The future_<input> keys contain ground-truth data for the forecast steps.
The model uses them only to calculate the training loss.
The model does not give them to forward.
Do not use them in a different part of the model.
Note
The data module reads more data for each sample when it loads the forecast steps. It loads them only for the processor and finetune stages, because the encoder and decoder stages do not use them. A sample is valid only if all the input groups have data for all the forecast steps. Thus, the dataset can contain fewer samples. For example, the Argo data has some missing dates.
Note
The loss is calculated on all the channels of the latent space, with the same weight for each channel. Most of these channels come from input groups that are not the target, for example ERA5.
Register the processor in config¶
Add a model config under cryocast/config/model/ that points processor._target_ at your class:
# cryocast/config/model/cnn_mydiffusion_cnn.yaml
_target_: cryocast.models.EncodeProcessDecode
name: cnn-ddpm-cnn
encoders:
latent_space: [144, 144]
era5:
_target_: cryocast.models.encoders.CNNEncoder
sic-osisaf:
_target_: cryocast.models.encoders.CNNEncoder
processor:
_target_: cryocast.models.processors.MyDiffusionProcessor
timesteps: 1000
decoder:
_target_: cryocast.models.decoders.CNNDecoder
bounded: false
Then run training with: