drop_path.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. # Copyright (c) Meta Platforms, Inc. and affiliates.
  2. # All rights reserved.
  3. #
  4. # This source code is licensed under the license found in the
  5. # LICENSE file in the root directory of this source tree.
  6. # References:
  7. # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
  8. # https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/drop.py
  9. from torch import nn
  10. def drop_path(x, drop_prob: float = 0.0, training: bool = False):
  11. if drop_prob == 0.0 or not training:
  12. return x
  13. keep_prob = 1 - drop_prob
  14. shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
  15. random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
  16. if keep_prob > 0.0:
  17. random_tensor.div_(keep_prob)
  18. output = x * random_tensor
  19. return output
  20. class DropPath(nn.Module):
  21. """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
  22. def __init__(self, drop_prob=None):
  23. super(DropPath, self).__init__()
  24. self.drop_prob = drop_prob
  25. def forward(self, x):
  26. return drop_path(x, self.drop_prob, self.training)