"""PyTorch model for the STFPM model implementation."""# Copyright (C) 2020 Intel Corporation## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing,# software distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions# and limitations under the License.fromtypingimportDict,List,Optional,TupleimporttorchvisionfromtorchimportTensor,nnfromanomalib.models.componentsimportFeatureExtractorfromanomalib.models.stfpm.anomaly_mapimportAnomalyMapGeneratorfromanomalib.pre_processingimportTiler
[docs]classSTFPMModel(nn.Module):"""STFPM: Student-Teacher Feature Pyramid Matching for Unsupervised Anomaly Detection. Args: layers (List[str]): Layers used for feature extraction input_size (Tuple[int, int]): Input size for the model. backbone (str, optional): Pre-trained model backbone. Defaults to "resnet18". """def__init__(self,layers:List[str],input_size:Tuple[int,int],backbone:str="resnet18",):super().__init__()self.tiler:Optional[Tiler]=Noneself.backbone=getattr(torchvision.models,backbone)self.teacher_model=FeatureExtractor(backbone=self.backbone(pretrained=True),layers=layers)self.student_model=FeatureExtractor(backbone=self.backbone(pretrained=False),layers=layers)# teacher model is fixedforparametersinself.teacher_model.parameters():parameters.requires_grad=False# Create the anomaly heatmap generator whether tiling is set.# TODO: Check whether Tiler is properly initialized here.ifself.tiler:image_size=(self.tiler.tile_size_h,self.tiler.tile_size_w)else:image_size=input_sizeself.anomaly_map_generator=AnomalyMapGenerator(image_size=tuple(image_size))
[docs]defforward(self,images):"""Forward-pass images into the network. During the training mode the model extracts the features from the teacher and student networks. During the evaluation mode, it returns the predicted anomaly map. Args: images (Tensor): Batch of images. Returns: Teacher and student features when in training mode, otherwise the predicted anomaly maps. """ifself.tiler:images=self.tiler.tile(images)teacher_features:Dict[str,Tensor]=self.teacher_model(images)student_features:Dict[str,Tensor]=self.student_model(images)ifself.training:output=teacher_features,student_featureselse:output=self.anomaly_map_generator(teacher_features=teacher_features,student_features=student_features)ifself.tiler:output=self.tiler.untile(output)returnoutput