|
| 1 | +from typing import Any |
| 2 | + |
| 3 | +import lightning as L |
| 4 | +import torch |
| 5 | +from torch import nn |
| 6 | + |
| 7 | +from auto_cast.models.encoder_decoder import EncoderDecoder |
| 8 | +from auto_cast.processors.base import Processor |
| 9 | +from auto_cast.types import Batch, RolloutOutput, Tensor |
| 10 | + |
| 11 | + |
| 12 | +class EncoderProcessorDecoder(L.LightningModule): |
| 13 | + """Encoder-Processor-Decoder Model.""" |
| 14 | + |
| 15 | + encoder_decoder: EncoderDecoder |
| 16 | + processor: Processor |
| 17 | + teacher_forcing_ratio: float |
| 18 | + stride: int |
| 19 | + max_rollout_steps: int |
| 20 | + loss_func: nn.Module |
| 21 | + |
| 22 | + def __init__(self): ... |
| 23 | + |
| 24 | + def from_encoder_processor_decoder( |
| 25 | + self, encoder_decoder: EncoderDecoder, processor: Processor |
| 26 | + ) -> None: |
| 27 | + self.encoder_decoder = encoder_decoder |
| 28 | + self.processor = processor |
| 29 | + |
| 30 | + def forward(self, *args: Any, **kwargs: Any) -> Any: |
| 31 | + return self.encoder_decoder.decoder( |
| 32 | + self.processor(self.encoder_decoder.encoder(*args, **kwargs)) |
| 33 | + ) |
| 34 | + |
| 35 | + def training_step(self, batch: Batch, batch_idx: int) -> Tensor: # noqa: ARG002 |
| 36 | + output = self(batch) |
| 37 | + loss = self.processor.loss_func(output, batch.output_fields) |
| 38 | + return loss # noqa: RET504 |
| 39 | + |
| 40 | + def configure_optimizers(self): ... |
| 41 | + |
| 42 | + def rollout(self, batch: Batch) -> RolloutOutput: |
| 43 | + """Rollout over multiple time steps.""" |
| 44 | + pred_outs, gt_outs = [], [] |
| 45 | + for _ in range(0, self.max_rollout_steps, self.stride): |
| 46 | + x = self.encoder_decoder.encoder(batch) |
| 47 | + pred_outs.append(self.processor.map(x)) |
| 48 | + # TODO: combining teacher forcing logic |
| 49 | + gt_outs.append(batch.output_fields) # This assumes we have output fields |
| 50 | + return torch.stack(pred_outs), torch.stack(gt_outs) |
| 51 | + |
| 52 | + |
| 53 | +# TODO: consider if separate rollout class would be better |
| 54 | +class Rollout: |
| 55 | + max_rollout_steps: int |
| 56 | + stride: int |
| 57 | + |
| 58 | + def rollout( |
| 59 | + self, |
| 60 | + batch: Batch, |
| 61 | + model: Processor | EncoderProcessorDecoder, |
| 62 | + ) -> RolloutOutput: |
| 63 | + """Rollout over multiple time steps.""" |
| 64 | + pred_outs, gt_outs = [], [] |
| 65 | + for _ in range(0, self.max_rollout_steps, self.stride): |
| 66 | + output = model(batch) |
| 67 | + pred_outs.append(output) |
| 68 | + # TODO: logic for moving window with teacher forcing that assigns |
| 69 | + gt_outs.append(batch.output_fields) # This assumes we have output fields |
| 70 | + return torch.stack(pred_outs), torch.stack(gt_outs) |
0 commit comments