| |
| import torch |
| import torch.nn as nn |
| import torch.nn.functional as F |
| from abc import ABC |
| from lightning.pytorch import LightningModule |
| from torchmetrics import MetricCollection, Accuracy |
|
|
| from marble.modules.ema import LitEma |
|
|
|
|
| class BaseTask(LightningModule, ABC): |
| """ |
| Base Task class to encapsulate encoder-decoder models with: |
| - support for multiple embedding transforms |
| - multiple decoders (multiβhead) |
| - multiple loss functions |
| - splitβspecific MetricCollections |
| - optional EMA on encoder weights |
| """ |
|
|
| def __init__( |
| self, |
| *, |
| encoder: nn.Module, |
| emb_transforms: list[nn.Module] | None = None, |
| decoders: list[nn.Module] | None = None, |
| losses: list[nn.Module] | None = None, |
| metrics: dict[str, dict[str, nn.Module]] | None = None, |
| sample_rate: int | None = None, |
| use_ema: bool = False, |
| **kwargs, |
| ): |
| super().__init__() |
| |
| self.save_hyperparameters(ignore=['encoder', 'emb_transforms', 'decoders', 'losses', 'metrics']) |
|
|
| |
| self.encoder = encoder |
| self.emb_transforms = nn.ModuleList(emb_transforms or []) |
| self.decoders = nn.ModuleList(decoders or []) |
| self.loss_fns = nn.ModuleList(losses or []) |
|
|
| |
| self.use_ema = use_ema |
| if self.use_ema: |
| self.ema = LitEma(self.encoder) |
|
|
| |
| if metrics: |
| for split in ('train', 'val', 'test'): |
| split_cfg = metrics.get(split) |
| if split_cfg: |
| mc = MetricCollection( |
| {name: m for name, m in split_cfg.items()}, |
| prefix=f"{split}/" |
| ) |
| setattr(self, f"{split}_metrics", mc) |
|
|
| def forward(self, x: torch.Tensor) -> torch.Tensor | list[torch.Tensor]: |
| """ |
| Default forward: encoder β transforms β each decoder head. |
| Returns single Tensor if only one head, else list of Tensors. |
| """ |
| h = self.encoder(x) |
| for t in self.emb_transforms: |
| h = t(h) |
| outputs = [dec(h) for dec in self.decoders] |
| return outputs[0] if len(outputs) == 1 else outputs |
|
|
| def _shared_step(self, batch, batch_idx: int, split: str) -> torch.Tensor: |
| """ |
| Common logic for train/val: |
| - unpack batch |
| - forward |
| - sum all loss_fns |
| - log loss and metrics |
| """ |
| x, y, uids_or_paths = batch |
| logits = self(x) |
|
|
| |
| losses = [fn(logits, y) for fn in self.loss_fns] |
| loss = sum(losses) |
| self.log(f"{split}/loss", loss, prog_bar=True, on_step=False, on_epoch=True, sync_dist=True) |
|
|
| |
| mc: MetricCollection = getattr(self, f"{split}_metrics", None) |
| if mc is not None: |
| metrics_out = mc(logits, y) |
| self.log_dict(metrics_out, prog_bar=(split == "val"), on_step=False, on_epoch=True, sync_dist=True) |
|
|
| return loss |
|
|
| def training_step(self, batch, batch_idx: int) -> torch.Tensor: |
| loss = self._shared_step(batch, batch_idx, "train") |
| return loss |
|
|
| def validation_step(self, batch, batch_idx: int): |
| self._shared_step(batch, batch_idx, "val") |
|
|
| def on_train_batch_end(self, outputs, batch, batch_idx, unused=0) -> None: |
| if self.use_ema: |
| self.ema.update() |
|
|
| def test_step(self, batch, batch_idx: int): |
| """ |
| Default test: returns raw logits and labels for aggregation. |
| Override in subclass for custom behavior. |
| """ |
| x, y = batch[:2] |
| logits = self(x) |
| return {"logits": logits, "labels": y} |
|
|
| def configure_optimizers(self): |
| |
| return super().configure_optimizers() |
|
|
|
|
| class BaseFewShotTask(LightningModule, ABC): |
| """ |
| Few-shot multiclass classification via nearest-centroid. |
| |
| Workflow in each epoch |
| ββββββββββββββββββββββ |
| 1. `training_step` collects embeddings & labels for all train batches. |
| 2. `on_validation_epoch_start` computes one centroid per class. |
| 3. Validation/test steps assign each example to the nearest centroid. |
| """ |
|
|
| |
| |
| @staticmethod |
| def _to_label_indices(y: torch.Tensor) -> torch.Tensor: |
| """ |
| Convert `y` to shape (N,) of dtype long. |
| |
| Accepts: |
| β’ (N,) already indices |
| β’ (N, 1) unsqueezed indices |
| β’ (N, C, β¦) one-hot (argmax over dim=1) |
| """ |
| if y.ndim == 2 and y.size(1) == 1: |
| y = y.squeeze(1) |
| elif y.ndim >= 2: |
| y = y.argmax(dim=1) |
| return y.long().view(-1) |
|
|
| |
| |
| def __init__( |
| self, |
| sample_rate: int, |
| num_classes: int, |
| encoder, |
| emb_transforms, |
| ): |
| super().__init__() |
| self.save_hyperparameters(ignore=["encoder", "emb_transforms"]) |
|
|
| |
| self.encoder = encoder |
| self.emb_transforms = nn.ModuleList(emb_transforms or []) |
|
|
| self.sample_rate = sample_rate |
| self.num_classes = num_classes |
|
|
| |
| self.val_accuracy = Accuracy(num_classes=num_classes, task="multiclass") |
| self.test_accuracy = Accuracy(num_classes=num_classes, task="multiclass") |
|
|
| |
| self._train_embeddings: list[torch.Tensor] = [] |
| self._train_labels: list[torch.Tensor] = [] |
|
|
| |
| self.register_buffer("class_centroids", torch.empty(0)) |
|
|
| |
| self.automatic_optimization = False |
|
|
| def forward(self, x: torch.Tensor) -> torch.Tensor: |
| h = self.encoder(x) |
| for tf in self.emb_transforms: |
| h = tf(h) |
| h = h.view(h.size(0), -1) |
| return h |
|
|
| |
| |
| def training_step(self, batch, batch_idx): |
| x, y = batch[:2] |
| y = self._to_label_indices(y) |
|
|
| emb = self(x) |
| self._train_embeddings.append(emb.detach()) |
| self._train_labels.append(y.detach()) |
|
|
| return None |
|
|
| |
| |
| def on_validation_epoch_start(self) -> None: |
| |
| if not self._train_embeddings: |
| return |
|
|
| embs = torch.cat(self._train_embeddings, dim=0) |
| labels = torch.cat(self._train_labels, dim=0) |
|
|
| classes = torch.unique(labels).sort()[0] |
| centroids = torch.stack( |
| [embs[labels == c].mean(dim=0) for c in classes], dim=0 |
| ) |
|
|
| self.class_centroids = centroids.to(self.device) |
|
|
| |
| self._train_embeddings.clear() |
| self._train_labels.clear() |
|
|
| |
| |
| @staticmethod |
| def _nearest(emb: torch.Tensor, centroids: torch.Tensor) -> torch.Tensor: |
| """ |
| Return index of closest centroid for each embedding. |
| emb : (B, D) |
| centroids : (C, D) |
| β (B,) |
| """ |
| dists = torch.norm( |
| emb.unsqueeze(1) - centroids.unsqueeze(0), dim=2 |
| ) |
| return dists.argmin(dim=1) |
|
|
| |
| |
| def validation_step(self, batch, batch_idx): |
| if self.class_centroids.numel() == 0: |
| raise RuntimeError( |
| "Centroids empty β ensure `on_validation_epoch_start` has run." |
| ) |
|
|
| x, y = batch[:2] |
| y = self._to_label_indices(y) |
|
|
| embs = self(x) |
| preds = self._nearest(embs, self.class_centroids) |
|
|
| |
| self.log( |
| "val/acc", |
| self.val_accuracy(preds.float(), y), |
| prog_bar=True, |
| on_epoch=True, |
| sync_dist=True, |
| ) |
| |
| |
| def test_step(self, batch, batch_idx): |
| if self.class_centroids.numel() == 0: |
| |
| train_loader = self.trainer.datamodule.train_dataloader() |
| self._train_embeddings.clear() |
| self._train_labels.clear() |
| |
| |
| for batch in train_loader: |
| x, y = batch[:2] |
| y = self._to_label_indices(y) |
| emb = self(x) |
| self._train_embeddings.append(emb.detach()) |
| self._train_labels.append(y.detach()) |
|
|
| embs = torch.cat(self._train_embeddings, dim=0) |
| labels = torch.cat(self._train_labels, dim=0) |
|
|
| classes = torch.unique(labels).sort()[0] |
| centroids = torch.stack( |
| [embs[labels == c].mean(dim=0) for c in classes], dim=0 |
| ) |
|
|
| self.class_centroids = centroids.to(self.device) |
| self._train_embeddings.clear() |
| self._train_labels.clear() |
|
|
| x, y = batch[:2] |
| y = self._to_label_indices(y) |
| preds = self._nearest(self(x), self.class_centroids) |
|
|
| |
| self.test_accuracy = self.test_accuracy.to(self.device) |
|
|
| |
| self.log( |
| "test/acc", |
| self.test_accuracy(preds.to(self.device), y.to(self.device)), |
| prog_bar=True, |
| on_epoch=True, |
| sync_dist=True, |
| ) |
| |
| def configure_optimizers(self): |
| |
| return [] |
| |