|
14 | 14 | # See the License for the specific language governing permissions
|
15 | 15 | # and limitations under the License.
|
16 | 16 |
|
| 17 | +import io |
17 | 18 | from typing import Optional
|
18 | 19 |
|
| 20 | +import torch |
19 | 21 | from adapters.anomalib.callbacks import ProgressCallback
|
20 | 22 | from adapters.anomalib.data import OTEAnomalyDataModule
|
21 | 23 | from adapters.anomalib.logger import get_logger
|
| 24 | +from anomalib.models import AnomalyModule, get_model |
22 | 25 | from anomalib.utils.callbacks import (
|
23 | 26 | MetricsConfigurationCallback,
|
24 | 27 | MinMaxNormalizationCallback,
|
@@ -83,3 +86,42 @@ def train(
|
83 | 86 | self.save_model(output_model)
|
84 | 87 |
|
85 | 88 | logger.info("Training completed.")
|
| 89 | + |
| 90 | + def load_model(self, ote_model: Optional[ModelEntity]) -> AnomalyModule: |
| 91 | + """Create and Load Anomalib Module from OTE Model. |
| 92 | +
|
| 93 | + This method checks if the task environment has a saved OTE Model, |
| 94 | + and creates one. If the OTE model already exists, it returns the |
| 95 | + the model with the saved weights. |
| 96 | +
|
| 97 | + Args: |
| 98 | + ote_model (Optional[ModelEntity]): OTE Model from the |
| 99 | + task environment. |
| 100 | +
|
| 101 | + Returns: |
| 102 | + AnomalyModule: Anomalib |
| 103 | + classification or segmentation model with/without weights. |
| 104 | + """ |
| 105 | + model = get_model(config=self.config) |
| 106 | + if ote_model is None: |
| 107 | + logger.info( |
| 108 | + "No trained model in project yet. Created new model with '%s'", |
| 109 | + self.model_name, |
| 110 | + ) |
| 111 | + else: |
| 112 | + buffer = io.BytesIO(ote_model.get_data("weights.pth")) |
| 113 | + model_data = torch.load(buffer, map_location=torch.device("cpu")) |
| 114 | + |
| 115 | + try: |
| 116 | + if model_data["config"]["model"]["backbone"] == self.config["model"]["backbone"]: |
| 117 | + model.load_state_dict(model_data["model"]) |
| 118 | + logger.info("Loaded model weights from Task Environment") |
| 119 | + else: |
| 120 | + logger.info( |
| 121 | + "Model backbone does not match. Created new model with '%s'", |
| 122 | + self.model_name, |
| 123 | + ) |
| 124 | + except BaseException as exception: |
| 125 | + raise ValueError("Could not load the saved model. The model file structure is invalid.") from exception |
| 126 | + |
| 127 | + return model |
0 commit comments