-
Notifications
You must be signed in to change notification settings - Fork 7.1k
New Feature: add DropBlock layer #5416
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
45 commits
Select commit
Hold shift + click to select a range
c33246e
Create dropblock.py
xiaohu2015 ff34c8e
add dropblock2d
xiaohu2015 2a86d77
fix pylint
xiaohu2015 a90e036
refactor dropblock
xiaohu2015 09f1396
add dropblock
xiaohu2015 f279981
Rename dropblock.py to drop_block.py
xiaohu2015 f8cb184
Merge branch 'pytorch:main' into main
xiaohu2015 ade32f0
fix pylint
xiaohu2015 2f7a10d
add dropblock
xiaohu2015 29edef5
add dropblock3d
xiaohu2015 9969e96
add drop_block3d
xiaohu2015 bb5be85
Merge branch 'main' into main
xiaohu2015 a6900f6
Merge branch 'pytorch:main' into main
xiaohu2015 e5c505e
add dropblock
xiaohu2015 5ba51be
Update drop_block.py
xiaohu2015 2901eff
Update torchvision/ops/drop_block.py
xiaohu2015 90f86f6
Update torchvision/ops/drop_block.py
xiaohu2015 918c979
Update torchvision/ops/drop_block.py
xiaohu2015 77ea0ab
Update torchvision/ops/drop_block.py
xiaohu2015 fefa74e
Update drop_block.py
xiaohu2015 f5b79ee
Update drop_block.py
xiaohu2015 8c84c73
Merge branch 'pytorch:main' into main
xiaohu2015 b45a9e6
import torch.fx
xiaohu2015 c669853
fix lint
xiaohu2015 892f1e5
fix lint
xiaohu2015 7c5e909
Update drop_block.py
xiaohu2015 d06bc24
improve dropblock
xiaohu2015 fdac2f4
add dropblock
xiaohu2015 aedd5f0
refactor dropblock
xiaohu2015 af7305e
fix doc
xiaohu2015 2dd89af
remove the limitation of block_size
xiaohu2015 4f40274
Update torchvision/ops/drop_block.py
xiaohu2015 b1f91e5
fix lint
xiaohu2015 60cf559
fix lint
xiaohu2015 2b3d9cc
add dropblock
xiaohu2015 4019e7a
Fix linter
datumbox df0001a
Merge branch 'main' into main
xiaohu2015 dcf9296
add dropblock random check
xiaohu2015 84cd3dc
reduce test time
xiaohu2015 b159f4d
Update test_ops.py
xiaohu2015 ebea539
speed the dropblock test
xiaohu2015 6ba5147
Merge branch 'main' into main
datumbox 8d89128
fix lint
xiaohu2015 bbb9016
Merge branch 'main' into main
datumbox 2af4162
Merge branch 'main' into main
datumbox File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,155 @@ | ||
import torch | ||
import torch.fx | ||
import torch.nn.functional as F | ||
from torch import nn, Tensor | ||
|
||
from ..utils import _log_api_usage_once | ||
|
||
|
||
def drop_block2d( | ||
input: Tensor, p: float, block_size: int, inplace: bool = False, eps: float = 1e-06, training: bool = True | ||
) -> Tensor: | ||
""" | ||
Implements DropBlock2d from `"DropBlock: A regularization method for convolutional networks" | ||
<https://arxiv.org/abs/1810.12890>`. | ||
|
||
Args: | ||
input (Tensor[N, C, H, W]): The input tensor or 4-dimensions with the first one | ||
being its batch i.e. a batch with ``N`` rows. | ||
p (float): Probability of an element to be dropped. | ||
block_size (int): Size of the block to drop. | ||
inplace (bool): If set to ``True``, will do this operation in-place. Default: ``False``. | ||
eps (float): A value added to the denominator for numerical stability. Default: 1e-6. | ||
training (bool): apply dropblock if is ``True``. Default: ``True``. | ||
|
||
Returns: | ||
Tensor[N, C, H, W]: The randomly zeroed tensor after dropblock. | ||
""" | ||
if not torch.jit.is_scripting() and not torch.jit.is_tracing(): | ||
_log_api_usage_once(drop_block2d) | ||
if p < 0.0 or p > 1.0: | ||
raise ValueError(f"drop probability has to be between 0 and 1, but got {p}.") | ||
if input.ndim != 4: | ||
raise ValueError(f"input should be 4 dimensional. Got {input.ndim} dimensions.") | ||
if not training or p == 0.0: | ||
return input | ||
|
||
N, C, H, W = input.size() | ||
block_size = min(block_size, W, H) | ||
# compute the gamma of Bernoulli distribution | ||
gamma = (p * H * W) / ((block_size ** 2) * ((H - block_size + 1) * (W - block_size + 1))) | ||
noise = torch.empty((N, C, H - block_size + 1, W - block_size + 1), dtype=input.dtype, device=input.device) | ||
noise.bernoulli_(gamma) | ||
|
||
noise = F.pad(noise, [block_size // 2] * 4, value=0) | ||
noise = F.max_pool2d(noise, stride=(1, 1), kernel_size=(block_size, block_size), padding=block_size // 2) | ||
noise = 1 - noise | ||
normalize_scale = noise.numel() / (eps + noise.sum()) | ||
if inplace: | ||
input.mul_(noise).mul_(normalize_scale) | ||
else: | ||
input = input * noise * normalize_scale | ||
return input | ||
|
||
|
||
def drop_block3d( | ||
input: Tensor, p: float, block_size: int, inplace: bool = False, eps: float = 1e-06, training: bool = True | ||
) -> Tensor: | ||
""" | ||
Implements DropBlock3d from `"DropBlock: A regularization method for convolutional networks" | ||
<https://arxiv.org/abs/1810.12890>`. | ||
|
||
Args: | ||
input (Tensor[N, C, D, H, W]): The input tensor or 5-dimensions with the first one | ||
being its batch i.e. a batch with ``N`` rows. | ||
p (float): Probability of an element to be dropped. | ||
block_size (int): Size of the block to drop. | ||
inplace (bool): If set to ``True``, will do this operation in-place. Default: ``False``. | ||
eps (float): A value added to the denominator for numerical stability. Default: 1e-6. | ||
training (bool): apply dropblock if is ``True``. Default: ``True``. | ||
|
||
Returns: | ||
Tensor[N, C, D, H, W]: The randomly zeroed tensor after dropblock. | ||
""" | ||
if not torch.jit.is_scripting() and not torch.jit.is_tracing(): | ||
_log_api_usage_once(drop_block3d) | ||
if p < 0.0 or p > 1.0: | ||
raise ValueError(f"drop probability has to be between 0 and 1, but got {p}.") | ||
if input.ndim != 5: | ||
raise ValueError(f"input should be 5 dimensional. Got {input.ndim} dimensions.") | ||
if not training or p == 0.0: | ||
return input | ||
|
||
N, C, D, H, W = input.size() | ||
block_size = min(block_size, D, H, W) | ||
# compute the gamma of Bernoulli distribution | ||
gamma = (p * D * H * W) / ((block_size ** 3) * ((D - block_size + 1) * (H - block_size + 1) * (W - block_size + 1))) | ||
noise = torch.empty( | ||
(N, C, D - block_size + 1, H - block_size + 1, W - block_size + 1), dtype=input.dtype, device=input.device | ||
) | ||
noise.bernoulli_(gamma) | ||
|
||
noise = F.pad(noise, [block_size // 2] * 6, value=0) | ||
noise = F.max_pool3d( | ||
noise, stride=(1, 1, 1), kernel_size=(block_size, block_size, block_size), padding=block_size // 2 | ||
) | ||
noise = 1 - noise | ||
normalize_scale = noise.numel() / (eps + noise.sum()) | ||
if inplace: | ||
input.mul_(noise).mul_(normalize_scale) | ||
else: | ||
input = input * noise * normalize_scale | ||
return input | ||
|
||
|
||
torch.fx.wrap("drop_block2d") | ||
|
||
|
||
class DropBlock2d(nn.Module): | ||
""" | ||
See :func:`drop_block2d`. | ||
""" | ||
|
||
def __init__(self, p: float, block_size: int, inplace: bool = False, eps: float = 1e-06) -> None: | ||
super().__init__() | ||
|
||
self.p = p | ||
self.block_size = block_size | ||
self.inplace = inplace | ||
self.eps = eps | ||
|
||
def forward(self, input: Tensor) -> Tensor: | ||
""" | ||
Args: | ||
input (Tensor): Input feature map on which some areas will be randomly | ||
dropped. | ||
Returns: | ||
Tensor: The tensor after DropBlock layer. | ||
""" | ||
return drop_block2d(input, self.p, self.block_size, self.inplace, self.eps, self.training) | ||
|
||
def __repr__(self) -> str: | ||
s = f"{self.__class__.__name__}(p={self.p}, block_size={self.block_size}, inplace={self.inplace})" | ||
return s | ||
|
||
|
||
xiaohu2015 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
torch.fx.wrap("drop_block3d") | ||
|
||
|
||
class DropBlock3d(DropBlock2d): | ||
""" | ||
See :func:`drop_block3d`. | ||
""" | ||
|
||
def __init__(self, p: float, block_size: int, inplace: bool = False, eps: float = 1e-06) -> None: | ||
super().__init__(p, block_size, inplace, eps) | ||
|
||
def forward(self, input: Tensor) -> Tensor: | ||
""" | ||
Args: | ||
input (Tensor): Input feature map on which some areas will be randomly | ||
dropped. | ||
Returns: | ||
Tensor: The tensor after DropBlock layer. | ||
""" | ||
return drop_block3d(input, self.p, self.block_size, self.inplace, self.eps, self.training) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.