16
16
from torch import nn
17
17
from torch .optim .swa_utils import AveragedModel , SWALR
18
18
19
- import openvino as ov
20
- import shelve
21
19
22
20
from sklearn .decomposition import PCA
23
21
@@ -1703,8 +1701,7 @@ def save(self, path, use_onnx=False, path_onnx=None, use_openvino=False, path_op
1703
1701
path , pickle_module = pickle_module , ** kwargs )
1704
1702
1705
1703
elif use_openvino :
1706
- if batch_size is None :
1707
- raise ValueError ('Specify valid `batch_size`, used for model inference!' )
1704
+ import openvino as ov
1708
1705
1709
1706
path_openvino = path_openvino or (path + '_openvino' )
1710
1707
if os .path .splitext (path_openvino )[- 1 ] == '' :
@@ -1722,16 +1719,14 @@ def save(self, path, use_onnx=False, path_onnx=None, use_openvino=False, path_op
1722
1719
# Save the rest of parameters
1723
1720
preserved = set (self .PRESERVE ) - set (['model' , 'loss' , 'optimizer' , 'scaler' , 'decay' ])
1724
1721
preserved_dict = {item : getattr (self , item ) for item in preserved }
1725
- out_path_params = f'{ os .path .splitext (path_openvino )[0 ]} _bf_params_db'
1726
-
1727
- with shelve .open (out_path_params ) as params_db :
1728
- params_db .update (preserved_dict )
1722
+ torch .save ({'openvino' : True , 'path_openvino' : path_openvino , ** preserved_dict },
1723
+ path , pickle_module = pickle_module , ** kwargs )
1729
1724
1730
1725
else :
1731
1726
torch .save ({item : getattr (self , item ) for item in self .PRESERVE },
1732
1727
path , pickle_module = pickle_module , ** kwargs )
1733
1728
1734
- def load (self , file , is_openvino = False , make_infrastructure = False , mode = 'eval' , pickle_module = dill , ** kwargs ):
1729
+ def load (self , file , make_infrastructure = False , mode = 'eval' , pickle_module = dill , ** kwargs ):
1735
1730
""" Load a torch model from a file.
1736
1731
1737
1732
If the model was saved in ONNX format (refer to :meth:`.save` for more info), we fix the microbatch size
@@ -1741,8 +1736,6 @@ def load(self, file, is_openvino=False, make_infrastructure=False, mode='eval',
1741
1736
----------
1742
1737
file : str, PathLike, io.Bytes
1743
1738
a file where a model is stored.
1744
- is_openvino : bool, default False
1745
- Whether the load file as openvino model instance.
1746
1739
make_infrastructure : bool
1747
1740
Whether to re-create model loss, optimizer, scaler and decay.
1748
1741
mode : str
@@ -1752,39 +1745,40 @@ def load(self, file, is_openvino=False, make_infrastructure=False, mode='eval',
1752
1745
kwargs : dict
1753
1746
Other keyword arguments, passed directly to :func:`torch.save`.
1754
1747
"""
1755
- self . _parse_devices ( )
1748
+ model_load_kwargs = kwargs . pop ( 'model_load_kwargs' , {} )
1756
1749
1757
- if is_openvino :
1758
- device = kwargs .pop ('device' , None ) or self .device or 'CPU'
1759
- self .device = device .lower ()
1750
+ device = kwargs .pop ('device' , None )
1760
1751
1761
- model = OVModel ( model_path = file , device = device , ** kwargs )
1762
- self .model = model
1752
+ if device is not None :
1753
+ self .device = device
1763
1754
1764
- # Load params
1765
- out_path_params = f' { os . path . splitext ( file )[ 0 ] } _bf_params_db'
1766
- with shelve . open ( out_path_params ) as params_db :
1767
- params = { ** params_db }
1755
+ if ( self . device == 'cpu' ) or (( not isinstance ( self . device , str )) and ( self . device . type == 'cpu' )):
1756
+ self . amp = False
1757
+ else :
1758
+ self . _parse_devices ()
1768
1759
1769
- for key , value in params .items ():
1770
- setattr (self , key , value )
1760
+ kwargs ['map_location' ] = self .device
1771
1761
1772
- self ._loaded_from_openvino = True
1773
- self .disable_training = True
1774
- else :
1775
- kwargs ['map_location' ] = self .device if self .device else 'cpu'
1762
+ # Load items from disk storage and set them as insance attributes
1763
+ checkpoint = torch .load (file , pickle_module = pickle_module , ** kwargs )
1776
1764
1777
- # Load items from disk storage and set them as insance attributes
1778
- checkpoint = torch .load (file , pickle_module = pickle_module , ** kwargs )
1765
+ # `load_config` is a reference to `self.external_config` used to update `config`
1766
+ # It is required since `self.external_config` may be overwritten in the cycle below
1767
+ load_config = self .external_config
1779
1768
1780
- # `load_config` is a reference to `self.external_config` used to update `config`
1781
- # It is required since ` self.external_config` may be overwritten in the cycle below
1782
- load_config = self .external_config
1769
+ for key , value in checkpoint . items ():
1770
+ setattr ( self , key , value )
1771
+ self . config = self .config + load_config
1783
1772
1784
- for key , value in checkpoint .items ():
1785
- setattr (self , key , value )
1786
- self .config = self .config + load_config
1773
+ if 'openvino' in checkpoint :
1774
+ # Load openvino model
1775
+ model = OVModel (model_path = checkpoint ['path_openvino' ], ** model_load_kwargs )
1776
+ self .model = model
1787
1777
1778
+ self ._loaded_from_openvino = True
1779
+ self .disable_training = True
1780
+
1781
+ else :
1788
1782
# Load model from onnx, if needed
1789
1783
if 'onnx' in checkpoint :
1790
1784
try :
@@ -1957,25 +1951,47 @@ def reduce_channels(array, normalize=True, n_components=3):
1957
1951
return compressed_array , explained_variance_ratio
1958
1952
1959
1953
class OVModel :
1960
- def __init__ (self , model_path , core_config = None , device = 'CPU' , compile_config = None ):
1954
+ """ Class-wrapper for openvino models to interact with them through :class:`~.TorchModel` interface.
1955
+
1956
+ Note, openvino models are loaded on 'cpu' only.
1957
+
1958
+ Parameters
1959
+ ----------
1960
+ model_path : str
1961
+ Path to compiled openvino model.
1962
+ core_config : tuple or dict, optional
1963
+ Openvino core properties.
1964
+ If you want set properties globally provide them as tuple: `('CPU', {name: value})`.
1965
+ For local properties just provide `{name: value}` dict.
1966
+ For more, read the documentation:
1967
+ https://docs.openvino.ai/2023.3/openvino_docs_OV_UG_query_api.html#setting-properties-globally
1968
+ compile_config : dict, optional
1969
+ Openvino model compilation config.
1970
+ """
1971
+ def __init__ (self , model_path , core_config = None , compile_config = None ):
1972
+ import openvino as ov
1973
+
1961
1974
core = ov .Core ()
1962
1975
1963
1976
if core_config is not None :
1964
- for name , kwargs_ in core_config .items ():
1965
- core .set_property (name , kwargs_ )
1977
+ if isinstance (core_config , tuple ):
1978
+ core .set_property (core_config [0 ], core_config [1 ])
1979
+ else :
1980
+ core .set_property (core_config )
1966
1981
1967
1982
self .model = core .read_model (model = model_path )
1968
1983
1969
1984
if compile_config is None :
1970
1985
compile_config = {}
1971
- self .model = core .compile_model (self .model , device , config = compile_config )
1986
+
1987
+ self .model = core .compile_model (self .model , 'CPU' , config = compile_config )
1972
1988
1973
1989
def eval (self ):
1974
1990
""" Placeholder for compatibility with :class:`~TorchModel` methods."""
1975
1991
pass
1976
1992
1977
1993
def __call__ (self , input_tensor ):
1978
- """ Evaluate model on provided data. """
1994
+ """ Evaluate model on the provided data. """
1979
1995
results = self .model (input_tensor )
1980
1996
1981
1997
results = torch .from_numpy (results [self .model .output (0 )])
0 commit comments