"""DropPath (Stochastic Depth) regularization layers.Modified from timm (https://github.com/huggingface/pytorch-image-models)."""from__future__importannotationsimporttorchfromtorchimportnn
[docs]defdrop_path(x:torch.Tensor,drop_prob:float=0.0,training:bool=False,scale_by_keep:bool=True,)->torch.Tensor:"""Drop path regularizer (Stochastic Depth) per sample. Args: x (torch.Tensor): Input tensor of shape (batch_size, ...). drop_prob (float, optional): Probability of an element to be zeroed. Defaults to 0.0. training (bool, optional): If to apply drop path. Defaults to False. scale_by_keep (bool, optional): If to scale by keep probability. Defaults to True. """ifdrop_prob==0.0ornottraining:returnxkeep_prob=1-drop_probshape=(x.shape[0],)+(1,)*(x.ndim-1)# work with diff dim tensors, not just 2D ConvNetsrandom_tensor=x.new_empty(shape).bernoulli_(keep_prob)ifkeep_prob>0.0andscale_by_keep:random_tensor.div_(keep_prob)returnx*random_tensor
[docs]classDropPath(nn.Module):"""DropPath regularizer (Stochastic Depth) per sample."""def__init__(self,drop_prob:float=0.0,scale_by_keep:bool=True)->None:"""Init DropPath. Args: drop_prob (float, optional): Probability of an item to be masked. Defaults to 0.0. scale_by_keep (bool, optional): If to scale by keep probability. Defaults to True. """super().__init__()self.drop_prob=drop_probself.scale_by_keep=scale_by_keep