|
| 1 | +# Copyright contributors to the Terratorch project |
| 2 | + |
| 3 | +""" |
| 4 | +This is just an example of a possible structure to include SMP models |
| 5 | +Right now it always returns a UNET, but could easily be extended to many of the models provided by SMP. |
| 6 | +""" |
| 7 | + |
| 8 | +from torch import nn |
| 9 | +import torch |
| 10 | +from terratorch.models.model import Model, ModelFactory, ModelOutput, register_factory |
| 11 | +from terratorch.tasks.segmentation_tasks import to_segmentation_prediction |
| 12 | + |
| 13 | +import importlib |
| 14 | + |
| 15 | +def freeze_module(module: nn.Module): |
| 16 | + for param in module.parameters(): |
| 17 | + param.requires_grad_(False) |
| 18 | + |
| 19 | +@register_factory |
| 20 | +class GenericUnetModelFactory(ModelFactory): |
| 21 | + def build_model( |
| 22 | + self, |
| 23 | + task: str = "segmentation", |
| 24 | + backbone: str = None, |
| 25 | + decoder: str = None, |
| 26 | + dilations: tuple[int] = (1, 6, 12, 18), |
| 27 | + in_channels: int = 6, |
| 28 | + pretrained: str | bool | None = True, |
| 29 | + num_classes: int = 1, |
| 30 | + regression_relu: bool = False, |
| 31 | + **kwargs, |
| 32 | + ) -> Model: |
| 33 | + """Factory to create model based on SMP. |
| 34 | +
|
| 35 | + Args: |
| 36 | + task (str): Must be "segmentation". |
| 37 | + model (str): Decoder architecture. Currently only supports "unet". |
| 38 | + in_channels (int): Number of input channels. |
| 39 | + pretrained(str | bool): Which weights to use for the backbone. If true, will use "imagenet". If false or None, random weights. Defaults to True. |
| 40 | + num_classes (int): Number of classes. |
| 41 | + regression_relu (bool). Whether to apply a ReLU if task is regression. Defaults to False. |
| 42 | +
|
| 43 | + Returns: |
| 44 | + Model: SMP model wrapped in SMPModelWrapper. |
| 45 | + """ |
| 46 | + if task not in ["segmentation", "regression"]: |
| 47 | + msg = f"SMP models can only perform pixel wise tasks, but got task {task}" |
| 48 | + raise Exception(msg) |
| 49 | + |
| 50 | + mmseg_decoders = importlib.import_module("mmseg.models.decode_heads") |
| 51 | + mmseg_encoders = importlib.import_module("mmseg.models.backbones") |
| 52 | + |
| 53 | + if backbone: |
| 54 | + backbone_kwargs = _extract_prefix_keys(kwargs, "backbone_") |
| 55 | + model = backbone |
| 56 | + model_kwargs = backbone_kwargs |
| 57 | + mmseg = mmseg_encoders |
| 58 | + elif decoder: |
| 59 | + decoder_kwargs = _extract_prefix_keys(kwargs, "decoder_") |
| 60 | + model = decoder |
| 61 | + model_kwargs = decoder_kwargs |
| 62 | + mmseg = mmseg_decoders |
| 63 | + else: |
| 64 | + print("It is necessary to define a backbone and/or a decoder.") |
| 65 | + |
| 66 | + model_class = getattr(mmseg, model) |
| 67 | + |
| 68 | + model = model_class( |
| 69 | + **model_kwargs, |
| 70 | + ) |
| 71 | + |
| 72 | + return GenericUnetModelWrapper( |
| 73 | + model, relu=task == "regression" and regression_relu, squeeze_single_class=task == "regression" |
| 74 | + ) |
| 75 | + |
| 76 | +class GenericUnetModelWrapper(Model, nn.Module): |
| 77 | + def __init__(self, unet_model, relu=False, squeeze_single_class=False) -> None: |
| 78 | + super().__init__() |
| 79 | + self.unet_model = unet_model |
| 80 | + self.final_act = nn.ReLU() if relu else nn.Identity() |
| 81 | + self.squeeze_single_class = squeeze_single_class |
| 82 | + |
| 83 | + def forward(self, *args, **kwargs): |
| 84 | + |
| 85 | + # It supposes the input has dimension (B, C, H, W) |
| 86 | + input_data = [args[0]] # It adapts the input to became a list of time 'snapshots' |
| 87 | + args = (input_data,) |
| 88 | + |
| 89 | + unet_output = self.unet_model(*args, **kwargs) |
| 90 | + unet_output = self.final_act(unet_output) |
| 91 | + |
| 92 | + if unet_output.shape[1] == 1 and self.squeeze_single_class: |
| 93 | + unet_output = unet_output.squeeze(1) |
| 94 | + |
| 95 | + model_output = ModelOutput(unet_output) |
| 96 | + |
| 97 | + return model_output |
| 98 | + |
| 99 | + def freeze_encoder(self): |
| 100 | + raise NotImplementedError() |
| 101 | + |
| 102 | + def freeze_decoder(self): |
| 103 | + raise freeze_module(self.unet_model) |
| 104 | + |
| 105 | + |
| 106 | +def _extract_prefix_keys(d: dict, prefix: str) -> dict: |
| 107 | + extracted_dict = {} |
| 108 | + keys_to_del = [] |
| 109 | + for k, v in d.items(): |
| 110 | + if k.startswith(prefix): |
| 111 | + extracted_dict[k.split(prefix)[1]] = v |
| 112 | + keys_to_del.append(k) |
| 113 | + |
| 114 | + for k in keys_to_del: |
| 115 | + del d[k] |
| 116 | + |
| 117 | + return extracted_dict |
0 commit comments