importfnmatchimportimportlibimportinspectimportsysfromdataclassesimportdataclassfromenumimportEnumfromfunctoolsimportpartialfrominspectimportsignaturefromtypesimportModuleTypefromtypingimportAny,Callable,Dict,get_args,Iterable,List,Mapping,Optional,Set,Type,TypeVar,Unionfromtorchimportnnfrom.._internally_replaced_utilsimportload_state_dict_from_url__all__=["WeightsEnum","Weights","get_model","get_model_builder","get_model_weights","get_weight","list_models"]@dataclassclassWeights:""" This class is used to group important attributes associated with the pre-trained weights. Args: url (str): The location where we find the weights. transforms (Callable): A callable that constructs the preprocessing method (or validation preset transforms) needed to use the model. The reason we attach a constructor method rather than an already constructed object is because the specific object might have memory and thus we want to delay initialization until needed. meta (Dict[str, Any]): Stores meta-data related to the weights of the model and its configuration. These can be informative attributes (for example the number of parameters/flops, recipe link/methods used in training etc), configuration parameters (for example the `num_classes`) needed to construct the model or important meta-data (for example the `classes` of a classification model) needed to use the model. """url:strtransforms:Callablemeta:Dict[str,Any]def__eq__(self,other:Any)->bool:# We need this custom implementation for correct deep-copy and deserialization behavior.# TL;DR: After the definition of an enum, creating a new instance, i.e. by deep-copying or deserializing it,# involves an equality check against the defined members. Unfortunately, the `transforms` attribute is often# defined with `functools.partial` and `fn = partial(...); assert deepcopy(fn) != fn`. Without custom handling# for it, the check against the defined members would fail and effectively prevent the weights from being# deep-copied or deserialized.# See https://github.com/pytorch/vision/pull/7107 for details.ifnotisinstance(other,Weights):returnNotImplementedifself.url!=other.url:returnFalseifself.meta!=other.meta:returnFalseifisinstance(self.transforms,partial)andisinstance(other.transforms,partial):return(self.transforms.func==other.transforms.funcandself.transforms.args==other.transforms.argsandself.transforms.keywords==other.transforms.keywords)else:returnself.transforms==other.transformsclassWeightsEnum(Enum):""" This class is the parent class of all model weights. Each model building method receives an optional `weights` parameter with its associated pre-trained weights. It inherits from `Enum` and its values should be of type `Weights`. Args: value (Weights): The data class entry with the weight information. """@classmethoddefverify(cls,obj:Any)->Any:ifobjisnotNone:iftype(obj)isstr:obj=cls[obj.replace(cls.__name__+".","")]elifnotisinstance(obj,cls):raiseTypeError(f"Invalid Weight class provided; expected {cls.__name__} but received {obj.__class__.__name__}.")returnobjdefget_state_dict(self,*args:Any,**kwargs:Any)->Mapping[str,Any]:returnload_state_dict_from_url(self.url,*args,**kwargs)def__repr__(self)->str:returnf"{self.__class__.__name__}.{self._name_}"@propertydefurl(self):returnself.value.url@propertydeftransforms(self):returnself.value.transforms@propertydefmeta(self):returnself.value.meta
[docs]defget_weight(name:str)->WeightsEnum:""" Gets the weights enum value by its full name. Example: "ResNet50_Weights.IMAGENET1K_V1" Args: name (str): The name of the weight enum entry. Returns: WeightsEnum: The requested weight enum. """try:enum_name,value_name=name.split(".")exceptValueError:raiseValueError(f"Invalid weight name provided: '{name}'.")base_module_name=".".join(sys.modules[__name__].__name__.split(".")[:-1])base_module=importlib.import_module(base_module_name)model_modules=[base_module]+[x[1]forxininspect.getmembers(base_module,inspect.ismodule)ifx[1].__file__.endswith("__init__.py")# type: ignore[union-attr]]weights_enum=Noneforminmodel_modules:potential_class=m.__dict__.get(enum_name,None)ifpotential_classisnotNoneandissubclass(potential_class,WeightsEnum):weights_enum=potential_classbreakifweights_enumisNone:raiseValueError(f"The weight enum '{enum_name}' for the specific method couldn't be retrieved.")returnweights_enum[value_name]
[docs]defget_model_weights(name:Union[Callable,str])->Type[WeightsEnum]:""" Returns the weights enum class associated to the given model. Args: name (callable or str): The model builder function or the name under which it is registered. Returns: weights_enum (WeightsEnum): The weights enum class associated with the model. """model=get_model_builder(name)ifisinstance(name,str)elsenamereturn_get_enum_from_fn(model)
def_get_enum_from_fn(fn:Callable)->Type[WeightsEnum]:""" Internal method that gets the weight enum of a specific model builder method. Args: fn (Callable): The builder method used to create the model. Returns: WeightsEnum: The requested weight enum. """sig=signature(fn)if"weights"notinsig.parameters:raiseValueError("The method is missing the 'weights' argument.")ann=sig.parameters["weights"].annotationweights_enum=Noneifisinstance(ann,type)andissubclass(ann,WeightsEnum):weights_enum=annelse:# handle cases like Union[Optional, T]fortinget_args(ann):# type: ignore[union-attr]ifisinstance(t,type)andissubclass(t,WeightsEnum):weights_enum=tbreakifweights_enumisNone:raiseValueError("The WeightsEnum class for the specific method couldn't be retrieved. Make sure the typing info is correct.")returnweights_enumM=TypeVar("M",bound=nn.Module)BUILTIN_MODELS={}defregister_model(name:Optional[str]=None)->Callable[[Callable[...,M]],Callable[...,M]]:defwrapper(fn:Callable[...,M])->Callable[...,M]:key=nameifnameisnotNoneelsefn.__name__ifkeyinBUILTIN_MODELS:raiseValueError(f"An entry is already registered under the name '{key}'.")BUILTIN_MODELS[key]=fnreturnfnreturnwrapper
[docs]deflist_models(module:Optional[ModuleType]=None,include:Union[Iterable[str],str,None]=None,exclude:Union[Iterable[str],str,None]=None,)->List[str]:""" Returns a list with the names of registered models. Args: module (ModuleType, optional): The module from which we want to extract the available models. include (str or Iterable[str], optional): Filter(s) for including the models from the set of all models. Filters are passed to `fnmatch <https://docs.python.org/3/library/fnmatch.html>`__ to match Unix shell-style wildcards. In case of many filters, the results is the union of individual filters. exclude (str or Iterable[str], optional): Filter(s) applied after include_filters to remove models. Filter are passed to `fnmatch <https://docs.python.org/3/library/fnmatch.html>`__ to match Unix shell-style wildcards. In case of many filters, the results is removal of all the models that match any individual filter. Returns: models (list): A list with the names of available models. """all_models={kfork,vinBUILTIN_MODELS.items()ifmoduleisNoneorv.__module__.rsplit(".",1)[0]==module.__name__}ifinclude:models:Set[str]=set()ifisinstance(include,str):include=[include]forinclude_filterininclude:models=models|set(fnmatch.filter(all_models,include_filter))else:models=all_modelsifexclude:ifisinstance(exclude,str):exclude=[exclude]forexclude_filterinexclude:models=models-set(fnmatch.filter(all_models,exclude_filter))returnsorted(models)
defget_model_builder(name:str)->Callable[...,nn.Module]:""" Gets the model name and returns the model builder method. Args: name (str): The name under which the model is registered. Returns: fn (Callable): The model builder method. """name=name.lower()try:fn=BUILTIN_MODELS[name]exceptKeyError:raiseValueError(f"Unknown model {name}")returnfn
[docs]defget_model(name:str,**config:Any)->nn.Module:""" Gets the model name and configuration and returns an instantiated model. Args: name (str): The name under which the model is registered. **config (Any): parameters passed to the model builder method. Returns: model (nn.Module): The initialized model. """fn=get_model_builder(name)returnfn(**config)
Docs
Access comprehensive developer documentation for PyTorch
To analyze traffic and optimize your experience, we serve cookies on this site. By clicking or navigating, you agree to allow our usage of cookies. As the current maintainers of this site, Facebook’s Cookies Policy applies. Learn more, including about available controls: Cookies Policy.