Skip to content

zamba.pytorch_lightning.utils

Attributes

DEFAULT_TOP_K = (1, 3, 5, 10) module-attribute

default_transform = transforms.Compose([ConvertTHWCtoCTHW(), transforms.ConvertImageDtype(torch.float32)]) module-attribute

Classes

ZambaDataModule

Bases: LightningDataModule

Source code in zamba/pytorch_lightning/utils.py
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
class ZambaDataModule(LightningDataModule):
    def __init__(
        self,
        batch_size: int = 1,
        num_workers: int = max(cpu_count() - 1, 1),
        transform: transforms.Compose = default_transform,
        video_loader_config: Optional[VideoLoaderConfig] = None,
        prefetch_factor: int = 2,
        train_metadata: Optional[pd.DataFrame] = None,
        predict_metadata: Optional[pd.DataFrame] = None,
        multiprocessing_context: Optional[str] = "forkserver",
        *args,
        **kwargs,
    ):
        self.batch_size = batch_size
        self.num_workers = num_workers  # Number of parallel processes fetching data
        self.prefetch_factor = prefetch_factor
        self.video_loader_config = (
            None if video_loader_config is None else video_loader_config.dict()
        )

        self.train_metadata = train_metadata
        self.predict_metadata = predict_metadata

        (
            self.train_dataset,
            self.val_dataset,
            self.test_dataset,
            self.predict_dataset,
        ) = get_datasets(
            train_metadata=train_metadata,
            predict_metadata=predict_metadata,
            transform=transform,
            video_loader_config=video_loader_config,
        )
        self.multiprocessing_context: BaseContext = (
            None
            if (multiprocessing_context is None) or (num_workers == 0)
            else multiprocessing_context
        )

        super().__init__(*args, **kwargs)

    def train_dataloader(self) -> Optional[torch.utils.data.DataLoader]:
        if self.train_dataset:
            return torch.utils.data.DataLoader(
                self.train_dataset,
                batch_size=self.batch_size,
                num_workers=self.num_workers,
                shuffle=True,
                multiprocessing_context=self.multiprocessing_context,
                prefetch_factor=self.prefetch_factor,
                persistent_workers=self.num_workers > 0,
            )

    def val_dataloader(self) -> Optional[torch.utils.data.DataLoader]:
        if self.val_dataset:
            return torch.utils.data.DataLoader(
                self.val_dataset,
                batch_size=self.batch_size,
                num_workers=self.num_workers,
                shuffle=False,
                multiprocessing_context=self.multiprocessing_context,
                prefetch_factor=self.prefetch_factor,
                persistent_workers=self.num_workers > 0,
            )

    def test_dataloader(self) -> Optional[torch.utils.data.DataLoader]:
        if self.test_dataset:
            return torch.utils.data.DataLoader(
                self.test_dataset,
                batch_size=self.batch_size,
                num_workers=self.num_workers,
                shuffle=False,
                multiprocessing_context=self.multiprocessing_context,
                prefetch_factor=self.prefetch_factor,
                persistent_workers=self.num_workers > 0,
            )

    def predict_dataloader(self) -> Optional[torch.utils.data.DataLoader]:
        if self.predict_dataset:
            return torch.utils.data.DataLoader(
                self.predict_dataset,
                batch_size=self.batch_size,
                num_workers=self.num_workers,
                shuffle=False,
                multiprocessing_context=self.multiprocessing_context,
                prefetch_factor=self.prefetch_factor,
                persistent_workers=True,
            )

Attributes

batch_size = batch_size instance-attribute
multiprocessing_context: BaseContext = None if multiprocessing_context is None or num_workers == 0 else multiprocessing_context instance-attribute
num_workers = num_workers instance-attribute
predict_metadata = predict_metadata instance-attribute
prefetch_factor = prefetch_factor instance-attribute
train_metadata = train_metadata instance-attribute
video_loader_config = None if video_loader_config is None else video_loader_config.dict() instance-attribute

Functions

__init__(batch_size: int = 1, num_workers: int = max(cpu_count() - 1, 1), transform: transforms.Compose = default_transform, video_loader_config: Optional[VideoLoaderConfig] = None, prefetch_factor: int = 2, train_metadata: Optional[pd.DataFrame] = None, predict_metadata: Optional[pd.DataFrame] = None, multiprocessing_context: Optional[str] = 'forkserver', *args, **kwargs)
Source code in zamba/pytorch_lightning/utils.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def __init__(
    self,
    batch_size: int = 1,
    num_workers: int = max(cpu_count() - 1, 1),
    transform: transforms.Compose = default_transform,
    video_loader_config: Optional[VideoLoaderConfig] = None,
    prefetch_factor: int = 2,
    train_metadata: Optional[pd.DataFrame] = None,
    predict_metadata: Optional[pd.DataFrame] = None,
    multiprocessing_context: Optional[str] = "forkserver",
    *args,
    **kwargs,
):
    self.batch_size = batch_size
    self.num_workers = num_workers  # Number of parallel processes fetching data
    self.prefetch_factor = prefetch_factor
    self.video_loader_config = (
        None if video_loader_config is None else video_loader_config.dict()
    )

    self.train_metadata = train_metadata
    self.predict_metadata = predict_metadata

    (
        self.train_dataset,
        self.val_dataset,
        self.test_dataset,
        self.predict_dataset,
    ) = get_datasets(
        train_metadata=train_metadata,
        predict_metadata=predict_metadata,
        transform=transform,
        video_loader_config=video_loader_config,
    )
    self.multiprocessing_context: BaseContext = (
        None
        if (multiprocessing_context is None) or (num_workers == 0)
        else multiprocessing_context
    )

    super().__init__(*args, **kwargs)
predict_dataloader() -> Optional[torch.utils.data.DataLoader]
Source code in zamba/pytorch_lightning/utils.py
111
112
113
114
115
116
117
118
119
120
121
def predict_dataloader(self) -> Optional[torch.utils.data.DataLoader]:
    if self.predict_dataset:
        return torch.utils.data.DataLoader(
            self.predict_dataset,
            batch_size=self.batch_size,
            num_workers=self.num_workers,
            shuffle=False,
            multiprocessing_context=self.multiprocessing_context,
            prefetch_factor=self.prefetch_factor,
            persistent_workers=True,
        )
test_dataloader() -> Optional[torch.utils.data.DataLoader]
Source code in zamba/pytorch_lightning/utils.py
 99
100
101
102
103
104
105
106
107
108
109
def test_dataloader(self) -> Optional[torch.utils.data.DataLoader]:
    if self.test_dataset:
        return torch.utils.data.DataLoader(
            self.test_dataset,
            batch_size=self.batch_size,
            num_workers=self.num_workers,
            shuffle=False,
            multiprocessing_context=self.multiprocessing_context,
            prefetch_factor=self.prefetch_factor,
            persistent_workers=self.num_workers > 0,
        )
train_dataloader() -> Optional[torch.utils.data.DataLoader]
Source code in zamba/pytorch_lightning/utils.py
75
76
77
78
79
80
81
82
83
84
85
def train_dataloader(self) -> Optional[torch.utils.data.DataLoader]:
    if self.train_dataset:
        return torch.utils.data.DataLoader(
            self.train_dataset,
            batch_size=self.batch_size,
            num_workers=self.num_workers,
            shuffle=True,
            multiprocessing_context=self.multiprocessing_context,
            prefetch_factor=self.prefetch_factor,
            persistent_workers=self.num_workers > 0,
        )
val_dataloader() -> Optional[torch.utils.data.DataLoader]
Source code in zamba/pytorch_lightning/utils.py
87
88
89
90
91
92
93
94
95
96
97
def val_dataloader(self) -> Optional[torch.utils.data.DataLoader]:
    if self.val_dataset:
        return torch.utils.data.DataLoader(
            self.val_dataset,
            batch_size=self.batch_size,
            num_workers=self.num_workers,
            shuffle=False,
            multiprocessing_context=self.multiprocessing_context,
            prefetch_factor=self.prefetch_factor,
            persistent_workers=self.num_workers > 0,
        )

ZambaVideoClassificationLightningModule

Bases: LightningModule

Source code in zamba/pytorch_lightning/utils.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
class ZambaVideoClassificationLightningModule(LightningModule):
    def __init__(
        self,
        species: List[str],
        lr: float = 1e-3,
        scheduler: Optional[str] = None,
        scheduler_params: Optional[dict] = None,
        **kwargs,
    ):
        super().__init__()
        if (scheduler is None) and (scheduler_params is not None):
            warnings.warn(
                "scheduler_params provided without scheduler. scheduler_params will have no effect."
            )

        self.lr = lr
        self.species = species
        self.num_classes = len(species)

        if scheduler is not None:
            self.scheduler = torch.optim.lr_scheduler.__dict__[scheduler]
        else:
            self.scheduler = scheduler

        self.scheduler_params = scheduler_params
        self.model_class = type(self).__name__

        self.save_hyperparameters("lr", "scheduler", "scheduler_params", "species")
        self.hparams["model_class"] = self.model_class

    def forward(self, x):
        return self.model(x)

    def on_train_start(self):
        metrics = {"val_macro_f1": {}}

        if self.num_classes > 2:
            metrics.update(
                {f"val_top_{k}_accuracy": {} for k in DEFAULT_TOP_K if k < self.num_classes}
            )
        else:
            metrics.update({"val_accuracy": {}})

        # write hparams to hparams.yaml file, log metrics to tb hparams tab
        self.logger.log_hyperparams(self.hparams, metrics)

    def training_step(self, batch, batch_idx):
        x, y = batch
        y_hat = self(x)
        loss = F.binary_cross_entropy_with_logits(y_hat, y)
        self.log("train_loss", loss.detach())
        return loss

    def validation_step(self, batch, batch_idx):
        x, y = batch
        y_hat = self(x)
        loss = F.binary_cross_entropy_with_logits(y_hat, y)
        self.log("val_loss", loss.detach())

        y_proba = torch.sigmoid(y_hat.cpu()).numpy()
        return {
            "y_true": y.cpu().numpy().astype(int),
            "y_pred": y_proba.round().astype(int),
            "y_proba": y_proba,
        }

    @staticmethod
    def aggregate_step_outputs(
        outputs: Dict[str, np.ndarray]
    ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
        y_true = np.vstack([output["y_true"] for output in outputs])
        y_pred = np.vstack([output["y_pred"] for output in outputs])
        y_proba = np.vstack([output["y_proba"] for output in outputs])

        return y_true, y_pred, y_proba

    def compute_and_log_metrics(
        self, y_true: np.ndarray, y_pred: np.ndarray, y_proba: np.ndarray, subset: str
    ):
        self.log(f"{subset}_macro_f1", f1_score(y_true, y_pred, average="macro", zero_division=0))

        # if only two classes, skip top_k accuracy since not enough classes
        if self.num_classes > 2:
            for k in DEFAULT_TOP_K:
                if k < self.num_classes:
                    self.log(
                        f"{subset}_top_{k}_accuracy",
                        top_k_accuracy_score(
                            y_true.argmax(
                                axis=1
                            ),  # top k accuracy only supports single label case
                            y_proba,
                            labels=np.arange(y_proba.shape[1]),
                            k=k,
                        ),
                    )
        else:
            self.log(f"{subset}_accuracy", accuracy_score(y_true, y_pred))

        for metric_name, label, metric in compute_species_specific_metrics(
            y_true, y_pred, self.species
        ):
            self.log(f"species/{subset}_{metric_name}/{label}", metric)

    def validation_epoch_end(self, outputs: List[Dict[str, np.ndarray]]):
        """Aggregates validation_step outputs to compute and log the validation macro F1 and top K
        metrics.

        Args:
            outputs (List[dict]): list of output dictionaries from each validation step
                containing y_pred and y_true.
        """
        y_true, y_pred, y_proba = self.aggregate_step_outputs(outputs)
        self.compute_and_log_metrics(y_true, y_pred, y_proba, subset="val")

    def test_step(self, batch, batch_idx):
        return self.validation_step(batch, batch_idx)

    def test_epoch_end(self, outputs: List[Dict[str, np.ndarray]]):
        y_true, y_pred, y_proba = self.aggregate_step_outputs(outputs)
        self.compute_and_log_metrics(y_true, y_pred, y_proba, subset="test")

    def predict_step(self, batch, batch_idx, dataloader_idx: Optional[int] = None):
        x, y = batch
        y_hat = self(x)
        pred = torch.sigmoid(y_hat).cpu().numpy()
        return pred

    def _get_optimizer(self):
        return torch.optim.Adam(filter(lambda p: p.requires_grad, self.parameters()), lr=self.lr)

    def configure_optimizers(self):
        """
        Setup the Adam optimizer. Note, that this function also can return a lr scheduler, which is
        usually useful for training video models.
        """
        optim = self._get_optimizer()

        if self.scheduler is None:
            return optim
        else:
            return {
                "optimizer": optim,
                "lr_scheduler": self.scheduler(
                    optim, **({} if self.scheduler_params is None else self.scheduler_params)
                ),
            }

    def to_disk(self, path: os.PathLike):
        checkpoint = {
            "state_dict": self.state_dict(),
            "hyper_parameters": self.hparams,
        }
        torch.save(checkpoint, path)

    @classmethod
    def from_disk(cls, path: os.PathLike):
        return cls.load_from_checkpoint(path)

Attributes

lr = lr instance-attribute
model_class = type(self).__name__ instance-attribute
num_classes = len(species) instance-attribute
scheduler = torch.optim.lr_scheduler.__dict__[scheduler] instance-attribute
scheduler_params = scheduler_params instance-attribute
species = species instance-attribute

Functions

__init__(species: List[str], lr: float = 0.001, scheduler: Optional[str] = None, scheduler_params: Optional[dict] = None, **kwargs)
Source code in zamba/pytorch_lightning/utils.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def __init__(
    self,
    species: List[str],
    lr: float = 1e-3,
    scheduler: Optional[str] = None,
    scheduler_params: Optional[dict] = None,
    **kwargs,
):
    super().__init__()
    if (scheduler is None) and (scheduler_params is not None):
        warnings.warn(
            "scheduler_params provided without scheduler. scheduler_params will have no effect."
        )

    self.lr = lr
    self.species = species
    self.num_classes = len(species)

    if scheduler is not None:
        self.scheduler = torch.optim.lr_scheduler.__dict__[scheduler]
    else:
        self.scheduler = scheduler

    self.scheduler_params = scheduler_params
    self.model_class = type(self).__name__

    self.save_hyperparameters("lr", "scheduler", "scheduler_params", "species")
    self.hparams["model_class"] = self.model_class
aggregate_step_outputs(outputs: Dict[str, np.ndarray]) -> Tuple[np.ndarray, np.ndarray, np.ndarray] staticmethod
Source code in zamba/pytorch_lightning/utils.py
190
191
192
193
194
195
196
197
198
@staticmethod
def aggregate_step_outputs(
    outputs: Dict[str, np.ndarray]
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    y_true = np.vstack([output["y_true"] for output in outputs])
    y_pred = np.vstack([output["y_pred"] for output in outputs])
    y_proba = np.vstack([output["y_proba"] for output in outputs])

    return y_true, y_pred, y_proba
compute_and_log_metrics(y_true: np.ndarray, y_pred: np.ndarray, y_proba: np.ndarray, subset: str)
Source code in zamba/pytorch_lightning/utils.py
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
def compute_and_log_metrics(
    self, y_true: np.ndarray, y_pred: np.ndarray, y_proba: np.ndarray, subset: str
):
    self.log(f"{subset}_macro_f1", f1_score(y_true, y_pred, average="macro", zero_division=0))

    # if only two classes, skip top_k accuracy since not enough classes
    if self.num_classes > 2:
        for k in DEFAULT_TOP_K:
            if k < self.num_classes:
                self.log(
                    f"{subset}_top_{k}_accuracy",
                    top_k_accuracy_score(
                        y_true.argmax(
                            axis=1
                        ),  # top k accuracy only supports single label case
                        y_proba,
                        labels=np.arange(y_proba.shape[1]),
                        k=k,
                    ),
                )
    else:
        self.log(f"{subset}_accuracy", accuracy_score(y_true, y_pred))

    for metric_name, label, metric in compute_species_specific_metrics(
        y_true, y_pred, self.species
    ):
        self.log(f"species/{subset}_{metric_name}/{label}", metric)
configure_optimizers()

Setup the Adam optimizer. Note, that this function also can return a lr scheduler, which is usually useful for training video models.

Source code in zamba/pytorch_lightning/utils.py
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
def configure_optimizers(self):
    """
    Setup the Adam optimizer. Note, that this function also can return a lr scheduler, which is
    usually useful for training video models.
    """
    optim = self._get_optimizer()

    if self.scheduler is None:
        return optim
    else:
        return {
            "optimizer": optim,
            "lr_scheduler": self.scheduler(
                optim, **({} if self.scheduler_params is None else self.scheduler_params)
            ),
        }
forward(x)
Source code in zamba/pytorch_lightning/utils.py
154
155
def forward(self, x):
    return self.model(x)
from_disk(path: os.PathLike) classmethod
Source code in zamba/pytorch_lightning/utils.py
279
280
281
@classmethod
def from_disk(cls, path: os.PathLike):
    return cls.load_from_checkpoint(path)
on_train_start()
Source code in zamba/pytorch_lightning/utils.py
157
158
159
160
161
162
163
164
165
166
167
168
def on_train_start(self):
    metrics = {"val_macro_f1": {}}

    if self.num_classes > 2:
        metrics.update(
            {f"val_top_{k}_accuracy": {} for k in DEFAULT_TOP_K if k < self.num_classes}
        )
    else:
        metrics.update({"val_accuracy": {}})

    # write hparams to hparams.yaml file, log metrics to tb hparams tab
    self.logger.log_hyperparams(self.hparams, metrics)
predict_step(batch, batch_idx, dataloader_idx: Optional[int] = None)
Source code in zamba/pytorch_lightning/utils.py
246
247
248
249
250
def predict_step(self, batch, batch_idx, dataloader_idx: Optional[int] = None):
    x, y = batch
    y_hat = self(x)
    pred = torch.sigmoid(y_hat).cpu().numpy()
    return pred
test_epoch_end(outputs: List[Dict[str, np.ndarray]])
Source code in zamba/pytorch_lightning/utils.py
242
243
244
def test_epoch_end(self, outputs: List[Dict[str, np.ndarray]]):
    y_true, y_pred, y_proba = self.aggregate_step_outputs(outputs)
    self.compute_and_log_metrics(y_true, y_pred, y_proba, subset="test")
test_step(batch, batch_idx)
Source code in zamba/pytorch_lightning/utils.py
239
240
def test_step(self, batch, batch_idx):
    return self.validation_step(batch, batch_idx)
to_disk(path: os.PathLike)
Source code in zamba/pytorch_lightning/utils.py
272
273
274
275
276
277
def to_disk(self, path: os.PathLike):
    checkpoint = {
        "state_dict": self.state_dict(),
        "hyper_parameters": self.hparams,
    }
    torch.save(checkpoint, path)
training_step(batch, batch_idx)
Source code in zamba/pytorch_lightning/utils.py
170
171
172
173
174
175
def training_step(self, batch, batch_idx):
    x, y = batch
    y_hat = self(x)
    loss = F.binary_cross_entropy_with_logits(y_hat, y)
    self.log("train_loss", loss.detach())
    return loss
validation_epoch_end(outputs: List[Dict[str, np.ndarray]])

Aggregates validation_step outputs to compute and log the validation macro F1 and top K metrics.

Parameters:

Name Type Description Default
outputs List[dict]

list of output dictionaries from each validation step containing y_pred and y_true.

required
Source code in zamba/pytorch_lightning/utils.py
228
229
230
231
232
233
234
235
236
237
def validation_epoch_end(self, outputs: List[Dict[str, np.ndarray]]):
    """Aggregates validation_step outputs to compute and log the validation macro F1 and top K
    metrics.

    Args:
        outputs (List[dict]): list of output dictionaries from each validation step
            containing y_pred and y_true.
    """
    y_true, y_pred, y_proba = self.aggregate_step_outputs(outputs)
    self.compute_and_log_metrics(y_true, y_pred, y_proba, subset="val")
validation_step(batch, batch_idx)
Source code in zamba/pytorch_lightning/utils.py
177
178
179
180
181
182
183
184
185
186
187
188
def validation_step(self, batch, batch_idx):
    x, y = batch
    y_hat = self(x)
    loss = F.binary_cross_entropy_with_logits(y_hat, y)
    self.log("val_loss", loss.detach())

    y_proba = torch.sigmoid(y_hat.cpu()).numpy()
    return {
        "y_true": y.cpu().numpy().astype(int),
        "y_pred": y_proba.round().astype(int),
        "y_proba": y_proba,
    }

Functions