Module contrib.semseg.training
Trains multiple linear probes in parallel on DINOv2's ADE20K activations.
Functions
def batched_idx(total_size: int, batch_size: int) ‑> Iterator[tuple[int, int]]
-
Iterate over (start, end) indices for total_size examples, where end - start is at most batch_size.
Args
total_size
- total number of examples
batch_size
- maximum distance between the generated indices.
Returns
A generator of (int, int) tuples that can slice up a list or a tensor.
def batched_upsample_and_pred(tensor: jaxtyping.Float[Tensor, 'n channels width height'],
*,
size: tuple[int, int],
mode: str,
batch_size: int = 128) ‑> jaxtyping.Int[Tensor, 'n {size[0]} {size[1]}']def check_cfgs(cfgs: list[Train])
def count_patches(ade20k: Ade20kDataset,
patch_size_px: tuple[int, int] = (14, 14),
threshold: float = 0.9,
n_workers: int = 8)-
Count the number of patches in the data that meets
def dump(cfg: Train,
model: torch.nn.modules.module.Module,
*,
step: int | None = None)-
Save a model checkpoint to disk along with configuration, using the trick from equinox.
def get_class_ious(y_pred: jaxtyping.Int[Tensor, 'models batch width height'],
y_true: jaxtyping.Int[Tensor, 'models batch width height'],
n_classes: int,
ignore_class: int | None = 0) ‑> jaxtyping.Float[Tensor, 'models n_classes']-
Calculate mean IoU for predicted masks.
Arguments
y_pred: y_true: n_classes: Number of classes.
Returns
Mean IoU as a float tensor.
def get_dataloader(cfg: Train,
*,
is_train: bool)def load(fpath: str, *, device: str = 'cpu') ‑> torch.nn.modules.module.Module
-
Loads a sparse autoencoder from disk.
def load_latest(dpath: str, *, device: str = 'cpu') ‑> torch.nn.modules.module.Module
-
Loads the latest checkpoint by picking out the checkpoint file in dpath with the largest _step{step} suffix.
Arguments
dpath: Directory to search. device: optional torch device to pass to load.
def main(cfgs: list[Train])
def make_models(cfgs: list[Train],
d_vit: int) ‑> tuple[torch.nn.modules.container.ModuleList, list[dict[str, object]]]
Classes
class Dataset (imgs_cfg: Ade20kDataset)
-
An abstract class representing a :class:
Dataset
.All datasets that represent a map from keys to data samples should subclass it. All subclasses should overwrite :meth:
__getitem__
, supporting fetching a data sample for a given key. Subclasses could also optionally overwrite :meth:__len__
, which is expected to return the size of the dataset by many :class:~torch.utils.data.Sampler
implementations and the default options of :class:~torch.utils.data.DataLoader
. Subclasses could also optionally implement :meth:__getitems__
, for speedup batched samples loading. This method accepts list of indices of samples of batch and returns list of samples.Note
:class:
~torch.utils.data.DataLoader
by default constructs an index sampler that yields integral indices. To make it work with a map-style dataset with non-integral indices/keys, a custom sampler must be provided.Expand source code
@beartype.beartype class Dataset(torch.utils.data.Dataset): def __init__(self, imgs_cfg: saev.config.Ade20kDataset): img_transform = v2.Compose([ v2.Resize(size=(256, 256)), v2.CenterCrop(size=(224, 224)), v2.ToImage(), v2.ToDtype(torch.float32, scale=True), v2.Normalize(mean=[0.4850, 0.4560, 0.4060], std=[0.2290, 0.2240, 0.2250]), ]) seg_transform = v2.Compose([ v2.Resize(size=(256, 256), interpolation=v2.InterpolationMode.NEAREST), v2.CenterCrop((224, 224)), v2.ToImage(), ]) self.samples = saev.activations.Ade20k( imgs_cfg, img_transform=img_transform, seg_transform=seg_transform ) self.patch_size_px = (14, 14) def __getitem__(self, i: int) -> dict[str, object]: # Get patch and pixel level semantic labels. sample = self.samples[i] pixel_labels = sample["segmentation"].squeeze() pw, ph = self.patch_size_px patch_labels = ( einops.rearrange(pixel_labels, "(w pw) (h ph) -> w h (pw ph)", pw=pw, ph=ph) .mode(axis=-1) .values ) return { "index": i, "image": sample["image"], "pixel_labels": pixel_labels, "patch_labels": patch_labels, } def __len__(self) -> int: return len(self.samples)
Ancestors
- torch.utils.data.dataset.Dataset
- typing.Generic
class DinoV2
-
Base class for all neural network modules.
Your models should also subclass this class.
Modules can also contain other Modules, allowing to nest them in a tree structure. You can assign the submodules as regular attributes::
import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x))
Submodules assigned in this way will be registered, and will have their parameters converted too when you call :meth:
to
, etc.Note
As per the example above, an
__init__()
call to the parent class must be made before assignment on the child.:ivar training: Boolean represents whether this module is in training or evaluation mode. :vartype training: bool
Initialize internal Module state, shared by both nn.Module and ScriptModule.
Expand source code
@jaxtyped(typechecker=beartype.beartype) class DinoV2(torch.nn.Module): def __init__(self): super().__init__() self.model = torch.hub.load("facebookresearch/dinov2", "dinov2_vitb14_reg") self.d_resid = 768 def forward(self, batch: Float[Tensor, "batch 3 width height"]): dct = self.model.forward_features(batch) return dct["x_norm_patchtokens"]
Ancestors
- torch.nn.modules.module.Module
Methods
def forward(self, batch: jaxtyping.Float[Tensor, 'batch 3 width height']) ‑> Callable[..., Any]
-
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the :class:
Module
instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.