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
from torch import device
|
| 5 |
+
from .utils import get_parameter_device, get_parameter_dtype, save_state_dict_and_config, load_state_dict_from_path
|
| 6 |
+
|
| 7 |
+
class BaseModel(torch.nn.Module):
|
| 8 |
+
"""
|
| 9 |
+
A base model class that provides a template for implementing models. It includes methods for
|
| 10 |
+
loading, saving, and managing model configurations and states. This class is designed to be
|
| 11 |
+
extended by specific model implementations.
|
| 12 |
+
|
| 13 |
+
Attributes:
|
| 14 |
+
config (object): Configuration object containing model settings.
|
| 15 |
+
input_color_flip (bool): Whether to flip the color channels from BGR to RGB.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
def __init__(self, config=None):
|
| 19 |
+
"""
|
| 20 |
+
Initializes the BaseModel class.
|
| 21 |
+
|
| 22 |
+
Parameters:
|
| 23 |
+
config (object, optional): Configuration object containing model settings.
|
| 24 |
+
"""
|
| 25 |
+
super(BaseModel, self).__init__()
|
| 26 |
+
self.config = config
|
| 27 |
+
if self.config.color_space == 'BGR':
|
| 28 |
+
self.input_color_flip = True
|
| 29 |
+
self._config_color_space = 'BGR'
|
| 30 |
+
self.config.color_space = 'RGB'
|
| 31 |
+
else:
|
| 32 |
+
self.input_color_flip = False
|
| 33 |
+
|
| 34 |
+
def forward(self, x):
|
| 35 |
+
"""
|
| 36 |
+
Forward pass of the model. Needs to be implemented in subclass.
|
| 37 |
+
|
| 38 |
+
Parameters:
|
| 39 |
+
x (torch.Tensor): Input tensor.
|
| 40 |
+
|
| 41 |
+
Raises:
|
| 42 |
+
NotImplementedError: If the subclass does not implement this method.
|
| 43 |
+
"""
|
| 44 |
+
raise NotImplementedError('forward must be implemented in subclass')
|
| 45 |
+
|
| 46 |
+
@classmethod
|
| 47 |
+
def from_config(cls, config) -> "BaseModel":
|
| 48 |
+
"""
|
| 49 |
+
Creates an instance of this class from a configuration object. Needs to be implemented in subclass.
|
| 50 |
+
|
| 51 |
+
Parameters:
|
| 52 |
+
config (object): Configuration object.
|
| 53 |
+
|
| 54 |
+
Returns:
|
| 55 |
+
BaseModel: An instance of the subclass.
|
| 56 |
+
|
| 57 |
+
Raises:
|
| 58 |
+
NotImplementedError: If the subclass does not implement this method.
|
| 59 |
+
"""
|
| 60 |
+
raise NotImplementedError('from_config must be implemented in subclass')
|
| 61 |
+
|
| 62 |
+
def make_train_transform(self):
|
| 63 |
+
"""
|
| 64 |
+
Creates training data transformations. Needs to be implemented in subclass.
|
| 65 |
+
|
| 66 |
+
Raises:
|
| 67 |
+
NotImplementedError: If the subclass does not implement this method.
|
| 68 |
+
"""
|
| 69 |
+
raise NotImplementedError('make_train_transform must be implemented in subclass')
|
| 70 |
+
|
| 71 |
+
def make_test_transform(self):
|
| 72 |
+
"""
|
| 73 |
+
Creates testing data transformations. Needs to be implemented in subclass.
|
| 74 |
+
|
| 75 |
+
Raises:
|
| 76 |
+
NotImplementedError: If the subclass does not implement this method.
|
| 77 |
+
"""
|
| 78 |
+
raise NotImplementedError('make_test_transform must be implemented in subclass')
|
| 79 |
+
|
| 80 |
+
def save_pretrained(
|
| 81 |
+
self,
|
| 82 |
+
save_dir: Union[str, os.PathLike],
|
| 83 |
+
name: str = 'model.pt',
|
| 84 |
+
rank: int = 0,
|
| 85 |
+
):
|
| 86 |
+
"""
|
| 87 |
+
Saves the model's state_dict and configuration to the specified directory.
|
| 88 |
+
|
| 89 |
+
Parameters:
|
| 90 |
+
save_dir (Union[str, os.PathLike]): The directory to save the model.
|
| 91 |
+
name (str, optional): The name of the file to save the model as. Default is 'model.pt'.
|
| 92 |
+
rank (int, optional): The rank of the process (used in distributed training). Default is 0.
|
| 93 |
+
"""
|
| 94 |
+
save_path = os.path.join(save_dir, name)
|
| 95 |
+
if rank == 0:
|
| 96 |
+
save_state_dict_and_config(self.state_dict(), self.config, save_path)
|
| 97 |
+
|
| 98 |
+
def load_state_dict_from_path(self, pretrained_model_path):
|
| 99 |
+
state_dict = load_state_dict_from_path(pretrained_model_path)
|
| 100 |
+
if 'net.vit' in list(self.state_dict().keys())[-1] and 'pretrained_models' in pretrained_model_path:
|
| 101 |
+
state_dict = {k.replace('net', 'net.vit'): v for k, v in state_dict.items()}
|
| 102 |
+
|
| 103 |
+
st_keys = list(state_dict.keys())
|
| 104 |
+
self_keys = list(self.state_dict().keys())
|
| 105 |
+
print('compatible keys in state_dict', len(set(st_keys).intersection(set(self_keys))), '/', len(st_keys))
|
| 106 |
+
print('Check\n\n')
|
| 107 |
+
result = self.load_state_dict(state_dict, strict=False)
|
| 108 |
+
print(result)
|
| 109 |
+
print(f"Loaded pretrained model from {pretrained_model_path}")
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@property
|
| 113 |
+
def device(self) -> device:
|
| 114 |
+
"""
|
| 115 |
+
Returns the device of the model's parameters.
|
| 116 |
+
|
| 117 |
+
Returns:
|
| 118 |
+
device: The device the model is on.
|
| 119 |
+
"""
|
| 120 |
+
return get_parameter_device(self)
|
| 121 |
+
|
| 122 |
+
@property
|
| 123 |
+
def dtype(self) -> torch.dtype:
|
| 124 |
+
"""
|
| 125 |
+
Returns the data type of the model's parameters.
|
| 126 |
+
|
| 127 |
+
Returns:
|
| 128 |
+
torch.dtype: The data type of the model.
|
| 129 |
+
"""
|
| 130 |
+
return get_parameter_dtype(self)
|
| 131 |
+
|
| 132 |
+
def num_parameters(self, only_trainable: bool = False) -> int:
|
| 133 |
+
"""
|
| 134 |
+
Returns the number of parameters in the model, optionally filtering only trainable parameters.
|
| 135 |
+
|
| 136 |
+
Parameters:
|
| 137 |
+
only_trainable (bool, optional): Whether to count only trainable parameters. Default is False.
|
| 138 |
+
|
| 139 |
+
Returns:
|
| 140 |
+
int: The number of parameters.
|
| 141 |
+
"""
|
| 142 |
+
return sum(p.numel() for p in self.parameters() if p.requires_grad or not only_trainable)
|
| 143 |
+
|
| 144 |
+
def has_trainable_params(self):
|
| 145 |
+
"""
|
| 146 |
+
Checks if the model has any trainable parameters.
|
| 147 |
+
|
| 148 |
+
Returns:
|
| 149 |
+
bool: True if the model has trainable parameters, False otherwise.
|
| 150 |
+
"""
|
| 151 |
+
return any(p.requires_grad for p in self.parameters())
|