Repository: Project-MONAI/MONAI
File: monai/networks/nets/resnet.py (Python)

Code before:
def _resnet(
    arch: str,
    block: type[ResNetBlock | ResNetBottleneck],
    layers: list[int],
    block_inplanes: list[int],
    pretrained: bool | str,
    progress: bool,
    **kwargs: Any,
) -> ResNet:
    model: ResNet = ResNet(block, layers, block_inplanes, **kwargs)
    if pretrained:
        if isinstance(pretrained, str):
            if Path(pretrained).exists():
                logger.info(f"Loading weights from {pretrained}...")
                model_state_dict = torch.load(pretrained, map_location=device)
            else:
                # Throw error
                raise FileNotFoundError("The pretrained checkpoint file is not found")
        else:
            # Also check bias downsample and shortcut.
            if kwargs.get("spatial_dims", 3) == 3:
                if kwargs.get("n_input_channels", 3) == 1 and kwargs.get("feed_forward", True) is False:
                    resnet_depth = int(re.search(r"resnet(\d+)", arch).group(1))
                    # get shortcut_type and bias_downsample.

                    def get_medicalnet_pretrained_resnet_args(resnet_depth: int):
                        """
                        Return correct shortcut_type and bias_downsample
                        for pretrained MedicalNet weights according to rensnet depth
                        """
                        # After testing
                        # False: 10, 50, 101, 152, 200
                        # Any: 18, 34
                        bias_downsample = -1 if resnet_depth in [18, 34] else 0  # 18, 10, 34
                        shortcut_type = "A" if resnet_depth in [18, 34] else "B"
                        return bias_downsample, shortcut_type

                    # Check model bias_downsample and shortcut_type
                    bias_downsample, shortcut_type = get_medicalnet_pretrained_resnet_args(resnet_depth)
                    if shortcut_type == kwargs.get("shortcut_type", "B") and (
                        bool(bias_downsample) == kwargs.get("bias_downsample", False) if bias_downsample != -1 else True
                    ):
                        # Download the MedicalNet pretrained model
                        model_state_dict = get_pretrained_resnet_medicalnet(
                            resnet_depth, device=device, datasets23=True
                        )
                    else:
                        raise NotImplementedError(
                            f"Please set shortcut_type to {shortcut_type} and bias_downsample to"
                            f"{bool(bias_downsample) if bias_downsample!=-1 else 'True or False'}"
                            f"when using pretrained MedicalNet resnet{resnet_depth}"

Review comment (suggestion):
I would suggest moving it out from the `_resnet` as a separate function then the unittest can also import this one without duplicating another one.

Code after:
def _resnet(
    arch: str,
    block: type[ResNetBlock | ResNetBottleneck],
    layers: list[int],
    block_inplanes: list[int],
    pretrained: bool | str,
    progress: bool,
    **kwargs: Any,
) -> ResNet:
    model: ResNet = ResNet(block, layers, block_inplanes, **kwargs)
    if pretrained:
        device = "cuda" if torch.cuda.is_available() else "cpu"
        if isinstance(pretrained, str):
            if Path(pretrained).exists():
                logger.info(f"Loading weights from {pretrained}...")
                model_state_dict = torch.load(pretrained, map_location=device)
            else:
                # Throw error
                raise FileNotFoundError("The pretrained checkpoint file is not found")
        else:
            # Also check bias downsample and shortcut.
            if kwargs.get("spatial_dims", 3) == 3:
                if kwargs.get("n_input_channels", 3) == 1 and kwargs.get("feed_forward", True) is False:
                    search_res = re.search(r"resnet(\d+)", arch)
                    if search_res:
                        resnet_depth = int(search_res.group(1))
                    else:
                        raise ValueError("arch argument should be as 'resnet_{resnet_depth}")

                    # Check model bias_downsample and shortcut_type
                    bias_downsample, shortcut_type = get_medicalnet_pretrained_resnet_args(resnet_depth)
                    if shortcut_type == kwargs.get("shortcut_type", "B") and (
                        bool(bias_downsample) == kwargs.get("bias_downsample", False) if bias_downsample != -1 else True
                    ):
                        # Download the MedicalNet pretrained model
                        model_state_dict = get_pretrained_resnet_medicalnet(
                            resnet_depth, device=device, datasets23=True
                        )
                    else:
                        raise NotImplementedError(
                            f"Please set shortcut_type to {shortcut_type} and bias_downsample to"
                            f"{bool(bias_downsample) if bias_downsample!=-1 else 'True or False'}"
                            f"when using pretrained MedicalNet resnet{resnet_depth}"
                        )
                else:
                    raise NotImplementedError(
                        "Please set n_input_channels to 1"
                        "and feed_forward to False in order to use MedicalNet pretrained weights"
                    )
            else:
                raise NotImplementedError("MedicalNet pretrained weights are only avalaible for 3D models")