Source code for torchvision.models.quantization.shufflenetv2
fromfunctoolsimportpartialfromtypingimportAny,List,Optional,Unionimporttorchimporttorch.nnasnnfromtorchimportTensorfromtorchvision.modelsimportshufflenetv2from...transforms._presetsimportImageClassificationfrom.._apiimportregister_model,Weights,WeightsEnumfrom.._metaimport_IMAGENET_CATEGORIESfrom.._utilsimport_ovewrite_named_param,handle_legacy_interfacefrom..shufflenetv2import(ShuffleNet_V2_X0_5_Weights,ShuffleNet_V2_X1_0_Weights,ShuffleNet_V2_X1_5_Weights,ShuffleNet_V2_X2_0_Weights,)from.utilsimport_fuse_modules,_replace_relu,quantize_model__all__=["QuantizableShuffleNetV2","ShuffleNet_V2_X0_5_QuantizedWeights","ShuffleNet_V2_X1_0_QuantizedWeights","ShuffleNet_V2_X1_5_QuantizedWeights","ShuffleNet_V2_X2_0_QuantizedWeights","shufflenet_v2_x0_5","shufflenet_v2_x1_0","shufflenet_v2_x1_5","shufflenet_v2_x2_0",]classQuantizableInvertedResidual(shufflenetv2.InvertedResidual):def__init__(self,*args:Any,**kwargs:Any)->None:super().__init__(*args,**kwargs)self.cat=nn.quantized.FloatFunctional()defforward(self,x:Tensor)->Tensor:ifself.stride==1:x1,x2=x.chunk(2,dim=1)out=self.cat.cat([x1,self.branch2(x2)],dim=1)else:out=self.cat.cat([self.branch1(x),self.branch2(x)],dim=1)out=shufflenetv2.channel_shuffle(out,2)returnoutclassQuantizableShuffleNetV2(shufflenetv2.ShuffleNetV2):# TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659def__init__(self,*args:Any,**kwargs:Any)->None:super().__init__(*args,inverted_residual=QuantizableInvertedResidual,**kwargs)# type: ignore[misc]self.quant=torch.ao.quantization.QuantStub()self.dequant=torch.ao.quantization.DeQuantStub()defforward(self,x:Tensor)->Tensor:x=self.quant(x)x=self._forward_impl(x)x=self.dequant(x)returnxdeffuse_model(self,is_qat:Optional[bool]=None)->None:r"""Fuse conv/bn/relu modules in shufflenetv2 model Fuse conv+bn+relu/ conv+relu/conv+bn modules to prepare for quantization. Model is modified in place. .. note:: Note that this operation does not change numerics and the model after modification is in floating point """forname,minself._modules.items():ifnamein["conv1","conv5"]andmisnotNone:_fuse_modules(m,[["0","1","2"]],is_qat,inplace=True)forminself.modules():iftype(m)isQuantizableInvertedResidual:iflen(m.branch1._modules.items())>0:_fuse_modules(m.branch1,[["0","1"],["2","3","4"]],is_qat,inplace=True)_fuse_modules(m.branch2,[["0","1","2"],["3","4"],["5","6","7"]],is_qat,inplace=True,)def_shufflenetv2(stages_repeats:List[int],stages_out_channels:List[int],*,weights:Optional[WeightsEnum],progress:bool,quantize:bool,**kwargs:Any,)->QuantizableShuffleNetV2:ifweightsisnotNone:_ovewrite_named_param(kwargs,"num_classes",len(weights.meta["categories"]))if"backend"inweights.meta:_ovewrite_named_param(kwargs,"backend",weights.meta["backend"])backend=kwargs.pop("backend","fbgemm")model=QuantizableShuffleNetV2(stages_repeats,stages_out_channels,**kwargs)_replace_relu(model)ifquantize:quantize_model(model,backend)ifweightsisnotNone:model.load_state_dict(weights.get_state_dict(progress=progress,check_hash=True))returnmodel_COMMON_META={"min_size":(1,1),"categories":_IMAGENET_CATEGORIES,"backend":"fbgemm","recipe":"https://github.com/pytorch/vision/tree/main/references/classification#post-training-quantized-models","_docs":""" These weights were produced by doing Post Training Quantization (eager mode) on top of the unquantized weights listed below. """,}
[docs]@register_model(name="quantized_shufflenet_v2_x0_5")@handle_legacy_interface(weights=("pretrained",lambdakwargs:ShuffleNet_V2_X0_5_QuantizedWeights.IMAGENET1K_FBGEMM_V1ifkwargs.get("quantize",False)elseShuffleNet_V2_X0_5_Weights.IMAGENET1K_V1,))defshufflenet_v2_x0_5(*,weights:Optional[Union[ShuffleNet_V2_X0_5_QuantizedWeights,ShuffleNet_V2_X0_5_Weights]]=None,progress:bool=True,quantize:bool=False,**kwargs:Any,)->QuantizableShuffleNetV2:""" Constructs a ShuffleNetV2 with 0.5x output channels, as described in `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design <https://arxiv.org/abs/1807.11164>`__. .. note:: Note that ``quantize = True`` returns a quantized model with 8 bit weights. Quantized models only support inference and run on CPUs. GPU inference is not yet supported. Args: weights (:class:`~torchvision.models.quantization.ShuffleNet_V2_X0_5_QuantizedWeights` or :class:`~torchvision.models.ShuffleNet_V2_X0_5_Weights`, optional): The pretrained weights for the model. See :class:`~torchvision.models.quantization.ShuffleNet_V2_X0_5_QuantizedWeights` below for more details, and possible values. By default, no pre-trained weights are used. progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. quantize (bool, optional): If True, return a quantized version of the model. Default is False. **kwargs: parameters passed to the ``torchvision.models.quantization.ShuffleNet_V2_X0_5_QuantizedWeights`` base class. Please refer to the `source code <https://github.com/pytorch/vision/blob/main/torchvision/models/quantization/shufflenetv2.py>`_ for more details about this class. .. autoclass:: torchvision.models.quantization.ShuffleNet_V2_X0_5_QuantizedWeights :members: .. autoclass:: torchvision.models.ShuffleNet_V2_X0_5_Weights :members: :noindex: """weights=(ShuffleNet_V2_X0_5_QuantizedWeightsifquantizeelseShuffleNet_V2_X0_5_Weights).verify(weights)return_shufflenetv2([4,8,4],[24,48,96,192,1024],weights=weights,progress=progress,quantize=quantize,**kwargs)
[docs]@register_model(name="quantized_shufflenet_v2_x1_0")@handle_legacy_interface(weights=("pretrained",lambdakwargs:ShuffleNet_V2_X1_0_QuantizedWeights.IMAGENET1K_FBGEMM_V1ifkwargs.get("quantize",False)elseShuffleNet_V2_X1_0_Weights.IMAGENET1K_V1,))defshufflenet_v2_x1_0(*,weights:Optional[Union[ShuffleNet_V2_X1_0_QuantizedWeights,ShuffleNet_V2_X1_0_Weights]]=None,progress:bool=True,quantize:bool=False,**kwargs:Any,)->QuantizableShuffleNetV2:""" Constructs a ShuffleNetV2 with 1.0x output channels, as described in `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design <https://arxiv.org/abs/1807.11164>`__. .. note:: Note that ``quantize = True`` returns a quantized model with 8 bit weights. Quantized models only support inference and run on CPUs. GPU inference is not yet supported. Args: weights (:class:`~torchvision.models.quantization.ShuffleNet_V2_X1_0_QuantizedWeights` or :class:`~torchvision.models.ShuffleNet_V2_X1_0_Weights`, optional): The pretrained weights for the model. See :class:`~torchvision.models.quantization.ShuffleNet_V2_X1_0_QuantizedWeights` below for more details, and possible values. By default, no pre-trained weights are used. progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. quantize (bool, optional): If True, return a quantized version of the model. Default is False. **kwargs: parameters passed to the ``torchvision.models.quantization.ShuffleNet_V2_X1_0_QuantizedWeights`` base class. Please refer to the `source code <https://github.com/pytorch/vision/blob/main/torchvision/models/quantization/shufflenetv2.py>`_ for more details about this class. .. autoclass:: torchvision.models.quantization.ShuffleNet_V2_X1_0_QuantizedWeights :members: .. autoclass:: torchvision.models.ShuffleNet_V2_X1_0_Weights :members: :noindex: """weights=(ShuffleNet_V2_X1_0_QuantizedWeightsifquantizeelseShuffleNet_V2_X1_0_Weights).verify(weights)return_shufflenetv2([4,8,4],[24,116,232,464,1024],weights=weights,progress=progress,quantize=quantize,**kwargs)
[docs]@register_model(name="quantized_shufflenet_v2_x1_5")@handle_legacy_interface(weights=("pretrained",lambdakwargs:ShuffleNet_V2_X1_5_QuantizedWeights.IMAGENET1K_FBGEMM_V1ifkwargs.get("quantize",False)elseShuffleNet_V2_X1_5_Weights.IMAGENET1K_V1,))defshufflenet_v2_x1_5(*,weights:Optional[Union[ShuffleNet_V2_X1_5_QuantizedWeights,ShuffleNet_V2_X1_5_Weights]]=None,progress:bool=True,quantize:bool=False,**kwargs:Any,)->QuantizableShuffleNetV2:""" Constructs a ShuffleNetV2 with 1.5x output channels, as described in `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design <https://arxiv.org/abs/1807.11164>`__. .. note:: Note that ``quantize = True`` returns a quantized model with 8 bit weights. Quantized models only support inference and run on CPUs. GPU inference is not yet supported. Args: weights (:class:`~torchvision.models.quantization.ShuffleNet_V2_X1_5_QuantizedWeights` or :class:`~torchvision.models.ShuffleNet_V2_X1_5_Weights`, optional): The pretrained weights for the model. See :class:`~torchvision.models.quantization.ShuffleNet_V2_X1_5_QuantizedWeights` below for more details, and possible values. By default, no pre-trained weights are used. progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. quantize (bool, optional): If True, return a quantized version of the model. Default is False. **kwargs: parameters passed to the ``torchvision.models.quantization.ShuffleNet_V2_X1_5_QuantizedWeights`` base class. Please refer to the `source code <https://github.com/pytorch/vision/blob/main/torchvision/models/quantization/shufflenetv2.py>`_ for more details about this class. .. autoclass:: torchvision.models.quantization.ShuffleNet_V2_X1_5_QuantizedWeights :members: .. autoclass:: torchvision.models.ShuffleNet_V2_X1_5_Weights :members: :noindex: """weights=(ShuffleNet_V2_X1_5_QuantizedWeightsifquantizeelseShuffleNet_V2_X1_5_Weights).verify(weights)return_shufflenetv2([4,8,4],[24,176,352,704,1024],weights=weights,progress=progress,quantize=quantize,**kwargs)
[docs]@register_model(name="quantized_shufflenet_v2_x2_0")@handle_legacy_interface(weights=("pretrained",lambdakwargs:ShuffleNet_V2_X2_0_QuantizedWeights.IMAGENET1K_FBGEMM_V1ifkwargs.get("quantize",False)elseShuffleNet_V2_X2_0_Weights.IMAGENET1K_V1,))defshufflenet_v2_x2_0(*,weights:Optional[Union[ShuffleNet_V2_X2_0_QuantizedWeights,ShuffleNet_V2_X2_0_Weights]]=None,progress:bool=True,quantize:bool=False,**kwargs:Any,)->QuantizableShuffleNetV2:""" Constructs a ShuffleNetV2 with 2.0x output channels, as described in `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design <https://arxiv.org/abs/1807.11164>`__. .. note:: Note that ``quantize = True`` returns a quantized model with 8 bit weights. Quantized models only support inference and run on CPUs. GPU inference is not yet supported. Args: weights (:class:`~torchvision.models.quantization.ShuffleNet_V2_X2_0_QuantizedWeights` or :class:`~torchvision.models.ShuffleNet_V2_X2_0_Weights`, optional): The pretrained weights for the model. See :class:`~torchvision.models.quantization.ShuffleNet_V2_X2_0_QuantizedWeights` below for more details, and possible values. By default, no pre-trained weights are used. progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. quantize (bool, optional): If True, return a quantized version of the model. Default is False. **kwargs: parameters passed to the ``torchvision.models.quantization.ShuffleNet_V2_X2_0_QuantizedWeights`` base class. Please refer to the `source code <https://github.com/pytorch/vision/blob/main/torchvision/models/quantization/shufflenetv2.py>`_ for more details about this class. .. autoclass:: torchvision.models.quantization.ShuffleNet_V2_X2_0_QuantizedWeights :members: .. autoclass:: torchvision.models.ShuffleNet_V2_X2_0_Weights :members: :noindex: """weights=(ShuffleNet_V2_X2_0_QuantizedWeightsifquantizeelseShuffleNet_V2_X2_0_Weights).verify(weights)return_shufflenetv2([4,8,4],[24,244,488,976,2048],weights=weights,progress=progress,quantize=quantize,**kwargs)
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.