|
| 1 | +import warnings |
| 2 | +from abc import abstractmethod |
| 3 | +from typing import List, Optional, Sequence, Tuple, Union, final |
| 4 | + |
| 5 | +from bioimageio.spec.model import v0_4, v0_5 |
| 6 | + |
| 7 | +from ._model_adapter import ( |
| 8 | + DEFAULT_WEIGHT_FORMAT_PRIORITY_ORDER, |
| 9 | + ModelAdapter, |
| 10 | + WeightsFormat, |
| 11 | +) |
| 12 | +from .tensor import Tensor |
| 13 | + |
| 14 | + |
| 15 | +def create_model_adapter( |
| 16 | + model_description: Union[v0_4.ModelDescr, v0_5.ModelDescr], |
| 17 | + *, |
| 18 | + devices: Optional[Sequence[str]] = None, |
| 19 | + weight_format_priority_order: Optional[Sequence[WeightsFormat]] = None, |
| 20 | +): |
| 21 | + """ |
| 22 | + Creates model adapter based on the passed spec |
| 23 | + Note: All specific adapters should happen inside this function to prevent different framework |
| 24 | + initializations interfering with each other |
| 25 | + """ |
| 26 | + if not isinstance(model_description, (v0_4.ModelDescr, v0_5.ModelDescr)): |
| 27 | + raise TypeError( |
| 28 | + f"expected v0_4.ModelDescr or v0_5.ModelDescr, but got {type(model_description)}" |
| 29 | + ) |
| 30 | + |
| 31 | + weights = model_description.weights |
| 32 | + errors: List[Tuple[WeightsFormat, Exception]] = [] |
| 33 | + weight_format_priority_order = ( |
| 34 | + DEFAULT_WEIGHT_FORMAT_PRIORITY_ORDER |
| 35 | + if weight_format_priority_order is None |
| 36 | + else weight_format_priority_order |
| 37 | + ) |
| 38 | + # limit weight formats to the ones present |
| 39 | + weight_format_priority_order = [ |
| 40 | + w for w in weight_format_priority_order if getattr(weights, w) is not None |
| 41 | + ] |
| 42 | + |
| 43 | + for wf in weight_format_priority_order: |
| 44 | + if wf == "pytorch_state_dict" and weights.pytorch_state_dict is not None: |
| 45 | + try: |
| 46 | + from .model_adapters_old._pytorch_model_adapter import ( |
| 47 | + PytorchModelAdapter, |
| 48 | + ) |
| 49 | + |
| 50 | + return PytorchModelAdapter( |
| 51 | + outputs=model_description.outputs, |
| 52 | + weights=weights.pytorch_state_dict, |
| 53 | + devices=devices, |
| 54 | + ) |
| 55 | + except Exception as e: |
| 56 | + errors.append((wf, e)) |
| 57 | + elif ( |
| 58 | + wf == "tensorflow_saved_model_bundle" |
| 59 | + and weights.tensorflow_saved_model_bundle is not None |
| 60 | + ): |
| 61 | + try: |
| 62 | + from .model_adapters_old._tensorflow_model_adapter import ( |
| 63 | + TensorflowModelAdapter, |
| 64 | + ) |
| 65 | + |
| 66 | + return TensorflowModelAdapter( |
| 67 | + model_description=model_description, devices=devices |
| 68 | + ) |
| 69 | + except Exception as e: |
| 70 | + errors.append((wf, e)) |
| 71 | + elif wf == "onnx" and weights.onnx is not None: |
| 72 | + try: |
| 73 | + from .model_adapters_old._onnx_model_adapter import ONNXModelAdapter |
| 74 | + |
| 75 | + return ONNXModelAdapter( |
| 76 | + model_description=model_description, devices=devices |
| 77 | + ) |
| 78 | + except Exception as e: |
| 79 | + errors.append((wf, e)) |
| 80 | + elif wf == "torchscript" and weights.torchscript is not None: |
| 81 | + try: |
| 82 | + from .model_adapters_old._torchscript_model_adapter import ( |
| 83 | + TorchscriptModelAdapter, |
| 84 | + ) |
| 85 | + |
| 86 | + return TorchscriptModelAdapter( |
| 87 | + model_description=model_description, devices=devices |
| 88 | + ) |
| 89 | + except Exception as e: |
| 90 | + errors.append((wf, e)) |
| 91 | + elif wf == "keras_hdf5" and weights.keras_hdf5 is not None: |
| 92 | + # keras can either be installed as a separate package or used as part of tensorflow |
| 93 | + # we try to first import the keras model adapter using the separate package and, |
| 94 | + # if it is not available, try to load the one using tf |
| 95 | + try: |
| 96 | + from .backend.keras import ( |
| 97 | + KerasModelAdapter, |
| 98 | + keras, # type: ignore |
| 99 | + ) |
| 100 | + |
| 101 | + if keras is None: |
| 102 | + from .model_adapters_old._tensorflow_model_adapter import ( |
| 103 | + KerasModelAdapter, |
| 104 | + ) |
| 105 | + |
| 106 | + return KerasModelAdapter( |
| 107 | + model_description=model_description, devices=devices |
| 108 | + ) |
| 109 | + except Exception as e: |
| 110 | + errors.append((wf, e)) |
| 111 | + |
| 112 | + assert errors |
| 113 | + if len(weight_format_priority_order) == 1: |
| 114 | + assert len(errors) == 1 |
| 115 | + raise ValueError( |
| 116 | + f"The '{weight_format_priority_order[0]}' model adapter could not be created" |
| 117 | + + f" in this environment:\n{errors[0][1].__class__.__name__}({errors[0][1]}).\n\n" |
| 118 | + ) from errors[0][1] |
| 119 | + |
| 120 | + else: |
| 121 | + error_list = "\n - ".join( |
| 122 | + f"{wf}: {e.__class__.__name__}({e})" for wf, e in errors |
| 123 | + ) |
| 124 | + raise ValueError( |
| 125 | + "None of the weight format specific model adapters could be created" |
| 126 | + + f" in this environment. Errors are:\n\n{error_list}.\n\n" |
| 127 | + ) |
0 commit comments